Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add ordering to Case, When conditions in django
There are two fields: start_date and end_date. (DateField). Standard for sorting. Both start_date and end_date are empty values. (start_date = Null, end_date = Null) Start_date Most recently and end_date is empty values (start_date = not null, end_date = Null) If both start_date and end_date have values, end_date most recently (start_date = not Null, end_date = not Null) If both start_date and end_date have values, start_date most recently (start_date = not Null, end_date = not Null) Ex) I want start end 1. null null 2. null null 3. 2021-10-01 null 4. 2021-09-01 null 5. 2021-09-15 21-09-20 6. 2021-09-01 2021-09-20 7. 2021-09-01 2021-09-15 I tried Model.objects.annotate( order1=Case( When(Q(start_date__isnull=True) & Q(end_date__isnull=True), then=0), When(Q(start_date__isnull=False) & Q(end_date__isnull=True), then=1), When(Q(start_date__isnull=False) & Q(end_date__isnull=False), then=2), output_field=IntegerField() ), ).order_by('order1') result start end 1. null null 2. null null 3. 2021-09-01 null # change 3, 4 4. 2021-10-01 null 5. 2021-09-15 21-09-20 6. 2021-09-01 2021-09-20 7. 2021-09-01 2021-09-15 How can I solve the complicated order by in django? -
Django_googleapi_project: AttributeError at /profile Exception Value: 'User' object has no attribute 'userprofile'
I have been following this video to learn django: https://www.youtube.com/watch?v=_vCT42vDfgw. I have followed to the end, have run the server at <localhost port 8000>. I can signup users but when I try to update a user profile (clicking the 'Update User Profile' link in the view, I get an 'AttributeError at/profile' which I have not been able to resolve despite checking in with the tutor's source code (everything looks the same) looking up answers to similar questions on stack overflow here. Any help would be much appreciated...** Here' the error test: <!-- language: lang-none --> Environment: Request Method: GET Request URL: http://localhost:8000/profile Django Version: 3.2.9 Python Version: 3.10.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'users'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Toshiba\Envs\django_googleapi_project\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Toshiba\Envs\django_googleapi_project\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "c:\django_googleapi_project\users\views.py", line 48, in profile_view up = user.userprofile File "C:\Users\Toshiba\Envs\django_googleapi_project\lib\site-packages\django\utils\functional.py", line 247, in inner return func(self._wrapped, *args) Exception Type: AttributeError at /profile Exception Value: 'User' object has no attribute 'userprofile' Here's the code sample in the users\views.py file that contains the 'userprofile' object: from django.shortcuts import render, … -
Sqlite - Django: table has 13 columns but 14 were supplied
I am trying to export a .csv file into my database and the .csv file has 13 columns but for some reason when I try to export it is saying that I have 14 columns instead. I don't know if it is an issue with how I set up the ForeignKey and PrimaryKey but I can't figure this out. models.py class Dealer(models.Model): dealersName = models.TextField(('DealersName')) zipcode = models.CharField(("zipcodex"), max_length = 15) zipcode_2 = models.CharField(("zipCode"), max_length = 15) state = models.CharField(("state"), max_length=5) address = models.TextField(("Address")) ids = models.BigIntegerField(("ids"), primary_key=True) def __str__(self): return self.dealersName class DealershipListing(models.Model): vincode = models.CharField(('vinCode'), max_length=255, primary_key=True) price = models.IntegerField(('price')) msrp = models.IntegerField(('msrp')) mileage = models.TextField(('mileage'), max_length=9) is_new = models.BooleanField(('isNew')) first_seen = models.DateField(("first_seen")) last_seen = models.DateField(("last_seen")) model = models.CharField(("Models"), max_length= 255) make = models.CharField(("Make"), max_length=255) year = models.CharField(("Year"), max_length= 4) ids = models.ForeignKey(Dealer, on_delete=CASCADE) color = models.CharField(("ExtColor"), max_length=255, null=True, blank = True) intcolor = models.CharField(("IntColor"), max_length=255, null=True, blank=True) def __str__(self): return self.year + " " + self.make + " " + self.model and the csv file has vincode,price,msrp,mileage,is_new,first_seen,last_seen,model,make,year,dealerID,ExtColor,IntColor as columns. I would appreciate every help I can get. -
Django Rest Framework API sets image to default image even if user uploads an image
When I try to create a new user through DRF, the avatar field displays the default image even if the user uploads an image. When I try to create a user with an image through the admin panel it works fine. So I'm assuming that I'm missing something in my serializer. Custom User Model class myAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email') if not username: raise ValueError('Users must have an username') user = self.model( email = self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email = self.normalize_email(email), password=password, username=username, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) profileimage = models.ImageField(default='default.jpg') date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = myAccountManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True User serializer UserModel = User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = UserModel.objects.create_user( username=validated_data['username'], password=validated_data['password'], email=validated_data['email'], ) return user class Meta: model = UserModel # Tuple … -
queryset in admin.py never gets executed in django 2.2
My code was originally implemented for Django 1.8 now (after necessary changes) I'm running it with Django 2.2. Seems that the following was planned to show non-super-user only his/her own files: class Tiedostot3Admin(admin.ModelAdmin): fields = ['otsikko', 'kuvaus', 'tiedosto'] list_display = ('otsikko','paivitetty') inlines = [ Liitet3Inline, ] def queryset(self, request): print("queryset, request.user", request.user) qs = super(Tiedostot3Admin, self).queryset(request) if request.user.is_superuser: return qs return qs.filter(owner=request.user) def save_model(self, request, obj, form, change): print("save_model, request.user", request.user) obj.owner = request.user obj.save() When saving new files I can see save_model() executed, but I don't know how to get queryset() executed. It seems that it always shows the same list for all users. models.py: class Tiedostot3(models.Model): otsikko = models.CharField(max_length=250) kuvaus = RichTextField(blank=True) paivitetty = models.DateTimeField(auto_now_add=True, verbose_name="Päivitetty") tiedosto = models.FileField(upload_to='poytakirjat', verbose_name="Tiedosto", blank = True) owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) class Meta: ordering = ['-paivitetty'] verbose_name = "tiedosto" verbose_name_plural="tiedostot" def __unicode__(self): return unicode(self.otsikko) class Liite3(models.Model): otsikko = models.CharField(max_length=250) tiedosto = models.FileField(upload_to='poytakirjat') doku = models.ForeignKey(Tiedostot3, related_name="liitteet", on_delete=models.CASCADE) class Meta: verbose_name_plural="Liitteet" def __unicode__(self): return unicode(self.otsikko) the page: -
change background with Css
I want to change my background site so at first it changed but when I trying to change it again to another color it not happen I link my code file with style.css file with this code {% load static %} style.css (code):in my style.css folder body{ background-color: blue;} first I changed the background to brown then I want to change it to blue but it doesn't change (also when I go to my site it still brown also when I use this code in style.css (body{ background-color: blue} when I click on inspect it appears to me body{ background-color: brown} ) -
Customize Django ListView Pagination
im implementing a Django ListView for a Search View. The search is done using Elasticsearch and django-elasticsearch-dsl. Im actually getting a pagination of just 10 items because thats the amount of contents that Elasticsearh answers by default. I could ask elasticsearch to get all the contents but it would be really unnefficient since im only showing like 50 of them. Is there any way that Django reads the pagination information from other than the queryset? This is what my view looks like: from .elastic import search class SearchView(ListView): template_name = "search/index.html" paginate_by = 50 def get_queryset(self): keyword = self.kwargs['keyword'] lang = get_language() return search(keyword, lang) -
Upgrading Oracle XE from 11g to 21c broke django's ability to talk to TNS Listener
I have an old application that is running django 1.10 with an oracle XE 11g back end. We are trying to upgrade the XE to 21c. The issue is that django cannot find the TNS listener even though it is there and running. sqlplus works correctly so there is no issue with the listener itself. The django application and the XE database are both running on the same server so there is no networking issue. The main change as far as I can tell between the 11g and 21c is that the newer oracle database has plugin databases and needs to be addressed via the easy connect naming mechanism. Is that supported by django 1.10? Directly using cx_Oracle to connect to the database from python3 also works without throwing errors. Any pointers appreciated. -
Add html tag and style on CKEditor Textarea
I'm using django ckeditor, is it possible to add html and css on textarea? Something like this: -
How to track frontend app screens in backend
I have a application with django rest and flutter. In frontend there are 20 screens. Now i want track each screen like if user uninstall app and comeback after 1 year he will able to land on previous screen. So suggest me good approach form backend perspective -
Failed to save in SQLite database django
I have the following codes: models.py class Job(models.Model): jobname = models.CharField(max_length = 1000) owner = models.CharField(max_length = 150) enabled = models.BooleanField() freq_type = models.IntegerField(default = 1) freq_interval = models.IntegerField(default = 0) freq_recurrence = models.IntegerField(default = 0) start_date=models.CharField(max_length=10) end_date=models.CharField(max_length=10, blank = True) start_time=models.CharField(max_length=6) end_time=models.CharField(max_length=6, blank = True) date_added = models.DateTimeField(auto_now_add = True, null = True) date_modified=models.DateTimeField(auto_now = True, null = True) version=models.IntegerField(default = 1) class Job_removed(models.Model): jobname = models.CharField(max_length = 1000) owner = models.CharField(max_length = 150) enabled = models.BooleanField(null = True) freq_type = models.IntegerField(default = 1) freq_interval = models.IntegerField(default = 0) freq_recurrence = models.IntegerField(default = 0) start_date=models.CharField(max_length=10) end_date=models.CharField(max_length=10, blank = True) start_time=models.CharField(max_length=6) end_time=models.CharField(max_length=6, blank = True) date_added = models.DateTimeField(null = True) date_modified=models.DateTimeField(default=timezone.now) version=models.IntegerField(null=True) views.py def job_delete(request,pk): job=Job.objects.get(pk=pk) jobdetail = Job_detail.objects.get(job=pk) if request.method == "POST": jobr = JobRemovedForm(request.POST) if jobr.is_valid(): jobr.jobname = job.jobname print(jobr.jobname) jobr.owner = job.owner print(jobr.owner) jobr.enabled = job.enabled print(jobr.enabled) jobr.start_date = job.start_date print(jobr.start_date) jobr.start_time = job.start_time print(jobr.start_time) jobr.date_added = job.date_added print(jobr.date_added) jobr.version = job.version print(jobr.version) jobr.save() return redirect('/job/', {'job':Job.objects.all}) else: jobr = JobRemovedForm() return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail, 'jobr':jobr}) return render(request, 'interface/job_removed.html', {'job':job, 'jobdetail':jobdetail}) Output of my powershell for those print commands: In the database (SQLite): What I am trying to do is to copy from the entry from … -
Finding median in annotation django
Im using MySQL server as database and need to find median price in query like this: price_query = Product.objects \ .filter(price_query) \ .annotate(dt=Trunc('StartDate', frequency)) \ .values('dt') \ .annotate(avg_price=Avg('Price'), std_price=StdDev('Price'), count=Count('Price'), max_price=Max('Price'), min_price=Min('Price'), median='???') \ .order_by('dt') response is look like this {"date":"2021-05-01T00:00:00Z","avg_price":4326.666666666667,"std_price":20.548046676563168,"min_price":4300.0, "max_price":4350.0,"count":3} Any help is highly appreciated. -
Django - Getting all URLs for folders and subfolders
I am building an image gallery application that does not require a database. The user places a folder containing images and its subfolders into the '/media' directory, and python scripts gather data such as the full path, the name of the directory, the image path/names inside, and the subfolders and their images, it sends this data to the view and it's rendered in the template. The first folders all work, I can access them, see their content, but I can't access the subfolders inside those galleries. I want the url to look something like this but the subfolder part isn't cooperating. website.com/directory/<folder1>/<subfolder>/ The first folder is working with str:data, it displays. pagination works, the images are rendered to the template, but I don't know how to get the urls to work for all subsequent directories. path(r"directory/<str:data>/", views.directory, name="directory"), This is what the code looks like for that right now, I thought slug would be appropriate considering the file names can be a variety of different things. urls.py path(r"directory/album/<slug:item>", views.album, name="album") view.py def directory(req, data): sl = MyClass() dir = data albums = sl.folder_path(data, include_gallery=True) img_list = sl.list_files(dir) paginator = Paginator(img_list, 9) page_number = req.GET.get('page') page_obj = paginator.get_page(page_number) return render(req, "galleries/galleries.html", … -
Where do POST request from a form send the data to in django
Suppose I have created a login page and a register page. both have forms with same name attribute say "username" in the input tag. login page calls views.login function and register page calls views.register function. Now in register page I am submitting a form with some username and saving it in a variable in views.register something like this username = request.POST["username"] views.login too have the same code username = request.POST["username"] My query is where will the username go? only in the views.register function or in views.login function too? -
Using get_model in a custom slug generator raises django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
I created a custom slug generator function to use in multiple models across multiple apps. To achieve this I pass the relevant django app name and django model as string parameters to the function, so the function can check if the slug is unique for that model: def slug_generator(django_app, django_model, field_name, slug_len, prefix=""): unique_pk = False model = apps.get_model(django_app, django_model) while not unique_pk: random_pks = random.sample( string.ascii_uppercase + string.digits + string.ascii_lowercase, slug_len) new_pk = ''.join(random_pks) search_query = {field_name: new_pk} try: if not model.objects.filter(**search_query).exists(): unique_pk = True except: if not model.objects.all().exists(): unique_pk = True return prefix + new_pk called in models.py like so: class Form(models.Model): form_id = models.CharField( max_length=25, default=slug_generator('forms', 'Form', 'form_id', 25)) The function was working fine when I only was using it for a single model (so i wasn't using get_model, I just hard coded the model it was for). Since adding get_model, this error is thrown on startup django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. I tried putting the following before my function: import django django.setup() It only led me to a new error RuntimeError: populate() isn't reentrant, so it makes me think that there is a better way to write the function. Is what I am trying to achieve … -
htmx and django Class Based Views
I was traying to convert the countdown tutorial from here[1] to Class Based Views but I do not know what is missing. [1]https://htmx-django.com/blog/how-to-implement-countdown-timer-in-django-via-htm views.py class TimeDifferenceView(TemplateView): delta = datetime(2022, 12, 1, tzinfo=timezone.utc) - timezone.now() template_name = 'base.html' days = delta.days seconds = delta.seconds % 60 minutes = (delta.seconds //60) % 60 hours = delta.seconds // 3600 def get_context_data(self,*args, **kwargs): # Call the base implementation first to get the context context = super(TimeDifferenceView, self).get_context_data(*args, **kwargs) # Create any data and add it to the context. context['days'] = self.days context['seconds'] = self.seconds context['minutes'] = self.minutes context['hours'] = self.hours return context base.html <div id= "time" class="d-flex justify-content-between" hx-get="{% url 'time_difference' %}" hx-trigger="every 1s" hx-select="#time" hx-swap="outerHTML" > <div> <h5>Days</h5> <p> {{days}} </p> </div> <div> <h5>Hours</h5> <p> {{hours}} </p> </div> <div> <h5>Minutes</h5> <p> {{minutes}} </p> </div> <div> <h5>Seconds</h5> <p> {{seconds}} </p> </div> </div> -
How do I resolve "Invalid service account certificate. Certificate must contain a "type" field set to "service_account"" error to run a Django server?
I'm trying to run a Django server. I have installed python 3.8.2 and the rest of the requirements are installed through a requirements.txt file in the project folder. After installing the requirements, I've tried to run the server but it generates the following error: ValueError('Invalid service account certificate. Certificate must contain a ' ValueError: Invalid service account certificate. Certificate must contain a "type" field set to "service_account". I have tried re-installing python, re-installing the requirements, running it in a virtual environment but nothing has worked so far. It would be really great if someone guides me how to resolve this error and run the server. Error with complete traceback: https://drive.google.com/file/d/1nZdOXKjDgOnd96yJBfhZbWSZ_jdDjTuK/view?usp=sharing Manage.py: https://drive.google.com/file/d/1eXXvy8Jm2GmqmYD0pmG9CJUF-QEYchS-/view?usp=sharing Requirements.txt: https://drive.google.com/file/d/1hOsZrYactHs4nTmfbshPvIV2xAvzuaq4/view?usp=sharing -
Django model override save function raise error if an object is already active
in my Django Model I would like to validate an investment before saving, if this investment has active field value set to true and another investment belonging to the same company is already active then I should raise an error, si business rule is an only one active investment/company : Here is my code : def save(self, *args, **kwargs): if self.active: qs = type(self).objects.filter(active=True).filter(startup=self.startup) # TODO a bug here when unchecking then checking a unique active investment ==> error raised if qs: raise ValidationError(message="An active investment already exists for this startup") super(Investment, self).save(*args, **kwargs) My code seems to work, however i have found a bug in Django admin, in fact if an investment is active and is the only one to be active for that startup, when I uncheck then check again the active box the error is raised although I am not adding an active object neither updating here I am simply clicking on a checkbox twice!! -
How to sent data from contact form to my private gmail in django?
I have contact form on my Django website. I want, when someone fill the form to be sent to my private email. I have tried to do it like this, but it just refresh the page, I don't know what I made wrong. When I google the solution, I get many solutions with email services, but I don't need that, when form is filled, data to be sent to my private mail. What I need to change in my views function? This is contact form! views.py def contact(request): page_title = 'Contact' form = ColorfulContactForm() if request.method == 'GET': form = ColorfulContactForm(request.POST) if form.is_valid(): name = form.cleaned_data["name"] email = form.cleaned_data["email"] message = form.cleaned_data["message"] send_mail = EmailMessage("my.mail@gmail.com", message, to=[email]) return response else: form = ColorfulContactForm() return render(request, 'contact.html', {'page_title':page_title, 'form': form}) forms.py class ColorfulContactForm(forms.Form): name = forms.CharField( max_length=30, widget=forms.TextInput( attrs={ 'style': 'border-color: blue;', 'placeholder': 'Write your name here' } ) ) email = forms.EmailField( max_length=254, widget=forms.TextInput(attrs={'style': 'border-color: green;'}) ) message = forms.CharField( max_length=2000, widget=forms.Textarea(attrs={'style': 'border-color: orange;'}), help_text='Write here your message!' ) -
Can not create db table in django migration
I have 2 apps "app1", "app2" in my django project. When I ran python3 manage.pymakemigrations, I can see ... Migrations for 'app1': ... Migrations for 'app2': ... But when I ran python3 manage.py migrate, I got error saying django.db.utils.ProgrammingError: relation "auth_user" does not exist "auth_user" is db table for app1.User model. I tried to run migrate separately. It is fine for app2. But when I run python3 manage.py migrate app1, I got No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. I cannot find a solution for my case, anyone can help? -
Gmail API with heroku and django project
I am stuck with identyfing issue on application being deployed to Heroku. It is a python django project that using a Gmail API should send out emails to defined subscribers. Code is as below views.py (where function is called) def MailJournals(new_acts): mailAdresses = models.EmailSubscriber.objects.all().values_list('email') mail_list = [x[0] for x in mailAdresses] journal_date = datetime.strftime(datetime.now(), '%d/%m/%Y') message = MIMEText(render_to_string('newsScrapper/mail.html',{ 'journal_date': journal_date, 'new_acts': new_acts, }), 'html') message['to'] = ",".join(mail_list) message['from'] = EMAIL_HOST_USER message['subject'] = 'Official Journal as of ' + journal_date with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp: smtp.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) smtp.send_message(message) settings.py: EMAIL_HOST_USER = env('EMAIL_USERNAME') EMAIL_HOST_PASSWORD = env('EMAIL_PASSWORD') The thing is it perfectly works on localhost so I do not believe this is a code issue. Here are some heroku logs I have extracted for the call of that function: 2021-11-30T21:09:30.657994+00:00 heroku[router]: at=info method=GET path="/home/load/" host=legisync.herokuapp.com request_id=6c5c138d-05a4-488e-8bcd-c0bdc03da7fa fwd="83.23.240.85" dyno=web.1 connect=0ms service=464ms status=302 bytes=259 protocol=https Unfortunately I have no idea how to correctly identify underlying root cause why it does not work from heroku... Any ideas, or if sth else is needed from my side to share pls let me know. -
How to speed up the query transactions for large records in Django, if we are visiting multiple classes to achieve this?
I'm trying to show user profiles suggestion for a loggedIn user based on the tags he/she follows, In my case i have to travel to User_Interests_Tag class to get all the tags, next visit Post_Tag class to get all the posts for each of the tag(loop), once i have the all the postId's, visit the Post class to get each unique user and append it to a profile(List) and used paginator to limit the profiles sent to the client. How can i achieve this without using for loops to increase the overall efficiency and response time from the server? here is the snippet what i want to achieve : #looping through each tag for user_interests_tag in user_interests_tags: #user_post_tags = Post_Tag.objects.in_bulk(user_interests_tags) (used bulk but no luck) user_post_tags.extend(list(Post_Tag.objects.filter(tag_id = user_interests_tag).values_list('post_id', flat=True))) profiles = [] #looping through each tag id for user_post_tag in user_post_tags: #getting the user from post class user = Post.objects.get(id = user_post_tag) #checking if already follows and if already their in user profiles array if user not in profiles and not User_Follow.objects.filter( owner_id = user_id.id, user_id = user.user_id): profiles.append(user) #paginating 6 per request paginator = Paginator(profiles,6) limited_profiles = paginator.page(page) return limited_profiles Any leads very much appreciated, thanks in advance :) -
How to resolve the error: TypeError at /signup save() missing 1 required positional argument: 'self'
I'm trying to register users using AbstractUser but I'm getting an error. Although I'm getting error, users still get registered but I can't handle login with the registered users. The error goes thus: The error goes thus: The post request My views.py goes thus: def signup(request): if request.method == 'POST': first_name = request.POST['first-name'] last_name = request.POST['last-name'] username = request.POST['username'] email = request.POST['email'] phone_no = request.POST['phone-no'] password = request.POST['password'] password2 = request.POST['password2'] if password==password2: if CustomUser.objects.filter(username=username).exists(): messages.info(request, 'Username Taken') return redirect('signup') elif CustomUser.objects.filter(email=email).exists(): messages.info(request, 'Email Already Exist') return redirect('signup') else: CustomUser.objects.create_user(first_name=first_name, last_name=last_name, username=username, email=email, phone_no=phone_no, password=password) CustomUser.save(commit=False) return redirect('login') else: messages.info(request, 'Passwords Not Matching') return redirect('signup') else: return render(request, 'signup.html') And my models.py: class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100, unique=True) email = models.EmailField(unique=True) password = models.CharField(max_length=150) phone_no = models.CharField(max_length=20) is_end_user = models.BooleanField(default=True) is_smart_earner = models.BooleanField(default=False) is_top_user = models.BooleanField(default=False) -
Heroku : Server Error, Status=(500), bytes=403
Everything in the project is working but I only have problem with this request and I dont know what it is. heroku logs: 2021-11-30T19:23:21.705472+00:00 app[web.1]: 10.1.43.186 - - [30/Nov/2021:19:23:21 +0000] "GET /api/player=1/matches HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36" 2021-11-30T19:23:21.707787+00:00 heroku[router]: at=info method=GET path="/api/player=1/matches" host=football-players-stats-api.herokuapp.com request_id=e94d6c13-3fbd-4825-b696-282992be5bc9 fwd="186.58.74.102" dyno=web.1 connect=0ms service=27ms status=500 bytes=403 protocol=https views: class MatchesView(generics.ListAPIView): serializer_class = MatchesSerializer permissions = (IsAuthenticated) def get_queryset(self): player = self.kwargs['player'] return Matches.objects.filter(player=player).all() urls: app_name = 'api' urlpatterns = [ path('',include(router.urls)), path('player=<str:player>/matches',views.MatchesView) ] -
Why does my Django form not raise Validation Error?
I read through most SO cases regarding this issue but all are kind of specific, so I come here for help. I have impelemented a range filter in my Django project that takes in two inputs set to a low bound and high bound value, and displays the range of data within those bounds. What I'm trying to do, is make it so when a user inputs a higher number in the low bound than the high bound value, a ValidationError is raised for the user to see on the front end, and results are not displayed. I am a bit new to working with Django forms, but I can supply my code, and maybe someone could provide a solution forms.py class PlayerForm(forms.Form): # player forms points_high = forms.IntegerField(validators = [MinValueValidator(0)], min_value=0, label = 'Reviews', required = False, widget = forms.NumberInput( attrs={'id': 'pointsHigh', 'name': 'pointsHigh', 'href': '#', 'value': '', 'class': "form-control"})) points_low = forms.IntegerField(validators = [MinValueValidator(0)], min_value=0, required = False, widget = forms.NumberInput( attrs={'id': 'pointsLow', 'name': 'pointsLow', 'href': '#', 'value': '', 'class': "form-control"})) def check_bounds(self): """custom validation to check if low bound value is higher than high bound value""" data = self.cleaned_data player_low = data['player_low'] player_high = data['player_high'] if player_low …