Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Access Model Values in Another Model
I am new on Django and I have some issues about Rest API. I want to access User Model Values from Project Model. I have User JSON like this: [ { "id": 15, "first_name": "Ebrar", "last_name": "Bilgili", "university": "Bahçeşehir University", "faculty": "Software Engineering", "user": 17 }, ] And also I have Project JSON like this: { "id": 4, "title": "teammate", "city": "istanbul", "user": 17, "user_profile": 15 } But I want to access User First name, Last name, University and Faculty values in Project JSON like this: { "id": 4, "title": "teammate", "city": "istanbul", "user": 17, "user_profile": { "first_name": "Ebrar", "last_name": "Bilgili", "university": "Bahçeşehir University", "faculty": "Software Engineering", } } I have many researched but I could not find any solution. I searched all the methods that came to my mind.. I hope you help me. Thanks. -
Django admin served with gunicorn displays without styling at all
I have a Django application served with Unicorn, and I can reach the application through the IP, but Django Admin (and all other django views) looses all the styling: I followed this tutorial to make the deployment, and this is my settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_DIR = os.path.join(BASE_DIR, 'media/') STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = '/vol/web/media' LOCALE = "es_MX" I can't find what I can be doing wrong. -
URL tracking with the presence of GET parameters
I send a request to the site with GET parameters response = requests.get(f'http://localhost/botcontact&phonenumber={phonenumber}&user_id={user_id}') Tracking in urls.py path('botcontact/', views.botcontact) I get the error Not Found: / botcontact&phonenumber=+79162321578&user_id=228695396 How to make GET parameters not taken into account in urls.py and it could be tracked via path ('botcontact/', views.botcontact)? In this case, GET parameters must be obtained in the function -
Django create ContentType in only one database
I am having a Django project with two apps. One is a custom Auth1 app and other is the main app. I have two databases, one for each app with respective routers but I am not able to migrate. The below error occurs: (venv) D:\Languages\Python\DMS\void>manage.py migrate --database=Auth1 Operations to perform: Apply all migrations: admin, auth, contenttypes, cred, sessions Running migrations: No migrations to apply. Traceback (most recent call last): File "D:\Languages\Python\DMS\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: django_content_type The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Languages\Python\DMS\void\manage.py", line 22, in <module> main() File "D:\Languages\Python\DMS\void\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_l ine utility.execute() File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\commands\migrate.py", line 268, in handle emit_post_migrate_signal( File "D:\Languages\Python\DMS\venv\lib\site-packages\django\core\management\sql.py", line 42, in emit_post_migrate_signal models.signals.post_migrate.send( File "D:\Languages\Python\DMS\venv\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send return [ File "D:\Languages\Python\DMS\venv\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "D:\Languages\Python\DMS\venv\lib\site-packages\django\contrib\auth\management\__init__.py", … -
Django Get Returns More then one value
hello im new to django i am making a blog site i am getting an error when i try to acces my blog my code: views.py: from django.http import request from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import Item, Blog # Create your views here. class BlogView(ListView): model = Blog template_name = "main/blog.html" context_object_name = "blog" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) search_input = self.request.GET.get('search') or '' if search_input: context['blog'] = context['blog'].filter(title__icontains=search_input) return context class Detail(DetailView): model = Item template_name = "main/item.html" context_object_name = "items" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) obj = Item.objects.get() context['items'] = Item.objects.filter(blog_id=obj.blog_id) return context models.py: from django.db import models # Create your models here. class Blog(models.Model): title = models.CharField(max_length=200) image = models.ImageField(null=True, blank=True) created = models.DateField(auto_now_add=True, null=True) def __str__(self): return self.title class Meta: ordering = ['created'] @property def imageURL(self): try: url = self.image.url except: url = "" return url class Item(models.Model): title = models.CharField(max_length=200) description = models.TextField(max_length=1000) image = models.ImageField(null=True, blank=True) blog = models.ForeignKey(Blog, on_delete=models.CASCADE) def __str__(self): return self.title @property def imageURL(self): try: url = self.image.url except: url = "" return url any help would be appreciated on this error:MultipleObjectsReturned at /detail/2/ get() returned more than one Item … -
CreateView TestCase doesn't create an object
I have a simple CreateView for Hub objects, allowing users to create hubs. It works perfectly on local server but the TestCase fails. class HubTestCase(TestCase): def setUp(self): User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword') def test_create_hub(self): u = User.objects.get(username='john') self.client.force_login(u) response = self.client.post('/hub/create-hub/', {'mydata': 'somedata'}) self.assertEqual(Hub.objects.count(), 1) self.assertEqual(Hub.objects.count(), 1) AssertionError: 0 != 1 class CreateHubView(LoginRequiredMixin, CreateView): model = Hub form_class = HubModelForm template_name = 'hub/hub_form.html' success_url = '/' /hub/create-hub/ is the correct url. -
Django - how to copy one, specific model instance between two databases
I have an application that has a model called CalculationResults. I also have two databases with the same scheme - let's call them "source" and "target". On source database, I have a specific instance of CalculationResults that I want to migrate to "target" database - preferably, I also want to change the field "owner" of this instance in the process. What is the easiest way to achieve this goal? The data I'm talking about is not huge, so it's rather a question of manpower vs computational power. -
Use builtin-lookups in subclasses of a Django builtin-field in Python
While subclassing Django's IntegerField class I stumbled across the fact that the builtin lookups, like eq, gt, le, are not available for my subclassed field. from django.db.models import IntegerField class FooField(IntegerField): pass a = IntegerField() b = FooField() Do I need to register the lookups from the Django sources manually or is there a workaround to have the parent's field lookups in the derived class as well? -
Handling multiple Foreign keys from mutiple models in django
I have my parishioner model like below (Only pasting relevant CODE) class Parishioner(models.Model): family = models.ForeignKey(Family, null=True, on_delete=models.PROTECT, related_name='members') role = models.ForeignKey(FamilyRole, null=True, blank=True, on_delete=models.PROTECT, related_name='role') Parishioner can have one Family and One role in that family So I'm trying to achieve this in my Family Serializer. class FamilySerializer(serializers.ModelSerializer): members = serializers.PrimaryKeyRelatedField( many=True, queryset=Parishioner.objects.all(), allow_null=True, required=False ) role = serializers.PrimaryKeyRelatedField( many=True, queryset=FamilyRole.objects.all(), allow_null=True, required=False ) class Meta: model = Family fields = ('id', 'name', 'address', 'monthly_contribution', 'members', 'role', 'enabled') read_only_fields = ('id',) depth = 1 Basically What I'm trying to do is When I add family I can add members(Parishioners) to that family and assign a role each member. What am I doing wrong here ? because when I load my api/family/ I'm getting below error 'Family' object has no attribute 'role' But you can clearly see I added related_name='role' in my Parishioner model. So how can I achieve what I want ? I want to add members(Parishioners) to Family and asssign Role to each member in that Family. Examples for FamilyRole: Father, Mother, son, daughter -
Django 3 test to catch ValidationError is not recognising the raised error
I'm struggling to get my Django test to succeed. The test file is as follows, I've kept it as simple as I can: from django.test import TestCase from django.core.exceptions import ValidationError from .models import Reporter class NewReporterTests(TestCase): def test_reporter_name_should_not_be_empty(self): """ Checking new reporter name cannot be empty and raises validation error correctly """ blank_reporter = Reporter(full_name="") self.assertRaises(ValidationError, blank_reporter.save()) The code which is firing the exception is in the data model as follows: class Reporter(models.Model): uuid = models.UUIDField(default = uuid.uuid4, editable = False, unique=True) full_name = models.CharField(max_length=70) def save(self, *args, **kwargs): if self.full_name == '': raise ValidationError('full_name is empty and is not allowed to be') super(Reporter, self).save(*args, **kwargs) def __str__(self): return self.full_name The output from python manage.py test is: ====================================================================== ERROR: test_reporter_name_should_not_be_empty (gallery.tests.NewReporterTests) Checking new reporter name cannot be empty and raises validation error correctly ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/james/repos/django_play/gallery/tests.py", line 14, in test_reporter_name_should_not_be_empty self.assertRaises(ValidationError, blank_reporter.save()) File "/home/james/repos/django_play/gallery/models.py", line 17, in save raise ValidationError('full_name is empty and is not allowed to be') django.core.exceptions.ValidationError: ['full_name is empty and is not allowed to be'] ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (errors=1) Destroying test database for alias 'default'... So the test is creating a new reporter with a blank user … -
Use value from one form as value for another form in redirected template (Django)
I have two models def CarModel(models.Model): type = models.CharField() price = models.FloatField() img = models.URLfield() def WrongCar(models.Model): wrong_type = models.CharField() correct_type = models.CharField() price = models.FloatField() I have a product-list of, say, cars using the CarModel but if a car is classified wrong, the user should be able to correct it by filling out the fields in WrongCar by clicking on a button called "correct type", then the user is redirected to the wrong_car-template where the fields from WrongCar are such they can be filled out. When that happens, wrong_type should then automatically be filled out with the value type from the CarModel such that the user only should fill in correct_type and price. I think I can extract it from the request object, but I really dont have any idea of how to do so. -
Django migrations on gitlab CI/CD creates the same 0001_initial.py every time
I've configured GitLab CI/CD for my project. Suppose that I have a model named News and I want to add a new field named 'yyy' to it: class News(models.Model): title = models.CharField(max_length=200, verbose_name="News Title") description = models.TextField(verbose_name="Description") yyy = models.CharField(max_length=10, blank=True, null=True) # New field And my .gitlab-ci.yml file is like this: stages: - build build: stage: build script: - source /path-to-my-project/venv/bin/activate - cd /path-to-my-project/ - python3 manage.py makemigrations news - python3 manage.py migrate news Every time I add a new field to any table and push the changes, gitlab-ci creates the same 0001_initial.py file and I see this message on GitLab CI/CD console: This causes some inconsistent errors ( for example when I want to add a foreign-key field to the model ). A change that I did on GitLab CI configuration was that I changed Git strategy on the General pipelines section from git fetch to git clone and set the Git shallow clone to 0. Settings -> CI/CD -> General pipelines How can I fix this? Thank you -
Django how to restrict staff-user to edit or delete others staff-user post
Right now my all django staff-user can edit or delete others staff-user post. I want they only can able to be edit or delete their own post. How to restrict them to edit or delete others people post? here is my code: views.py: class BlogPublishView(PermissionRequiredMixin,CreateView): raise_exception = True permission_required = "blog.add_post" model = Post form_class = BlogPost template_name = "blog_post.html" #fields = ['title','author','body'] class BlogUpdateView(PermissionRequiredMixin,UpdateView): raise_exception = True permission_required = "blog.change_post" model = Post template_name = "blog_update_post.html" form_class = BlogPost class BlogDeleteView(PermissionRequiredMixin,DeleteView): raise_exception = True permission_required = "blog.delete_post" model = Post template_name = "delete_blog_post.html" success_url = reverse_lazy('blog') urls.py path('blog-post', BlogPublishView.as_view(), name='blog-post'), path('blog-update/<slug:slug>', BlogUpdateView.as_view(), name='blog-update'), path('blog-delete/<slug:slug>', BlogDeleteView.as_view(), name='blog-delete'), html {% if user.is_authenticated %}{% if user.id == post.author.id %} <a href="{% url 'blog-update' post.slug %}"><b>(Edit Blog)</b></a>&nbsp;<a href="{% url 'blog-delete' post.slug %}"><b>(Delete Blog)</b> </a>{% endif %}{% endif %} Let you explain little bit more if you still now don't understand my problem. Assume I have three user in my djano admin panel "A", "B" and "C". user "A" is Admin and user "B" and "C" is staff-user. User "B" and "C" have permission only edit, delete and publish post from admin panel. The problem is user "A" can edit and delete user "B" … -
Django QuerySet filter on inverse relationship
Really struggling with this one and could appreciate some help. I have the following model... class Booking(models.Model): property = models.ForeignKey(Property, related_name='booking', on_delete=models.SET_NULL, null=True) check_in_date = models.DateField() check_out_date = models.DateField() def __str__(self): return f"{self.property}" class Property(models.Model): name = models.CharField(max_length=100, blank = False) def __str__(self): return f"{self.name}" But when I run the following (below) to retrieve property bookings with a date equal to 2021-05-14, instead of just the bookings with a check_in_date of 2021-05-14 being returned, all the bookings for each property are returned even if they don't have a check_in_date of 2021-05-14 Property.objects.filter(booking__check_in_date='2021-05-14') Probably something really simple, but I'm new to Django have been stuck on this all morning and could appreciate some help. Thanks -
How to handle receiving duplicate and out of order webhook events in Django
I am interfacing with some systems that have webhooks set up where they push new and updated events to my Django system. I have the endpoints set up (REST based) and I can receive the incoming data. However, with some of the interfaces, they say that events can come out of order (within a 60 second window), and there can also be duplicate events. Out of order events can be detected by checking the "modified" timestamp in the incoming message, and duplicate messages can be detected by checking the eventId (which is unique). These issues seem to be fairly common with data sent from external systems via webhooks, so before I start architecting and writing something to handle this, is there an existing module/package/best practices for dealing with this within Django? Thanks. -
Django doesn't receive cookies from request
I'm working on a Nuxt/Vue app that uses Django on the backend. I'm using the standard Django Session authentication. The problem with my code is that the user's are always logged out, according to Django, because Django doesn't see any cookie in the request. Basically i created an API endpoin that should return whether or not the user is authenticated, but since Django doesn't see any sessionid cookie in the request, the user will always be unauthenticated to the backend. def checkAuth(request): print(request.COOKIES) response = {'state': str(request.user.is_authenticated), 'username': str(request.user)} return JsonResponse(response, safe=False) If i print request.COOKIES it returns {}. Here is how i send the request from the frontend, where i'm using Axios: return axios({ method: 'get', url: 'http://127.0.0.1:8000/checkAuth', withCredentials: true, }).then(function (response) { console.log(response) }).catch(function (error) { console.log(error) }); The problem should not be from the frontend, since on Chrome i can see the session cookie and the csrf cookie correctly. I already tried to disable any possible CORS security setting on Django. The frontend is running on 127.0.0.1:3000 and the Django app on 127.0.0.1:8000. Why doesn't Django see the cookies? Any kind of advice is appreciated -
Django site suddenly requiring users to clear their cookies to get a CSRF token
I run a Django site that hasn't undergone any updates in the last few months, yet all of a sudden I'm receiving a bunch of emails from users saying they're getting the following error: CSRF Failed: CSRF cookie not set. The bizarre thing is that refreshing the page does not fix the issue. The only way to resolve it is to have them manually clear their browser's cookies. Bear in mind that they are still logged in after refreshing. So even though they aren't getting a CSRF cookie, Django is acknowledging their session. While I'm glad they can clear their cookies to fix it, it's concerning to me as I can't fathom what is happening. It started happening around the same time that iOS 14.5 came out, so I initially thought it may somehow be related to that, but I just received a report from an Android user. Has anyone run into this before? Is there any way to resolve this without putting a banner on the site explaining to clear cookies if you see the error? Thanks! -
How to do custom error messages in Django Forms
I want to make custom error messages for my InstellingenForm, but no matter what I do, I keep getting the browser's standard error messages. The error messages that should be displayed can be seen in choicefield_errors and charfield_errors. Am I missing something cause I feel like it should be working. I want the error messages to be displayed in red above the concerned input field, right next to the label. At the bottom of the page, I put a few pictures of how it looks now. views.py: def instellingenDatabase(request): if request.method == "POST": form = InstellingenForm(request.POST) if form.is_valid(): request.session['data'] = request.POST spelmodus = request.POST.get('spelmodus') if spelmodus == 'woorden': return redirect('speelscherm-woorden') else: return redirect('speelscherm-tijd') else: form = InstellingenForm() return render(request, 'instellingenDatabase.html', {'formulier': form}) forms.py: from django import forms SPELMODUS = [ ('', ''), ('tijd', 'Tijd'), ('woorden', 'Woorden'), ] TIJD = [ ('', ''), ('60', '1 minuut'), ('120', '2 minuten'), ('300', '5 minuten'), ] WOORDEN = [ ('', ''), ('50', '50 woorden'), ('100', '100 woorden'), ('150', '150 woorden'), ] TALEN = [ ('', ''), ('nederlands', 'Nederlands'), ('engels', 'Engels'), ] MOEILIJKHEID = [ ('', ''), ('makkelijk', 'Makkelijk'), ('gemiddeld', 'Gemiddeld'), ('moeilijk', 'Moeilijk'), ] charfield_errors = { 'required': 'Dit veld is verplicht en mag alleen … -
NoReverseMatch at 'url' in Django, Reverse for 'my_app' not found. 'my_app' is not a valid view function or pattern name
I'm new to Django, and today when I tried to run a website with a database, I have encountered this error. I have searched for all solutions on StackOverflow and Django documents, but I can not fix it. This is the problem that similar to me, but it doesn't work. I want to create a link that moves user from user.html in user to index.html in citizens Here is my project structure. I'm sorry because I can't attach an image, so I will try to explain it in easiest way. [MYPROJECT] ->manage.py ->citizens (folder) -->templates (inside this folder I have citizen.html, index.html, layout.html) -->admin.py -->models.py -->tests.py -->urls.py -->views.py ->myproject (folder) -->setting.py -->urls.py -->etc that I think not important ->user (folder) -->templates (inside this folder I have login.html, user.html, layout.html) -->urls.py -->views.py -->etc that I think not important As you can see, I have user.html inside templates folder of user, and index.html inside templates folder of citizens. Here is my code: index.html inside citizens {% extends "citizens/layout.html" %} {% block body %} <h1>Hệ thống quản lý XNC</h1> <table class="table"> <thead> <tr> <th scope="col">Số TT</th> <th scope="col">Họ và tên công dân</th> <th scope="col">Giới tính</th> <th scope="col">Số Hộ chiếu</th> <th scope="col">Chi tiết</th> </tr> … -
Ajax is not sending selected items to django views
I am quite new to Django so bare with me. I'm working on a Django view where I upload a dataframe and the user has a dropdown list to select the target variable. The problem I'm facing is that I can't fetch the selected item on my views: def profile_upload(request): template = "profile_upload.html" my_class = MyClass() if request.method == "GET": prompt = {'order': 'First Page'} return render(request, template, prompt) if request.method == 'POST': csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') df = pd.read_csv(csv_file) my_class.df=df head = df.head(n=5) head = head.to_html(classes='table table-striped') thrsh = 0.1 dataframe_stats = utils.DfStats(df,thrsh) df_stats = dataframe_stats.get_df_stats() cat_cols,num_cols = dataframe_stats.get_type_var() my_class.quali_col = cat_cols my_class.quanti_col = num_cols dtype_counts = {"Variables qualitatives: ": len(cat_cols), "Variables quantitatives: ": len(num_cols)} context = {'table': head, 'stats': df_stats, "dtypes": dtype_counts, 'vars': df.columns} return render(request, template, context) if request.is_ajax() and request.method== "POST" : data = request.POST.get['mydata'] my_class.target_var = data return HttpResponse('<h1> Page was found</h1>') The views above work fine but the last if statement is not executed I don't know where things go wrong. Here is the dropdown script <label for="tar_col"> Select target variable <select class="js-example-basic-single js-states form-control" id="tar_col" name="tar_col" title="tar_col" style="width: 50%"> {% for col in vars … -
Django Bootstrap module in ubuntu
So deploying my django app into an unbuntu 20.04 with apache. I've got everything worked out(mostly). The latest kink is bootstrap. Now when I run the app through the built in django web server, it works beautifully. But when I try through apache, it gives an error that it can't find bootstrap: Error I've verified the syntax is right in my HTML files as that is the most common issue via google. I thought maybe apache needed to have jquery installed, which I did sudo apt-get install libjs-jquery to get installed but that did not resolve the issue. So any help would be appreciated. -
I want to create Django and React Music App but spotify api seem to not working for I tried with vpn too but no response
why spotify api doesn't response back this my view.py file from django.shortcuts import render, redirect from .credentials import REDIRECT_URI, CLIENT_ID, CLIENT_SECRET from rest_framework.views import APIView from requests import Request, post from rest_framework import status from rest_framework.response import Response from .util import * from api.models import Room class AuthURL(APIView): def get(self, request, format=None): # what information we want to access are scopes scopes = 'user-read-playback-state user-modify-playback-state user-read-currently-playing' url = Request('GET', 'https://accounts.spotify.com/authorize', params={ 'scope': scopes, 'response_type': 'code', 'redirect_uri': REDIRECT_URI, 'client_id': CLIENT_ID }).prepare().url return Response({'url': url}, status=status.HTTP_200_OK) def spotify_callback(request, format=None): code = request.GET.get('code') error = request.GET.get('error') response = post('https://accounts.spotify.com/api/token', data={ 'grant_type': 'authorization_code', 'code': code, 'redirect_uri': REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET }).json() access_token = response.get('access_token') token_type = response.get('token_type') refresh_token = response.get('refresh_token') expires_in = response.get('expires_in') error = response.get('error') if not request.session.exists(request.session.session_key): request.session.create() update_or_create_user_tokens(request.session.session_key, access_token, token_type, expires_in, refresh_token) return redirect('frontend:') class IsAuthenticated(APIView): def get(self, request, format=None): is_authenticated = is_spotify_authenticated(self.request.session.session_key) return Response({'status': is_authenticated}, status=status.HTTP_200_OK) class CurrentSong(APIView): def get(self, request, format=None): room_code = self.request.session.get('room_code') room = Room.objects.filter(code=room_code) if room.exists(): room = room[0] else: return Response({}, status=status.HTTP_404_NOT_FOUND) host = room.host endpoint = 'player/currently-playing' response = execute_spotify_api_request(host, endpoint) if 'error' in response or 'item' not in response: return Response({}, status=status.HTTP_204_NO_CONTENT) item = response.get('item') duration = item.get('duration_ms') progress = item.get('progress_ms') album_cover … -
(Django) Validation Forms in class based View doesn't work
I've created a view where user can sign up that use form with validation functions. However, those functions don't work. class SignUpPage(View): def get(self, request): form = SignUpForm() return render(request, "signup.html", {'form': form}) def post(self, request): form = SignUpForm(request.POST or None) if form.is_valid(): redirect('/signup') else: form = SignUpForm() ctx = {"form": form} return render(request, "signup.html", ctx) The form: class SignUpForm(forms.Form): first_name = forms.CharField(max_length=32, required=True) last_name = forms.CharField(max_length=32, required=True) username = forms.CharField(max_length=32, required=True) email = forms.CharField(label="email") password1 = forms.CharField(label="Password", max_length=32, widget=forms.PasswordInput(attrs={'class': 'password'})) password2 = forms.CharField(label="Password Again", max_length=32, widget=forms.PasswordInput(attrs={'class': 'password'})) date_of_birth = forms.DateField(label="Date of birth", required=True, widget=forms.SelectDateWidget(years=YEARS, attrs={'class': 'date-select'})) def validate_email(self): data = self.cleaned_data.get('email') if User.objects.filter(email=data).exists(): raise forms.ValidationError("This email is already registered") return data def validate_age(self): user_date = str(self.cleaned_data['date_of_birth']) year = int(user_date[0:4]) month = int(user_date[5:7]) day = int(user_date[8:10]) today = dt.today() if int(today.year) - year < 18: raise forms.ValidationError("You must be 18 years old to have an account") elif int(today.year) - year == 18 and int(today.month) - month < 0: raise forms.ValidationError("You must be 18 years old to have an account") elif int(today.year) - year == 18 and int(today.month) - month == 0 and int(today.day) - day < 0: raise forms.ValidationError("You must be 18 years old to have an account") else: return … -
getting bad request 401 even after adding link to ALLOWED_HOST
I'm getting a bad request 401 when trying to access the server, which is deployed to Heroku and my react app is on netlify added to ALLOWED_HOST, and CORS still can't figure out. Please help. -
Django checkbox data navigation
I am using simple bootstrap form. <div class="form-check"> <input class="form-check-input" type="checkbox" value="Resource" id="defaultCheck1" name="APP"> <label class="form-check-label" for="defaultCheck1"> ABC </label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="TC" id="defaultCheck2" name="APP" > <label class="form-check-label" for="defaultCheck2"> DEF </label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="CM" id="defaultCheck3" name="APP"> <label class="form-check-label" for="defaultCheck2"> GHI </label> </div> when i am submitting the form i am accessing it in view.py below function is defined in view.py and in function getdata i am parsing the input submitted. def getdata(request): if request.method == "POST": print(request.POST) print(request.POST['APP']) app=request.POST['APP'] print(app) in this code i am using post to check the request type if it is true i am accessing request object and parsing it. output of above is : <QueryDict: {'csrfmiddlewaretoken': ['cdcdcdcdcd'],'APP': ['ABC', 'DEF', 'GHI']}> RPL RPL