This is my view for User registration:
def user_reg(request):
UserReg = modelformset_factory(UserProfile)
if request.method == 'POST':
formset = UserReg(request.POST)
if formset.is_valid():
formset.save()
return HttpResponseRedirect('/thanks/')
else:
formset = UserReg()
return render_to_response("regform.html",{"formset":formset,})
This is my models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
name = models.CharField(max_length = 100)
reg_no = models.TextField(unique=True)
password = models.CharField(max_length=128)
The error I get is:
Exception Type: DatabaseError at /register/
Exception Value: column auth_userprofile.name does not exist
LINE 1: ..._userprofile"."id", "auth_userprofile"."user_id", "auth_user...
I've two questions here:
1. Obviously, i want to know why I'm getting the error and how to debug.
2. Is this the right way to go about it or should a define it in forms.py and then import it? The model formset I meant. The django documentation showed that this way it can be done.
The error is a database error, you need to add the column "name" to the table "auth_userprofile". I'd highly recommend looking into "South" for all your database schema migration needs.
Related
i am trying to save both FK data as well as tags into same model. FK is the user. user has to submit the question and tags like stack overflow. but i am not able to save both of them. it looks some issue at my views. Can you please help.
ValueError at /qanda/askquestion/
Question objects need to have a primary key value before you can access their tags.
Request Method: POST
Request URL: http://127.0.0.1:8000/qanda/askquestion/
Django Version: 2.2.4
Exception Type: ValueError
Exception Value:
Question objects need to have a primary key value before you can access their tags.
Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/taggit/managers.py in get, line 424
Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7
Python Version: 3.7.4
Python Path:
['/Users/SRIRAMAPADMAPRABHA/Desktop/IampythonDEV/iampython',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/Users/SRIRAMAPADMAPRABHA/Library/Python/3.7/lib/python/site-packages',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']
Models.py
class Question(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
question_number = models.AutoField(primary_key=True)
question_category=models.ForeignKey(Question_Category,related_name='questioncategory',on_delete=models.CASCADE)
question_title=models.CharField(max_length=250)
question_slug = models.SlugField(unique=True, max_length=250)
question_description=RichTextField()
question_tags = TaggableManager()
question_posted_at=models.DateTimeField(default=datetime.now,blank=True)
question_status= models.IntegerField(choices=STATUS, default=1)
question_updated_on= models.DateTimeField(auto_now= True)
def __str__(self):
return self.question_title
views.py
#login_required
def createQuestion(request):
if request.method == 'POST':
form = QuestionAskForm(request.POST)
if form.is_valid():
new_question=form.save(commit=False)
question_title = request.POST['question_title']
new_question.slug = slugify(new_question.question_title)
new_question=request.user
new_question.save()
form.save_m2m()
messages.success(request,'You question is succesfully submitted to the forum')
return redirect('feed')
else:
form = QuestionAskForm()
return render(request,'qanda/askyourquestion.html',{'form':form})
I want to submit both foreign key and as well as tag to the database. I am not able to do the tags. Please let me know your thoughts?
By writing:
new_question=request.user
now new_question is no longer a Question object, but it is simply the User object you use. You should edit the new_question.user object instead. For example with:
#login_required
def createQuestion(request):
if request.method == 'POST':
form = QuestionAskForm(request.POST)
if form.is_valid():
form.instance.slug = slugify(form.instance.question_title)
form.instance.user = request.user
form.save()
messages.success(request,'You question is succesfully submitted to the forum')
return redirect('feed')
else:
form = QuestionAskForm()
return render(request,'qanda/askyourquestion.html',{'form':form})
By using form.instance before saving the form, you prevent having to do the saving process yourself (saving the object and the many-to-many relations).
Note: Normally model fields have no prefix with the name of the model. This makes
queries longer to read, and often want uses inheritance of (abstract) models to
inherit fields, so using a prefix would make it less reusable. Therefore it
might be better to rename your field question_title to title.
Hi everyone I am a beginner in django, building a lodge reservation system with django3.0 and i can't seem to get my modelform to generate a proper queryset to get data in my Reservations model, i keep getting the NameError error message everytime i try enter a new date through my view and right now im not quite sure how to properly solve this error
here is my models.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
now = timezone.now
end = timezone.now() + timezone.timedelta(days=2)
room_choices = [
('single_room', 'Single Room'),
('double_room', 'Double Room'),
('executive_room', 'Executive Room'),
]
class Reservation(models.Model):
room_type = models.CharField(max_length=30, choices=room_choices, default=room_choices[1])
check_in = models.DateField(default=timezone.now)
check_out = models.DateField(default=end)
class Meta:
verbose_name = 'Reservation'
verbose_name_plural = 'Reservations'
I would like to add validation statements later in views.py for price and number of rooms depending on the room_type the user selected so disregard the field for now
here is my forms.py:
from django import forms
from .models import Reservation
class AvailabilityForm(forms.ModelForm):
class Meta:
model = Reservation
fields = [
"room_type",
"check_in",
"check_out",
]
widgets = {
'check_in': forms.DateInput(format='%m/%d/%Y'),
'check_out': forms.DateInput(format='%m/%d/%Y'),
}
If someone knows how to get the widgets to work properly outside of admin, displaying the calender onclick and not not just a charfield with a datefield inside, please also help me fix this problem as well
here is my views.py:
from django.shortcuts import get_object_or_404, render
from datetime import timedelta, date
from django.contrib.auth.models import User
from django.contrib import messages
from . import forms
from .models import Reservation
def availability(request):
form = forms.AvailabilityForm()
reservation = Reservation
if request.method == 'POST':
form = forms.AvailabilityForm(request.POST or None)
if form.is_valid:
reserve = form.save(commit=False)
reserve.reservation = reservation
# check whether the dates are valid
# case 1: a room is booked before the check_in date, and checks out after the requested check_in date
case_1 = Reservation.objects.filter(check_in__lte=reserve.check_in).filter(check_out__gte=check_in)
# case 2: oom is booked before the requested check_out date and check_out date is after requested check_out date
case_2 = Reservation.objects.filter(check_in__lte=check_out, check_out__gte=check_out).exists()
#case3: room is booked in a date which lies between the two requested check-in/check-out dates
case_3 = Reservation.objects.filter(check_in__gte=check_in, check_out__lte=check_out).exists()
# if either of these is true, abort and render the error
if case_1 or case_2 or case_3:
return render(request, "availability.html", {"errors": "This room is not available on your selected dates", "form": form})
# else dates are valid
reserve.save()
messages.add_message(request, messages.SUCCESS, 'Room is available for your stay here')
return redirect("/complete_booking")
return render(request, "availability.html", {"form": form})
i have tried different methods to try get my view to validate the check_in and check_out objects as you can see case1 and case2 use different filtering techniques but neither seem to work, any help would be appreciated as to where i'm going wrong and how to fix it
From the comments, the error is:
File "C:\Users\Karabo\Documents\technocrats2\core\views.py", line 160, in availability
case_1 = Reservation.objects.filter(check_in__lte=check_in).filter(check_out__gte=check_out).exists()
NameError: name 'check_in' is not defined
After checking the traceback, it is clear that you haven't define any check_in variable. You need to define the variable before using it.
check_in = "18-01-2020" # value you want to use in queryset.
case_1 = Reservation.objects.filter(check_in__lte=reserve.check_in).filter(check_out__gte=check_in)
I am trying to retrieve user input data in a django page. But I am unable to choose to multichoice field. I have tried multiple alternatives to no relief.
self.fields['site'].queryset=forms.ModelMultipleChoiceField(queryset=sites.objects.all())
self.fields['site'] = forms.ModelChoiceField(queryset=sites.objects.filter(project_id=project_id))
self.fields['site'].queryset = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=[(p.id, str(p)) for p in sites.objects.filter(project_id=project_id)])
forms.py
class SearchForm(forms.Form):
class Meta:
model= images
fields=['site']
def __init__(self,*args,**kwargs):
project_id = kwargs.pop("project_id") # client is the parameter passed from views.py
super(SearchForm, self).__init__(*args,**kwargs)
self.fields['site'] = forms.ModelChoiceField(queryset=sites.objects.filter(project_id=project_id))
views.py
def site_list(request, project_id):
form = SearchForm(project_id=project_id)
site_list = sites.objects.filter(project__pk=project_id).annotate(num_images=Count('images'))
template = loader.get_template('uvdata/sites.html')
if request.method == "POST":
image_list=[]
form=SearchForm(request.POST,project_id=project_id)
#form=SearchForm(request.POST)
#site_name=request.POST.get('site')
if form.is_valid():
site_name=form.cleaned_data.get('site')
print(site_name)
I expect to get a multiselect field but I end up getting this error:
Exception Value:
'site'
Exception Location: /home/clyde/Downloads/new/automatic_annotator_tool/django_app/search/forms.py in init, line 18
(line 18:self.fields['site'].queryset = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=[(p.id, str(p)) for p in sites.objects.filter(project_id=project_id)]))
You are not defining your form correctly. The documentation shows you how to do this.
In your case it would be something like this:
class SearchForm(forms.Form):
site = forms.ModelMultipleChoiceField(queryset=Sites.object.none())
def __init__(self,*args,**kwargs):
project_id = kwargs.pop("project_id")
super(SearchForm, self).__init__(*args,**kwargs)
self.fields['site'].queryset = Sites.objects.filter(project_id=project_id))
You also appear to be confusing regular Form and ModelForm, as Meta.model is only used in ModelForm whereas you are using a regular Form. I suggest you read up on the difference in the documentation before you proceed.
I am trying to extend the user model using a one to one relationship to a UserProfile model. I added some boolean fields and in the view I am trying to use those fields as permissions.
Here is my model:
class UserProfile(models.Model):
user = models.OneToOneField(User)
FirstName = models.CharField(max_length=25)
LastName = models.CharField(max_length=25)
ProximityAccess = models.BooleanField(default=True)
NewProxAccess = models.BooleanField(default=False)
def __unicode__(self):
return self.user.username
and here is the view I am trying to use:
#login_required
def NewProx(request):
if UserProfile.NewProxAccess:
if request.method == 'POST':
form = ProxForm(request.POST)
if form.is_valid():
ProxPart_instance = form.save(commit=True)
ProxPart_instance.save()
return HttpResponseRedirect('/proximity')
else:
form = ProxForm()
return render(request, 'app/NewProx.html', {'form': form})
else:
raise PermissionDenied
I don't get any error messages but it does not work as intended. I was hoping that if the user profile had NewProxAccess set to False it would raise the PermissionDenied but it doesn't. I have the admin module wired up and I can select or deselect the checkbox for that field but it has no effect. If I comment out the rest I can get it to show the Permission Denied error so it has to be in the view (I think). I think I am missing a line the establishes the logged in user as the user instance so we can check to see if the user has the permission or not. I know there are a ton of ways to do this and there is probably a better way but for the sake of learning, what is it that I am missing for this to work?
Thanks
Scott
As you want to check access for particular profile but not UserProfile model you need to do:
if request.user.userprofile.NewProxAccess:
# your code
As a note: according to PEP8 best practices you should use camelCase only for naming Classes. For attrs, functions use underscore: my_function
I would like to return some custom error messages in save_model function of Django admin page.
class EmployerAdmin(admin.ModelAdmin):
exclude = ('update_user','updatedate','activatedate','activate_user')
def save_model(self, request, obj, form, change):
if obj.department != None and obj.isDepartmentSuggested:
obj.isDepartmentSuggested =False
else:
return "You don't set a valid department. Do you want to continue ?"
obj.update_user = request.user
obj.updatedate = datetime.datetime.now()
obj.save()
Of course, Else part isn't correct but I want to illustrate what I want.
I am glad to suggest me a way or document to do that.
Thanks
You need to use a form to do your validation in your EmployerAdmin:
#forms.py
from your_app.models import Employer
class EmployerAdminForm(forms.ModelForm):
class Meta:
model = Employer
def clean(self):
cleaned_data = self.cleaned_data
department = cleaned_data.get('department')
isDepartmentSuggested = cleaned_data.get('isDepartmentSuggested')
if department == None and not isDepartmentSuggested:
raise forms.ValidationError(u"You haven't set a valid department. Do you want to continue?")
return cleaned_data
#admin.py
from django.contrib import admin
from your_app.forms import EmployerAdminForm
from your_app.models import Employer
class EmployerAdmin(admin.ModelAdmin):
exclude = ('update_user','updatedate','activatedate','activate_user')
form = EmployerAdminForm
admin.site.register(Employer, EmployerAdmin)
Hope that helps you out.
I'm using Django 1.6.3, and I'd like to add to Brandon's answer.
Add admin.site.register(Employer, EmployerAdmin) as a separate line below the EmployerAdmin class; that is, below form = EmployerAdminForm, unindented.
It took me some time to figure out why Brandon's answer wasn't working for me and the validations weren't running, apparently, you just need to register it on admin first.
Cheers.