Hey folks I have my model like :
class Rule(models.Model):
Ruleinfo = models.CharField(max_length=5,null=False)
Ispname = models.CharField(max_length=5,null=False)
priority = models.ForeignKey('Priority',related_name ="priority1")
From = models.IPAddressField(null=True)
To = models.IPAddressField(null=True)
def __unicode__(self):
return u'%s %s %s %s %s %s %s %d' % (self.Ruleinfo, self.Ispname, self.priority,
self.From, self.To)
class Priority(models.Model):
priority = models.IntegerField(null = True)
ispname = models.ForeignKey('Rule' ,related_name="ispname1")
rule = models.ForeignKey('Rule',related_name="rule1")
and here is my forms
class RuleInfoForm(ModelForm):
Ruleinfo = forms.CharField(max_length=5)
Ispname = forms.CharField(max_length=5)
priority = forms.IntegerField()
From = forms.IPAddressField()
To = forms.IPAddressField()
class Meta:
model = Rule
fields = ("Ruleinfo","Ispname","priority","From","To")
I am saving this form in my views as follow
def multiwanrule_info(request):
data = {}
try:
form = RuleInfoForm(request.POST)
except:
pass
if form.is_valid():
rl_frm = form.save(commit=False)
rl_frm.save()
else:
form = RuleInfoForm()
data['form'] = form
return render_to_response('networking.html',data)
But i am getting integrity error i.e
networking_rule.priority_id may not be NULL
why i am getting this error? Why it is not taking automatically like other tables
Your problem lies here:
rl_frm = form.save(commit=False)
rl_frm.save()
Since you don't have null=True in your ForeignKey, a valid foreign key is required; which you have not passed here.
So you should set the ForeignKey to null=True, then probably assign it:
r1_frm.priority.pk = 1 # some primary key to a valid Priority object
r1_frm.save()
Related
I have checked all the solutions related to my question but no one worked, i have an event table in which i am assigning the id of user. Event Model is
class Event(models.Model):
user_id=models.ForeignKey(User, on_delete=models.CASCADE)
event_auth_id=models.CharField(null=True, max_length=225)
event_title=models.CharField(max_length=225)
ticket_title=models.CharField(max_length=225)
category=models.CharField(max_length=50)
event_summary=models.TextField()
event_information=models.TextField()
restriction=models.CharField(max_length=50, default='No Restriction')
artist_image=models.CharField(null=True, max_length=50)
event_poster=models.CharField(null=True, max_length=50)
notification_email=models.CharField(null=True, max_length=50)
notification_frequency=models.CharField(null=True, max_length=15)
name_on_ticket=models.CharField(max_length=225)
event_tnc=models.TextField()
current_step=models.IntegerField(null=True)
event_status=models.BooleanField(default=True)
created=models.DateTimeField(auto_now=True)
modified=models.DateTimeField(auto_now_add=True)
I am assigning the logged in user id from view
def create_new_event(request, steps):
if request.method == 'POST':
if(steps=="step_1"):
stepFirstForm = CreateEventStepFirstForm(request.POST)
if stepFirstForm.is_valid():
eventStepFirst = Event(
user_id = request.user.id,
event_auth_id = uuid4(),
event_title = request.POST['event_title'],
ticket_title = request.POST['ticket_title'],
category = request.POST['categories'],
event_summary = request.POST['event_summary'],
event_information = request.POST['event_information'],
restriction = request.POST['restrictions'],
notification_email = request.POST['notification_email'],
notification_frequency = request.POST['email_frequency']
)
But its giving me error
Cannot assign "42": "Event.user_id" must be a "User" instance.
The problem is in this code:
def create_new_event(request, steps):
if request.method == 'POST':
if(steps=="step_1"):
stepFirstForm = CreateEventStepFirstForm(request.POST)
if stepFirstForm.is_valid():
eventStepFirst = Event(
user_id = request.user.id,
event_auth_id = uuid4(),
event_title = request.POST['event_title'],
ticket_title = request.POST['ticket_title'],
category = request.POST['categories'],
event_summary = request.POST['event_summary'],
event_information = request.POST['event_information'],
restriction = request.POST['restrictions'],
notification_email = request.POST['notification_email'],
notification_frequency = request.POST['email_frequency']
)
In the place of "user_id = request.user.id" You should use "user_id = request.user" or "user_id = request.user.username" because in the field
user_id=models.ForeignKey(User, on_delete=models.CASCADE)
of Event model,you assigned user_id as a foreign key of User model,So user_id field is expecting a User instance,not request.user.id
Thanks.
The ForeignKey field is expecting an object of type User, not the user ID. Try changing the assignment user_id = request.user.id to user_id = request.user. It might also make sense to rename the field to "user" to avoid confusion in the future.
This is my Model class
class SubJobs(models.Model):
id = models.AutoField(primary_key = True)
subjob_name = models.CharField(max_length=32,help_text="Enter subjob name")
subjobtype = models.ForeignKey(SubjobType)
jobstatus = models.ForeignKey(JobStatus, default= None, null=True)
rerun = models.ForeignKey(ReRun,help_text="Rerun")
transfer_method = models.ForeignKey(TransferMethod,help_text="Select transfer method")
priority = models.ForeignKey(Priority,help_text="Select priority")
suitefiles = models.ForeignKey(SuiteFiles,help_text="Suite file",default=None,null=True)
topofiles = models.ForeignKey(TopoFiles,help_text="Topo file",default=None,null=True)
load_image = models.NullBooleanField(default = True,help_text="Load image")
description = models.TextField(help_text="Enter description",null=True) command = models.TextField(help_text="Command",null=True)
run_id = models.IntegerField(help_text="run_id",null=True)
pid_of_run = models.IntegerField(help_text="pid_of_run",null=True)
hold_time = models.IntegerField()
created = models.DateTimeField(default=timezone.now,null=True)
updated = models.DateTimeField(default=timezone.now,null=True)
finished = models.DateTimeField(null=True)
The user might want to update a entry and may choose to update only few fields among these. How do I write a generic update statement that would update only the fields that were passed?
I tried this.
def update_subjob(request):
if (request.method == 'POST'):
subjobs_subjobid = request.POST[('subjob_id')]
post_data = request.POST
if 'subjob_name' in post_data:
subjobs_subjobname = request.POST[('subjob_name')]
if 'subjob_type' in post_data:
subjobs_subjobtype = request.POST[('subjob_type')]
if 'rerun_id' in post_data:
subjobs_rerun_id = request.POST[('rerun_id')]
if 'priority_id' in post_data:
subjobs_priority_id = request.POST[('priority_id')]
if 'transfer_method' in post_data:
subjobs_transfermethod = request.POST[('transfer_method')]
if 'suitefile' in post_data:
subjob_suitefile = request.POST[('suitefile')]
if 'topofile' in post_data:
subjob_topofile = request.POST[('topofile')]
try:
subjobinstance = SubJobs.objects.filter(id=subjobs_subjobid).update(subjob_name=subjobs_subjobname,
updated=datetime.now())
except Exception as e:
print("PROBLEM UPDAING SubJob!!!!")
print(e.message)
How do I write a generic update to update only those fields which are sent in request.POST?
You'd better use Forms. But if you insist on your code it could be done like this.
Suppose you have variable field_to_update where every field that you are waiting in request is listed.
subjobs_subjobid = request.POST[('subjob_id')]
field_to_update = ('subjob_name','subjob_type', 'rerun_id', 'priority_id', 'transfer_method', 'suitefile', 'topofile')
post_data = request.POST
to_be_updated = {field: post_data.get(field) for field in field_to_update if field in post_data}
# then you need to get the object, not filter it
try:
subjobinstance = SubJobs.objects.get(id=subjobs_subjobid)
subjobinstance.update(**to_be_updated, updated=datetime.now())
except ObjectDoesNotExist: # from django.core.exceptions
print('There is no such object') # better to use logger
except Exception as e:
print("PROBLEM UPDAING SubJob!!!!")
print(e.message)
I'd like to append a quoted pots to user's post before saving it.
Here is the view:
#login_required
def quote_reply(request, quote_id):
tform = PostForm()
print 'quote_id is:' + quote_id
quote = Post.objects.get(pk = quote_id)
topic_id = quote.topic_id
topic = Topic.objects.get(id= topic_id)
print 'quote is' + quote.body
args = {}
if request.method == 'POST':
post = PostForm(request.POST)
if post.is_valid():
p = post.save(commit = False)
p.topic = topic
p.title = post.cleaned_data['title']
p.body = post.cleaned_data['body']
p['body'].append(str(quote)) #problematic line
p.creator = request.user
p.user_ip = request.META['REMOTE_ADDR']
if len(p.title)< 1:
p.title=p.body[:60]
p.save()
tid = int(topic_id)
return HttpResponseRedirect('/forum/topic/%s' % topic_id)
else:
args.update(csrf(request))
args['form'] = tform
args['post'] = quote
args['topic_id'] = topic_id
return render_to_response('myforum/qoute_reply.html', args,
context_instance=RequestContext(request))
I tried also tried
p['body'].append(unicode(quote))
but gives the same error.
Appreciate your help to resolve this.
Update: Here is the Post model
class Post(models.Model):
title = models.CharField(max_length=75, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
updated = models.DateTimeField(auto_now=True)
topic = models.ForeignKey(Topic)
body = models.TextField(max_length=10000)
user_ip = models.GenericIPAddressField(blank=True, null=True)
def __unicode__(self):
return u"%s - %s - %s" % (self.creator, self.topic, self.title)
def short(self):
return u"%s - %s\n%s" % (self.creator, self.title, self.created.strftime("%b %d, %I:%M %p"))
short.allow_tags = True
Not sure what to do.
The main problem here is that p is a model instance, which does not support dict-style attribute access syntax. To access the post attribute, use the standard dot syntax, p.post.
The second problem is that you can't use append to change a Unicode or string object - they're immutable. Instead, you should create a new Unicode object containing the content you want and assign that. For instance:
p.post = post.cleaned_data['body'] + unicode(quote)
forms.py
class UserProfileForm(forms.ModelForm):
phone = forms.CharField(max_length = 15,widget = forms.TextInput(attrs = {'placeholder':'Enter mobile no. ','class':''}))
profession = forms.CharField(max_length= 50,widget = forms.Select(choices = PROFESSION_CHOICES,attrs = {'class':''}))
#email = forms.EmailField(label='Email address',max_length = 75,widget = forms.TextInput(attrs={'placeholder':'Email address.','class':''}))
sex = forms.CharField(max_length = 20,label="I am :",widget=forms.Select(choices=SEX_CHOICES,attrs = {'class':''}))
first_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Please enter your real name.','class':''}))
last_name = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter last name.','class':''}))
location = forms.CharField(max_length = 50,widget = forms.TextInput(attrs={'placeholder':'Enter your current location','class':''}))
def clean_first_name(self):
first_name = self.cleaned_data['first_name']
if first_name == '':
raise forms.ValidationError("This field is required.")
return first_name
def save(self,*args,**kw):
self.instance.first_name = self.cleaned_data.get("first_name")
self.instance.last_name = self.cleaned_data.get("last_name")
self.instance.sex = self.cleaned_data.get("sex")
self.instance.location = self.cleaned_data.get("location")
self.instance.profession = self.cleaned_data.get("profession")
self.instance.phone = self.cleaned_data.get("phone")
self.instance.save()
return self.instance
class Meta:
model = User
fields = ('username','first_name','last_name','phone','sex','profession','location')
views.py
def profile(request,nav="profile",template="profile.html",context = {},extra_context = None):
if request.POST:
if 'profileFormSubmit' in request.POST:
pform = UserProfileForm(request.POST,instance = request.user)
if pform.is_valid():
try:
user = pform.save()
return redirect(profile,nav="profile")
except RuntimeError as e:
return HttpResponse(e)
error
The User could not be changed because the data didn't validate.
line
user = super(UserProfileForm,self).save(*args,**kw)
doubt
what changes am i supposed to make to get rid of this error
how am i supposed to change the , i have tried removing all the clean_field form methods , but still getting the same error , please help , thanks in advance.
You are calling save on your form before you clean. And you are calling save twice. Once at the start of the form save. And once at the end.
pform.is_valid() returns a boolean that you never check.
docs on modelforms
The form wasn't validating because I was using 'username' in my meta class of the UserProfileForm, which wasn't supposed to be there.
Hey folks i am getting integrity error while saving my views .Please tell me what i am doing wrong
Here is my django model
class Ruleinfo(models.Model):
rule = models.IntegerField(null=False)
From = models.IPAddressField(null=True)
to = models.IPAddressField(null=True)
priority = models.ForeignKey('Priority',related_name='pri_no')
cisp =models.ForeignKey('Priority',related_name = 'CISP_no')
def __unicode__(self):
return u'%s' %(self.rule)
class Priority(models.Model):
pri = models.IntegerField(null = True)
Ruleno = models.ForeignKey('Ruleinfo',related_name = 'ruleno_no')
CISP = models.IntegerField(null = True)
def __unicode__(self):
return u'%s ' % (self.priority)
My model form is looking like .
class RuleInfoForm(ModelForm):
class Meta:
model = Ruleinfo
fields = ("rule","From","to")
here is my views.py
def multiwanrule_info(request):
data = {}
no_of_isp = MultiWAN.objects.all()
try:
form = RuleInfoForm(request.POST)
except:
pass
print "----------------------------printing form"
print form
if form.is_valid():
rl_frm = form.save(commit=False)
get_priorities = request.POST.getlist('priority')
get_cisp_info = request.POST.getlist('cisp')
rule_object = Ruleinfo()
for get_pri,get_ci in zip(get_priorities,get_cisp_info,):
pri_object = Priority.objects.get_or_create(Ruleno = rule_object)
pri_object.pri = get_pri
pri_object.CISP = get_ci
rl_frm.save()
else:
form = RuleInfoForm()
data['form'] = form
data['number_of_isp'] = no_of_isp
return render_to_response('networking.html',data)
I am getting the above error along this
networking_priority.Ruleno_id may not be NULL
help me out so that i could get back on track .
rule_object = Ruleinfo()
This just instantiates a new model object. It is not saved or assigned values. Since it is not saved it does not have an id value.
assigning your rule_object values: rule, from, to, priority, and cisp values, should fix your problem.