Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show all data in USERS Model in my profile page
views.py Here i have made logic where i have passed user data in my profile file but still it shows not output there #Authenciation APIs def handleSignup(request): if request.method=='POST': #Get the post parameters username=request.POST['username'] fname=request.POST['fname'] lname=request.POST['lname'] email=request.POST['email'] pass1=request.POST['pass1'] pass2=request.POST['pass2'] #checks for errorneous input #username should be <10 # username shouldbe alphanumeric if len(username)>10: messages.error(request,"username must be less than 10 characters") return redirect('/') if not username.isalnum(): messages.error(request,"username should only contain letters and numbers") return redirect('/') if pass1!=pass2: messages.error(request,"Password do not match") return redirect('/') #Create the user myuser=User.objects.create_user(username,email,pass1) myuser.first_name=fname myuser.last_name=lname myuser.save() messages.success(request,"your Musify account has been created succesfully Now go enter your credentials into the login form") return redirect('/') else: return HttpResponse('404 - Not Found') def handleLogin(request): if request.method=='POST': #Get the post parameters loginusername=request.POST['loginusername'] loginpassword=request.POST['loginpassword'] user=authenticate(username=loginusername,password=loginpassword) if user is not None: login(request,user) messages.success(request,"succesfully Logged In") return redirect('/') else: messages.error(request,"Invalid credentials Please try again") return redirect('/') return HttpResponse('404 - Not Found') def profile(request): user=User.objects.get(id=request.user.id) d={'user':user} return render(request,'profile.html',d) profile.html I have made sign up form where i have username,firstname,lastname,email fields in it. and i want to display this field on my profile page But its not working,not showing any output on my profile page. profile here {% for i in d %} {{i.email}} {{i.firstname}} … -
Resize uploaded images does not work correctly Django
I have model upload_path = 'images' upload_path_to_resize = 'resized' class Images(models.Model): image = models.ImageField(upload_to=upload_path, blank=True, null=True) image_url = models.URLField(blank=True, null=True) image_resized = models.ImageField(upload_to=upload_path_to_resize,blank=True) width = models.PositiveIntegerField(null=True) heigth = models.PositiveIntegerField(null=True) def clean(self): if (self.image == None and self.image_url == None ) or (self.image != None and self.image_url != None ): raise ValidationError('Empty or both blanked') def get_absolute_url(self): return reverse('image_edit', args=[str(self.id)]) def save(self): if self.image_url and not self.image: name = str(self.image_url).split('/')[-1] img = NamedTemporaryFile(delete=True) img.write(urlopen(self.image_url).read()) img.flush() self.image.save(name, File(img)) self.image_url = None super(Images, self).save() def resize(self): if (self.width != None) or (self.heigth != None): img = Image.open(self.image.path) output_size = (self.width, self.heigth) img.thumbnail(output_size) img.save(self.image_resized.path) super(Images, self).save() The resize method should take the existing file from the "ImageField" field, resize and load into the "image_resized" field, but for some reason the FormResize form passes the height and width arguments to the model, but nothing happens from django.forms import ModelForm from .models import Images class ImageForm(ModelForm): class Meta: model = Images fields = ['image', 'image_url'] class ResizedForm(ModelForm): class Meta: model = Images fields = ['width', 'heigth'] What do I need to do to make the resize work correctly? -
django redirect test - AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)
I can't get my test to accept the redirect works... I keep getting this error "AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)" but the redirect working logs web_1 | [11/Oct/2020 12:41:33] "GET /calendar/5d8b6a0a-66b8-4909-bf8f-8616593d2663/update/ HTTP/1.1" 302 0 web_1 | [11/Oct/2020 12:41:33] "GET /calendar/list/ HTTP/1.1" 200 4076 Please can some advise where I am going wrong. I have tried using assertRedirects but this still doesn't pass test.py class EventTests(TestCase): def setUp(self): self.eventbooked = Event.objects.create( manage=self.user, availability='Booked', start_time='2020-09-30 08:00:00+00:00', end_time='2020-09-30 17:00:00+00:00', ) def test_event_update_redirect_if_booked_view(self): self.client.login(email='test_username@example.com', password='da_password') response = self.client.get(self.eventbooked.get_absolute_url_edit()) self.assertEqual(response.status_code, 302) self.assertContains(response, 'Update Availability') view.py - this is where the redirect happens, this the object is excluded. class CalendarEventUpdate(LoginRequiredMixin, UpdateView): model= Event form_class = EventForm template_name='calendar_update_event_form.html' def get_queryset(self): return Event.objects.filter(manage=self.request.user).exclude(availability='Booked') def get(self, request, *args, **kwargs): try: return super(CalendarEventUpdate, self).get(request, *args, **kwargs) except Http404: return redirect(reverse('calendar_list')) models.py def get_absolute_url_edit(self): return reverse('calendar_event_detail_update', args=[str(self.id)]) -
Django 3 How To Join Without Where?
I have a question about joining table on Django, here is my models # Create your models here. class Customer(models.Model): id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=13, null=True) email = models.CharField(max_length=50, null=True) region = models.CharField(max_length=100, default='1') date_created = models.DateTimeField(auto_now_add=True) class Meta: db_table = "customers" def __str__(self): return self.name class Product(models.Model): id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=200, null=False) price = models.IntegerField(default=0) category = models.CharField(max_length=500, null=True) date_created = models.DateTimeField(auto_now_add=True) class Meta: db_table = "products" def __str__(self): return self.name class Order(models.Model): id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, editable=False) customer = models.ForeignKey(Customer, null=True,on_delete=models.SET_NULL, related_name='cus_orders') product = models.ForeignKey(Product, null=True,on_delete=models.SET_NULL) class Meta: db_table = 'orders' Here is my queryset customer = Customer.objects.get(id='9c2ed1c9-9dee-417c-bee6-1fd5ec3a500c') order = Order.objects.filter(product__name='', customer=customer.id) And here is the query result SELECT "orders"."id", "orders"."customer_id", "orders"."product_id" FROM "orders" INNER JOIN "products" ON ("orders"."product_id" = "products"."id") WHERE ("orders"."customer_id" = 9c2ed1c9-9dee-417c-bee6-1fd5ec3a500c AND "products"."name" = ) But how can I make the query without where on the products ? so like this SELECT "orders"."id", "orders"."customer_id", "orders"."product_id" FROM "orders" INNER JOIN "products" ON ("orders"."product_id" = "products"."id") WHERE "orders"."customer_id" = 9c2ed1c9-9dee-417c-bee6-1fd5ec3a500c But when I try tu use select_related customer = Customer.objects.get(id='9c2ed1c9-9dee-417c-bee6-1fd5ec3a500c') order = Order.objects.filter(customer__id=customer.id).select_related('product') The result of query become a left … -
Django & Python 3.7: ModuleNotFoundError: No module named '_ctypes'
I am busy with the Django Project Tutorial. I was by the part you get the write tests: https://docs.djangoproject.com/en/3.1/intro/tutorial05/#writing-our-first-test . But when I got by running the test, the fOllowing error came a long: 'ModuleNotFoundError: no module named '_ctypes''. I have tried to solve this error by trying the solutions who were brought in the following StackOverflow questions: Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing linux ModuleNotFoundError: No module named '_ctypes ModuleNotFoundError: No module named '_ctypes' when installing pip But it didn't work! Does someone know how to solve this error? -
No module found in Django Test
I have a Django app and I am writing tests. Since it's deployed on heroku with a PostgreSQL db, I created another db to run my tests. I did change my settings this way: if 'test' in sys.argv: #Configuration for test database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xx', 'USER': 'xxxxxx', 'PASSWORD': 'xxxxx66667297357aca0e412f06891aed646', 'HOST': 'xx-xx-137-124-19.eu-west-1.compute.amazonaws.com', 'PORT': 5432, 'TEST': { 'NAME': 'xx', } } } else: #Default configuration DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'd751emj1l26su7', 'USER': 'xxxxxx', 'PASSWORD': 'xxxxxfdd17531f544d0c2805726d12a1b230cf9a0e', 'HOST': 'xxx-xx-137-124-19.eu-west-1.compute.amazonaws.com', 'PORT': 5432, 'TEST': { 'NAME': 'xx', } } } This is my application tree: To execute my tests I run: heroku run python trusty_monkey/manage.py test trusty_monkey/users/tests My test is running but I get this error: ModuleNotFoundError: No module named 'trusty_monkey/users/tests' What am I doing wrong? -
Django form creating new record instead of updating
I'm creating a user update form in my app. but every time when the form is submitted , it creates a new record and if you try submitting again will return Integrity Error(duplicate username that both are null). ERROR message: django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username forms.py: class UserChangeForm(forms.ModelForm): class Meta: model = User fields = ['email', 'first_name', 'last_name'] def __init__(self, username, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) self.username = username views.py: def profile(request): user = request.user if request.method == 'POST': user_form = UserChangeForm(user, request.POST) if user_form.is_valid(): user_form.save() messages.success(request, f'Your account has been updated!') return redirect('users:profile') else: email = request.user.email first_name = request.user.first_name last_name = request.user.last_name user_form = UserChangeForm(user, initial={ 'email': email, 'first_name': first_name, 'last_name': last_name }) context = { 'user_form': user_form, } return render(request, 'users/profile.html', context) -
What happens when Django Session timesout?
In my scenario the function which does some backend updates is called when request is submitted takes a lot of time to return the value and as a result the session times out. So my doubt is What happens in backend when session times out? Does the function that was running stops running immediately as session timesout? Will the data from django session table be removed? I don't know much about django sessions and reading online didn't gave much clarity on doubts. -
cannot connect django web application to sql server 2016
i am writing a django web application using mssql database. and i used 'DIRS': [os.path.join(BASE_DIR, 'templates')], in setting.py file. but after runserver i got this error that:NameError: name 'os' is not defined. so i tried to install os-sys. but it didn't work. heres part of error i get. i also use visual studio 2019 and Python 3.8.6rc1 and django 3.1.2 any idea how can i fix my code?? Getting requirements to build wheel ... done Installing backend dependencies ... error ERROR: Command errored out with exit status 1: command: 'c:\users\marie\appdata\local\programs\python\python38\python.exe' 'c:\users\marie\appdata\local\programs\python\python38\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\Marie\AppData\Local\Temp\pip-build-env-15qobm6i\normal' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'cymem<2.1.0,>=2.0.2' 'murmurhash<1.1.0,>=0.28.0' 'cython>=0.25' 'preshed<3.1.0,>=3.0.2' wheel 'thinc<7.2.0,>=7.1.1' cwd: None Complete output (215 lines): Collecting cymem<2.1.0,>=2.0.2 Using cached cymem-2.0.3-cp38-cp38-win_amd64.whl (33 kB) Collecting murmurhash<1.1.0,>=0.28.0 Using cached murmurhash-1.0.2-cp38-cp38-win_amd64.whl (20 kB) Collecting cython>=0.25 Using cached Cython-0.29.21-cp38-cp38-win_amd64.whl (1.7 MB) Collecting preshed<3.1.0,>=3.0.2 Using cached preshed-3.0.2-cp38-cp38-win_amd64.whl (115 kB) Collecting wheel Using cached wheel-0.35.1-py2.py3-none-any.whl (33 kB) Collecting thinc<7.2.0,>=7.1.1 Using cached thinc-7.1.1.tar.gz (1.9 MB) Collecting blis<0.5.0,>=0.4.0 Using cached blis-0.4.1-cp38-cp38-win_amd64.whl (5.0 MB) Collecting wasabi<1.1.0,>=0.0.9 Using cached wasabi-0.8.0-py3-none-any.whl (23 kB) Collecting srsly<1.1.0,>=0.0.6 Using cached srsly-1.0.2-cp38-cp38-win_amd64.whl (181 kB) Collecting numpy>=1.7.0 Using cached numpy-1.19.2-cp38-cp38-win_amd64.whl (13.0 MB) Collecting plac<1.0.0,>=0.9.6 Using cached plac-0.9.6-py2.py3-none-any.whl (20 kB) Collecting tqdm<5.0.0,>=4.10.0 Using cached tqdm-4.50.2-py2.py3-none-any.whl (70 kB) … -
How to use temp table count values into into the where query in Django Raw Sql?
I need to use raw sql in my django project. I'm using count command and then I associated it with as command like "the_count" but i got an error. The error like this, the_count does not exist. And my my code here, query = 'SELECT "auth_user"."id", (SELECT COUNT(*) FROM "my_app" WHERE (something)) AS "the_count" FROM "auth_user" WHERE ( "the_count" = 0)' User.objects.raw(query) Thank you for yours helps... -
Django Rest Framework media files fetching HTTP instead of HTTPS in production
Django rest framework is fetching "pp": "http://xyz/media/IMG_9579_CBgxVGX.JPG", instead of "pp": "https://xyz/media/IMG_9579_CBgxVGX.JPG", even after configuring nginx here is my nginx configuration server { listen 80; #listen 443 ssl default_server; #listen 443 ; #listen [::]:443 ; listen 443 ; server_name xyz 13.232.17.9; #proxy_set_header X-Forwarded-Proto https; #return 301 https://$host$request_uri; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/ubuntu/ss42; } location /media { root /home/ubuntu/ss42; } location / { include proxy_params; proxy_set_header X-Forwarded-Proto https; proxy_pass http://unix/run/gunicorn.sock; #proxy_pass http://unix/run/gunicorn.sock; #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; #proxy_set_header Host $http_host; #proxy_redirect off; } } and my django settings where i have enabled ssl header SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') USE_X_FORWARDED_HOST = True media MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") I have tried several possibilities added SECURE_SSL_REDIRECT=True but that gave 500 error while access server #return 301 https://$host$request_uri; added this line in nginx but that gave "to many redirects error " removed listen 80; and added just listen 443 ; this is actually gave 404 not found error in nginx i have no idea what exactly is wrong from my side i have tried all the possible ways as mentioned in the official documentation and various stackoverflow threads -
Facebook Messengerbot python ( The Callback URL or Verify Token couldn't be validated. Please verify the provided information or try again later.)
Am trying to implement facebook messenger chatbot in python. Am created One API in python below @api_view(['GET']) def verify(request): form_data = request.query_params mode = form_data.get('hub.mode') token = form_data.get('hub.verify_token') challenge = form_data.get('hub.challenge') if mode and token: if mode == 'subscribe' and token == "mytestingtoken": print("WEBHOOK_VERIFIED") return JsonResponse({"code":200,'message':challenge}) else: return JsonResponse({"code":403}) return JsonResponse({"code":200,'message':'test'}) am mapping the API URL into ngrok URL(https://55d71a8248be.ngrok.io) then am created a Facebook App and configured a webhook. here callback URL and Verify Token also setup. but finally I got Error Message The Callback URL or Verify Token couldn't be validated. Please verify the provided information or try again later. Am referred facebook document https://developers.facebook.com/docs/messenger-platform/getting-started/webhook-setup -
qr url parameters using django
How to pass url parameters to function to generate qr code for current page? And this's my generate function: from django.shortcuts import render from qrcode import * data = None def home(request): global data if request.method == 'POST': data = request.POST['data'] img = make(data) img.save("static/image/test.png") else: pass return render(request,"home.html",{'data':data}) -
How can I use use the URL from feed and redirect to the user to a custom landing page based on URL in Django
I am working on a project where I am trying to build a news summarizer. It will use feedparser to parse and list the articles on home page and then if user clicks any of the links, it would redirect him to post page where he will see summary of the arcticle for which I am using newspaper and nltk library. **my views:** from django.shortcuts import render import feedparser import urllib import bs4 import nltk import newspaper from newspaper import Article url = 'https://timesofindia.indiatimes.com/rssfeedstopstories.cms' feed = feedparser.parse(url) def home(request): return render(request, 'entries/home.html', {'feed': feed}) def post(request): toi = newspaper.build('https://timesofindia.indiatimes.com/rssfeedstopstories.cms') for i in toi.articles: article = toi.articles[i] article.download() article.parse() nltk.download('punkt') article.nlp() return render(request, 'entries/post.html', {'article': article}) **Home HTML:** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Newzed</title> </head> <body> <h1>{{ feed.feed.title }}</h1> {% for item in feed.items %} <div> <p> {{ item.published }} <a href="post">{{ item.title }}</a> {{ item.author }} </p> </div> {% endfor %} </body> </html> **post HTML:** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ article.title }}</title> </head> <body> <h1>{{ article.title }}</h1> <div> <p> {{ article.summary }} </p> <p> Source for detail: <a href="{{ url }}">{{ article.title }}</a> </p> </div> </body> -
Django - my html files ignore what I change in css file?
This is my css. I want to have black font color, but I get white? and I don't know why? /* selected tag{ property: value; }*/ body{ background-image: url("/static/img/sample.jpeg"); /* top, right, bottom, left */ margin: 10px 30px 30px 30px; color: black; } This is my base html file {% load static %} <!DOCTYPE html> <html lang="en"> <link> <meta charset="UTF-8"> <title>Strona startowa</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> </head> <body> <div w3-include-html="base.html"></div> <div class="container"> <h1>Witaj użytkowniku w świecie sztucznej inteligencji</h1> <section> <nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <a class="navbar-brand" href="">Strona Główna</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/blog/"> Newsy <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/history/"> Historia </a> </li> <li class="nav-item active"> <a class="nav-link" href="/present/"> AI obecnie <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/philosophy/"> Filozofia AI <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/chatbot/"> Chatbot <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="/talk/"> Rozmowa z moim chatbotem <span class="sr-only">(current)</span></a> </li> </div> </nav> </section> {% block content %} {% endblock %} <img src="{% static "images/AI.jpg" %}" alt="Images not found"> </div> </body> </html> This … -
CommandError: [WinError 5] Access is denied: 'C:\\Windows\\System32\\Django_Projects\\Random_Password_Generator_Project\\projectApp'
CommandError: [WinError 5] Access is denied: 'C:\Windows\System32\Django_Projects\Random_Password_Generator_Project\projectApp' I have written PS C:\Windows\System32\Django_Projects\Random_Password_Generator_Project> python manage.py startapp projectApp but getting the error above mentioned as my projectApp is not created.I have run it in VS code editor. can anyone help me in this situaton please -
404 Static file not found - Django
I have an issue with django. I recently bought an instance of a shared server and I wanted to move my django website from AWS to this server (which use Cpanel). All worked fine with AWS but when I switched to Cpanel all statics files were missing. this is my settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = "/media/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] my project structure: my_project |-app/ |-... |-views.py |-db.sqlite3 |-manage.py |-media/ |-my_project/ |-... |-settings.py |-static/ |-main_page/ |-js/ |-my-script.js I add static files like this: {% load static %} <script src="{% static 'main_page/js/my-script.js' %}"></script> This is the error: GET http://my.domain.com/static/main_page/js/my-script.js net::ERR_ABORTED 404 (Not Found) When I go to the URL of the file it understands it like one of my URLs: 404 error screenshot I hope you will help me to solve this issue ;) thanks. -
Using multiple instance and Senders in django signals
how can i use multiple instances and senders (different models) in django signals. receiver(post_save, sender=Comment) @receiver(post_save, sender=Post) def create_comment_notification(*args, **kwargs): #comments notifier comment = kwargs['instance'] post = kwargs['instance'] if kwargs['created']: if comment.author != comment.post_connected: Notification.objects.create( assigned_to = post.author, group='NC', body=f"{comment.author} commented: {comment.content} on your post.", pk_relation=comment.id ) else: if comment.author != comment.post_connected: Notification.objects.create( assigned_to = post.author, group='NC', body=f"{comment.author} commented: {comment.content}.", pk_relation=comment.id ) I notice it work but does not recognizes the POST model, it uses COMMENT only. How can i use the two models as senders. and for the code to recognize them separately. Thank you -
Fill 24 Hours Values, Rounding the range in TImeFIeld Formset and Save in Views Django
I have following formset to save and rounding the range of TimeField in Views Django: Forms.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' MyModelFormSet = modelformset_factory( MyModel, form=MyModelForm, extra=1, max_num=24, ) Views.py: begin1 = datetime.datetime.strptime('01:00', '%H:%M').time() end1 = datetime.datetime.strptime('02:00', '%H:%M').time() begin2 = datetime.datetime.strptime('02:00', '%H:%M').time() end2 = datetime.datetime.strptime('03:00', '%H:%M').time() import datetime if formset.is_valid(): for item in formset: myformset = item.save(commit=False) if myformset.mytime is not None and myformset.mytime > begin1 and myformset.mytime < end1: myformset.mytime = '01:00' elif myformset.mytime is None: myformset.mytime = '01:00' else: pass if myformset.mytime is not None and myformset.mytime > begin2 and myformset.mytime < end2: myformset.mytime = '02:00' elif myformset.mytime is None: myformset.mytime = '02:00' else: pass myformset.save() It work properly to rounding the timefield when user input the mytime: 00:52 and rounding to the lowest hour as 00:00. But it failed to save the others of mytime when is None, except the user inputed. Example: When user fill the mytime: 00:52, 01:32, and 02:43 then it will save into 3 fields of mytime as: 00:00, 01:00, 02:00. But currently, it's not save the other 21 fields of mytime as: 03:00, 04:00, 05:00, 06:00, 07:00, ...... 21:00, 22:00, 23.00. How to save 3 user input … -
After creating a custom user with django when i tried to create a user my password don't show or its Blank or you can say its none
My django custom user return blank or none as password after creating a user but I can't find any problem I am new at this I've done my research but it's hopeless so help me Here is my models from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyUserManager(BaseUserManager): def create_user(self, username, email, first_name, last_name, date_of_birth, gender, password=None): if not first_name: raise ValueError("Users must have a first name") if not last_name: raise ValueError("Users must have a last name") if not email: raise ValueError('Users must have an email address') if not gender: raise ValueError("Users must have a gender") if not date_of_birth: raise ValueError("You Must Enter your date of birth") user = self.model( username=username, email=self.normalize_email(email), first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, gender=gender, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, first_name, last_name, date_of_birth, gender, password=None): user = self.create_user( username, email, first_name, last_name, date_of_birth, gender, ) user.set_password(password) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=254, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) date_of_birth = models.DateField() gender_choices = [ ("male", "Male"), ("female", "Female"), ("others", "Others") ] gender = models.CharField(max_length=50, choices=gender_choices) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD … -
Is it possible to combine two input image upload fields and save the data in 2 different fields of related models in the backend?
Is it possible to combine two image upload fields, one field is to upload one primary image and other upload field is to upload multiple images and then send the post data to two different fields in the backend. suppose, in the backend we have a image field in Post model and images field in postimages model which is in a foreign key relation with post. So when the user uploads the images through a single upload field in the frontend, Can I somehow send the data and save it in their corresponding fields in the backend? Or is there a better way to achieve this? Thanks -
Deploying REACT app and Django as a backend in Ubuntu(Apache2)
I have already deployed my react and Django app to my test server on different ports. My Django works by using POSTMAN. But the react app fails when I tried to login and send the request to the Django backend server. I have noticed that in the Network Tab, React sends the request, not on the proper address of the backend server. Here is an example. React APP(Frontend): IP: 192.20.0.10:3000 Django APP(Backend) IP: 192.20.0.10:8000/api/auth/login API: /api/auth/login React Browser Network Tab Request URL: 192.20.0.10:3000/192.20.0.10:8000/api/auth/login *as Expected the request url must be 192.20.0.10:8000/api/auth/login *It seems that the backend url is appended to the frontend url. So that is why the test fails. Any idea why this happens? Thank you -
how can I create user login using is_staff and is_superuser in Django Rest Framework?
I am a beginner. Here I am creating user login using is_staff and is_superuser that can view other systems that register into the system and can allow and deny them. -
HTML - Python Connection
So I have a website that has a form. I want to be able to connect it to Python so that all the form inputs gets transferred to an SQL Database. I have no clue how to do it tho. I've heard that Flask is easier but I have no clue if Django is easier or harder. Any help would be appreciated. -
DRF xss protection - get user details with a POST request
I'm working on an application which is going to be using DRF for the API and Angular or React on the frontend. I'll be using cookies season authentication that will be protected against XSS by csrf token for the unsafe methods. I was wondering what is happening with the safe methods as GET in cases where I request a piece of really sensitive user information, for example, user details whit phone number or even a home address. As far as I understand HTTPS alone will not protect such information as the attack is performed on an application level rather than being intercepted which makes it human-readable. I can imagen many more cases where we want to defend safe methods, especially in user-driven applications. If an attacker gains access to our authentication cookie and performs a forged GET request to /api/v1/users/:id, which by default will not be protected by csrf token even if we decorate the view with csrf_protect(), he will be able to read the response unless I'm missing something. I went through some articles here and there but didn't find a definitive answer to this problem. My question - can we use POST request in such situations despite we …