Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why do the pictures disappear when I reload the page in Django?
Site on Django. Configuration mod_wsgi-express inside virtualenv + apache2. I started the page through the command python manage.py runmodwsgi --setup-server --port 8888 --server-root = / home / user / virtualenv / mod_wsgi-express-80. Everything was OK the first time. The problem appeared when I started to reload the page (CTRL + R). What can cause problems? -
Ebay Integration with Python
I have to integrate my django project with Ebay. I have followed the SDK repository and set up an account on the developers forum as specified here Ebay SDK Repository for Python I tried to run the following function to add an item #!/usr/bin/env python3 from ebaysdk.trading import Connection if __name__ == '__main__': api = Connection(config_file="ebay.yaml", domain="api.sandbox.ebay.com", debug=True) request = { "Item": { "Title": "Professional Mechanical Keyboard", "Country": "US", "Location": "IT", "Site": "US", "ConditionID": "1000", "PaymentMethods": "PayPal", "PayPalEmailAddress": "nobody@gmail.com", "PrimaryCategory": {"CategoryID": "33963"}, "Description": "A really nice mechanical keyboard!", "ListingDuration": "Days_10", "StartPrice": "150", "Currency": "USD", "ReturnPolicy": { "ReturnsAcceptedOption": "ReturnsAccepted", "RefundOption": "MoneyBack", "ReturnsWithinOption": "Days_30", "Description": "If you are not satisfied, return the keyboard.", "ShippingCostPaidByOption": "Buyer" }, "ShippingDetails": { "ShippingServiceOptions": { "FreeShipping": "True", "ShippingService": "USPSMedia" } }, "DispatchTimeMax": "3" } } api.execute("AddItem", request) but then I'm running into the following errors ebaysdk.exception.ConnectionError: "AddItem: Class: RequestError, Severity: Error, Code: 120, You need to create a seller's account. Before you can list this item we need some additional information to create a seller's account." 020-01-16 17:13:02,385 ebaysdk [WARNING]:AddItem: Class: RequestError, Severity: Warning, Code: 21920200, Return Policy Attribute Not Valid Return Policy Attribute returnDescription Not Valid On This Site I am not getting how to set … -
react native csrf token works on local server, doesnt work on external
Basically I finished my react and react-native apps together with django server, thing is that eventho everything worked fine on local server, when I moved it to external one it cannot detect csrf token anymore... Does anyone knows why? Because mobile app cannot get csrf from cookies then I generate and serve it from django. Then in console log i can detect it, but when I set it in login, django says "Forbidden (CSRF cookie not set.): /django/login get_token() { // fetch("http://192.168.1.40:8000/csrftoken/") fetch(url + "/django/csrftoken/") .then(res => res.json()) .then(resp => this.setState({csrfToken: resp.token})) // .then(() => console.log(this.state.csrfToken)) } handleLogIn = () => { const auth = { "username": this.state.username, "password": this.state.password } // console.log(auth, this.state.csrfToken) // fetch("http://192.168.1.40:8000/login/", { fetch(url + "/django/login/", { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': this.state.csrfToken }, body: JSON.stringify(auth) }) .then(res => res.json()) .then(r => console.log(r) .catch(err => alert("Wrong password or username")) } -
Django/Webdatarocks: unable to correctly serialize data
I currently develop a Django project and try to implement WebDataRocks WebDataRocks is a free web reporting tool for data analysis and visualization I works but my problem deal with correctly presenting data to be updated in Webdatarocks I would like to update each of my models. I have a views name data use with my template that load WebDataRocks def data(request): data = serializers.serialize("json", mymodel.objects.filter(med_ide__lte=10)) return render(request, 'myapp/data.html', {'data':data}) I do not really understand the way json is produce because I get this format: [ { "model": "myapp.mymodel", "pk": 1, "fields": { "var1": 1, "var2": "ABC", "var3": "code", "var4": "text", "var5": null, "var6": "'text'", "var7": null } }, { "model": "myapp.mymodel", .... } ] The only 2 variables I get access in webdatarocks table are randomization.medicament and pk I try to extract only part of my data I need (=fields) using things like data['fields'] but it is not the right syntax what is wrong? -
the user login view in django is not working properly?
I am having a login page after registration page the problem in my login page when I log in with valid credentials it is redirecting to dashboard and when I give invalid credentials also it is redirecting to dashboard with the last valid credentials typed in the login form I am not understanding why it is like that My views.py def user_register(request): if request.method == 'POST': # if there is a post request in the form user_form = UserForm(data=request.POST) #first of all it is a user_form will be posted details present in the user_form user_requirement_form = UserRequirementForm(data=request.POST)# after posting the details of the user_form post the details if user_form.is_valid() and user_requirement_form.is_valid(): # if user_form & user_requirement form is valid User = user_form.save()#if form is valid save User.set_password(request.POST['password']) User.save() user_requirement = user_requirement_form.save(commit=False) # Set user user_requirement.user = User user_requirement.save() user_requirement_form.save_m2m() messages.success(request,('Project saved successfully')) return render(request,'home1.html') else: messages.warning(request, 'Please correct the errors above') else: user_form = UserForm() user_requirement_form = UserRequirementForm() return render(request,'register.html', {'user_form': user_form, 'requirements_form': user_requirement_form}) def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) messages.success(request, 'You are now logged in') return render(request,'dashboard.html') else: messages.error(request,'Invalid Credentials') … -
Django, adding two foerign keys to the same model
I have a table which relates one row in the Context table to another row in the Context table. In Django I try to add two foreign keys and it says I need to use related name. I've been reading the documentation on related name but I cannot understand it. I include the working model below with commented out rows. Following I also include the template. Can anyone fix the code below? model.py class Relationship (models.Model): relationship_id = models.AutoField(primary_key=True) # context_id1 = models.IntegerField() context_id1 = models.ForeignKey(Context, db_column='context_id1', on_delete = models.PROTECT) context_id2 = models.IntegerField() # context_id2 = models.ForeignKey(Context, db_column='context_id2', on_delete = models.PROTECT) relationship = models.CharField(max_length = 50, blank=True, null=True) template {% for relationship in context.relationship_set.all %} Current Context:{{relationship.context_id1.number}} <br> # works Relationship:{{relationship.relationship}} <br> # works Related Context: {{relationship.context_id2.number}} # fails {% endfor %} -
Why Sum() in Django returns number with 13 decimal places when evaluating numbers with only 2 decimal places?
I am learning Django and creating a cart application. What I am trying to do here is to display on the HTML page the sum of all the cart items 'prices'. Now, I know this is probably the worst way to do it, as I have seen many tutorials, but I'd rather learn step by step. So what I am doing here is setting the variable 'total' equal to the sum of all prices using the Sum() function documented here. The problem is that it displays a number with 13 decimal places, although my model allows just 2 decimal places. How can I overcome this issue? Here is all the code, and obviously If you have any tip about a better 'basic' way to do this (a best practice) please let me know in the comments. 'models.py' from django.db import models from django.contrib.auth.models import User # Create your models here. class Item(models.Model): name = models.CharField(max_length=25) price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.name class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) items = models.ManyToManyField(Item) def __str__(self): return 'Order number: %s' % self.id 'views.py' from django.shortcuts import render from .models import Cart, Item from django.db.models import Sum # Create your … -
Insert more than 1 million data in django
I have 2 models class Movie(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) vote_count = models.IntegerField() def __str__(self): return self.title class Watchlist(models.Model): userid = models.IntegerField() movie_id = models.ForeignKey(Movie, on_delete=models.CASCADE) rating = models.IntegerField() def __int__(self): return self.userid I can't enter 1 million data one by one using django admin panel, so how would i populate database of both model with 1 million data ? -
Django group_by argument depending on order_by
I'm struggling (again) with Django's annotate functionality where the actual SQL query is quite clear to me. Goal: I want to get the number of users with a certain let's say status (it could be just any column of the model). Approach(es): 1) User.objects.values('status').annotate(count=Count('*')) This results into the following SQL query SELECT users_user.status, COUNT(*) as count FROM users_user GROUP BY users_user.id ORDER BY usser_user.id ASC However, this will give me a queryset of all users each "annotated" with the count value. This is kind of the behaviour I would have expected. 2) User.objects.values('status').annotate(count=Count('*')).order_by() This results into the following SQL query SELECT users_user.status, COUNT(*) as count FROM users_user GROUP BY users_user.status No ORDER BY, and now the GROUP BY argument is the status column. This is not what I expected, but the result I was looking for. Question: Why does Django's order_by() without any argument affect the SQL GROUP BY argument? (Or broader, why does the second approach "work"?) Some details: django 2.2.9 postgres 9.4 -
How to send an array in an HTML post request with Django
I've got an array of values from a checklist: {% for groups in groupList %} <tr> <td id="checkboxes"> <input type="checkbox" name="check" id="check_{{groups.GroupID}}"> </td> <tr> {% endfor %} note this is just a snippet of a larger table. this is the relevant data though. I need to take all checked items in the table and extract the groups.GroupID into an array and pass this to somewhere (presumably a view) where I can use the data to edit a model instance. I know how to get the data to an array just fine, but I'm not sure how to approach passing the data on. Possibly a form but I'm not sure how I would implement this to be attached to a view and also pass an array. -
How to use filtering data while using distinct method in django?
I hope my title is enough to understand what I mean, please help me on this problem guys. When I tried this: id_list = grade.objects.filter(Teacher=m.id).values_list('Students_Enrollment_Records_id',flat=True).distinct() I use distinct() to eliminates duplicate rows of Students Enrollment Record from the query results but I wonder why the result is like this: What should I do to show the Students name not that QuerySet in my html? This is my current views.py: id_list = grade.objects.filter(Teacher=m.id).values_list('Students_Enrollment_Records_id',flat=True).distinct() print(id_list) grades = grade.objects.filter(Students_Enrollment_Records_id__in=id_list) print(grades) This is my models.py: class grade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Average = models.FloatField(null=True, blank=True) UPDATE when I tried this piste = grade.objects.filter(Teacher_id=m.id).values_list('Students_Enrollment_Records').annotate(Average=Avg('Average')).order_by('Grading_Categories').distinct() the computation is fix but the teacher name, Subject and Name of students didn't display but the ID is display just like this this is my desire answer this is how I post in html views.py return render(request, 'Homepage/index.html', {"piste":piste}) html {% for n in piste %} <tr> <td>{{n.Teacher}}</td> <td>{{n.Subjects}}</td> <td>{{n.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td> <td>{{n}}</td> </tr> {% endfor %} This is model.py class EmployeeUser(models.Model): Image = models.ImageField(upload_to='images', null=True, blank=True) Employee_Number = models.CharField(max_length=500, null=True) Username = models.CharField(max_length=500, null=True) Password = models.CharField(max_length=500, null=True) My_Department … -
Upload file limit in Django Nginx Gunicorn
When im trying to upload more than 1mb im getting this error: I tried configuring my nginx.conf file, I've added this line to inside http { }: 'client_max_body_size 100M;' and restarted nginx: service nginx restart but I still get 413 request entity too large. I feel like I'm missing something because when I tried to search my problem the client_max_body_size solve their problem. -
How to change the Django media url every time it is response?
In my code I know how to protect my endpoint url. I can do simply like this class ApprovalViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, GenericViewSet): permission_classes = (IsAdminUser,) queryset = User.objects.all() serializer_class = ApprovalSerializer Problem: However, my challenging task is I need to change /media url every time since it is sensitive files. And my files are stored in AWS S3 Questions: 1. How to protect the /media url in Django 2. My workaround is keep changing the url. How can I do that? -
How to send message to node js socket.io server from django server?
I have a node js socket.io server as well as django server. Socket server has some clients connected with it. Now I want to send some messages from django server to the socket.io server so that it can broadcast these messages to its connected client. Currently I am using pubsub by creating a redis server. But it's not working and no connection request is created with nodejs server: Please suggest me a good way. Thanks in advance. Code in django: import redis client = redis.StrictRedis(host='localhost', port=6379, db=5) client.publish('message', json.dumps({'query': {'token': jwt.encode({'user': 'admin'}, settings.SOCKET_SECRET_TOKEN, algorithm='HS256').decode('utf-8')}})) Code from nodejs server: const server = require('http').createServer(); const io = require('socket.io')(server); const hostname = '127.0.0.1'; const SECRET_KEY = '*******************************'; const port = 3000; const jwt = require('jsonwebtoken'); server.listen(3000, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); io.use(function(socket, next){ if (socket.handshake.query && socket.handshake.query.token){ jwt.verify(socket.handshake.query.token, SECRET_KEY, function(err, decoded) { if(err) return next(new Error('Authentication error')); socket.decoded = decoded; next(); }); } else { next(new Error('Authentication error')); } }) .on('connection', function(socket) { console.log("Co nnection established"); socket.on('message', function(message) { io.emit('message', message); }); }); -
Using Factory Boy SelfAttribute + relativedelta
I'm using Factory Boy in my tests and want to achieve the following: Make first_period_end_date dependent on first_period_date and add 12 months to it. I'm trying to use SelfAttribute in combination with relativedelta but the way I'm currently applying it doesn't work. My code: import datetime import factory from dateutil import relativedelta from somewhere.models import Contract class ContractFactory(factory.django.DjangoModelFactory): class Meta: model = Contract start_date = factory.LazyFunction(datetime.date.today) first_period_date = factory.SelfAttribute('start_date') first_period_end_date = ( factory.SelfAttribute('first_period_date') + relativedelta.relativedelta(months=12) ) But in runtime I get the following error: TypeError: unsupported operand type(s) for +: 'SelfAttribute' and 'relativedelta' So that is apparently not how it's done. But how do I do it? -
How to retrieve data from models in table with a month days as table heads?
Am new to Django, am trying to retrieve data from the models into html table. Essentially, I want to retrieve all teachers and their attendance Status(Present, Absent and Late ) in a particular month that the user selects. Am able to pass the context to the template from the views here is my code models.py class TeacherAttendance(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, blank=False, null=True) date = models.DateField() status = models.CharField(max_length=50, choices=ATTENDANCE) objects = models.Manager() class Meta: default_permissions = ('view', 'add', 'change', 'delete') ordering = ["date", ] get_latest_by = "date" views.py def teacher_attendance_report(request): context = {} form = TeacherAttendanceForm(request.POST) if request.method == 'POST': if request.POST.get('group_by'): grab_data_passed = request.POST.get('group_by') get_details = TeacherAttendance.objects.filter(date__month=grab_data_passed) z=0 range=9 days=[] if z< range: dats = TeacherAttendance.objects.filter(date__month=grab_data_passed)[z].date z+=1 y=dats.month x=dats.year cal = calendar.TextCalendar(calendar.WEDNESDAY) for day in cal.itermonthdays(x, y): days.append(day) context['days']=days teacher = User.objects.filter(is_teacher=True) for i in teacher: x=i.id get_details = TeacherAttendance.objects.filter(teacher__user=x, date__month=grab_data_passed) context['get_details']=get_details return render(request, 'Reports/teacher_attendance_report_details.html', context) context={'form':form} return render(request, 'Reports/teacher_attendance_report_index.html', context) I don't know whether that's the best pythonic way of retrieving data in a view function. here is my template <table id="datatable-responsive" class="datatable-responsive table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%"> <thead> <tr> <th>Teacher <i class="fa fa-long-arrow-down" z></i> - Date <i class="fa fa-long-arrow-right"></i></th> <th>{{days}}</th> </tr> </thead> <tbody> {% … -
Executing Django management commands that spins off multiple processes and threads in windows and linux
I am relatively new to multi-threading and multi-processing. I just encountered another learn-block when i just realized that windows and linux handles multi-processing very differently. I do not know th technicalities, but I do know that it is different. I am using a django to execute my application: python manage.py random_script, within random_script, I am importing multiprocessing and spinning of different processes. i get the following error: File "<string>", line 1, in <module> File "C:\FAST\Python\3.6.4\lib\multiprocessing\spawn.py", line 99, in spawn_main new_handle = reduction.steal_handle(parent_pid, pipe_handle) File "C:\FAST\Python\3.6.4\lib\multiprocessing\reduction.py", line 82, in steal_handle _winapi.PROCESS_DUP_HANDLE, False, source_pid) OSError: [WinError 87] The parameter is incorrect I tried adding this at the top because my development server is windows but my production server is linux: if 'win' in sys.platform: print('Window') multiprocessing.set_start_method('spawn') else: print('Linux') multiprocessing.set_start_method('fork') But to no success. When i continued to look through google, it suggest writing the portion of the process spawning under the if __name__ == '__main__': line. That would be fine if I am executing my scripts normally (i.e. python random_script.py), but I am not. I have ran out of ideas and no longer know how to proceed. Thanks for the guidance -
How to get the specific users details from the database in the dashboard after login in django?
I am having a registration,login and a dashboard page the registration form consists of username,email,password,goal,design,furniture,room so in these the username,email will be stored in custom user model and the remaining details will be stored in the user_requirement table and the login page consists of username and password which will be authenticated and get to the dashboard page now In dashboard page I am trying to display the goal,design,furniture,room details which the particular user given during registration My views.py: from django.shortcuts import render, redirect from django.contrib import messages, auth from django.contrib.auth.models import User from contacts.models import Contact from django.shortcuts import render,HttpResponseRedirect from django.contrib import messages,auth from account.forms import UserForm from account.forms import UserRequirementForm from django.contrib.auth import authenticate, login def register(request): return render(request, 'account/register.html',); def user_register(request): if request.method == 'POST': # if there is a post request in the form user_form = UserForm(data=request.POST) #first of all it is a user_form will be posted details present in the user_form user_requirement_form = UserRequirementForm(data=request.POST)# after posting the details of the user_form post the details if user_form.is_valid() and user_requirement_form.is_valid(): # if user_form & user_requirement form is valid User = user_form.save()#if form is valid save User.set_password(request.POST['password']) User.save() user_requirement = user_requirement_form.save(commit=False) # Set user user_requirement.user = User user_requirement.save() … -
How to remove fields on Django ModelForm?
I would like to build a form with dynamically fields depends on needs and i have tried this code but doesn't work, the model form show all fields. forms.py: class CustomModelForm(forms.ModelForm): class Meta: model = app_models.CustomModel fields = '__all__' def __init__(self, excluded_fields=None, *args, **kwargs): super(CustomModelForm, self).__init__(*args, **kwargs) for meta_field in self.fields: if meta_field in excluded_fields: # None of this instructions works -> del self.fields[meta_field] -> self.fields.pop(meta_field) -> self.fields.remove(meta_field) Anybody could help me ? Thanks in advance. -
how to dynamically change comment ModelForm in django
I need to view comment ModelForm with fields = ('name', 'email', 'body'). When user is authenticated, field 'name' must be request.user.username and 'email' must be request.user.email. When user is not authenticated user must insert his name and email. What solution can i use here. how can i find information about this question? -
Django: Model UniqueConstraint gives an error when migrating
In my Django project the in one of the model I need to use two UniqueConstraint instances. But when I add that and do the migration after running makemigrations it gives an error in the terminal. Model class: class MyDays(models.Model): class Meta: verbose_name = "My Day" verbose_name_plural = "My Days" constraints = [ models.UniqueConstraint(fields=['userid', 'date', 'from'], condition=Q(status=1), name='user_date_from_a'), models.UniqueConstraint(fields=['userid', 'date', 'to'], condition=Q(status=1), name='user_date_to_b') ] id = models.BigAutoField(primary_key=True) userid = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="User") date = models.DateField(auto_now_add=False, editable=True, validators=[validate_date]) from = models.TimeField(auto_now_add=False, editable=True) to = models.TimeField(auto_now_add=False, editable=True) status = models.ForeignKey(Status, on_delete=models.CASCADE, verbose_name="Status", default=1) When I run python3 manage.py migrate, it gives the following error: django.core.exceptions.FieldError: Joined field references are not permitted in this query I need to have unique records only if the status is 1 along with the other 3 field combination. What am I doing wrong? How can I fix this error? -
Django in kubernetes with ingress-nginx is not serving static files
I'm new to Kubernetes and this is my first project using it. What I'm trying to do is basically this. I have a Django app and a react app. I want to serve them together using a single ingress-nginx using kubernetes' own ingress nginx library (kubernetes/ingress-nginx) React app is served in root and Django is served in "/api" root. I've defined a FORCE_SCRIPT_NAME in Django settings. Also for static files, I've created a separate persistent volume claim and mounted it in Django deployment file. But when I hit the Django's admin page, static files are not served. And also media files are served in api/api/media... path which has an extra api. What is the proper way to serve static files in Kubernetes? I don't want to use an online static root like S3. Here is my Django deployment yaml. apiVersion: apps/v1 kind: Deployment metadata: name: django labels: deployment: django spec: replicas: 1 selector: matchLabels: pod: django template: metadata: labels: pod: django spec: volumes: - name: django-configmap-volume configMap: name: django-configmap - name: static-volume persistentVolumeClaim: claimName: static-volume - name: media-volume persistentVolumeClaim: claimName: media-volume containers: - name: django image: my_image:v1.0 ports: - containerPort: 8182 envFrom: - configMapRef: name: django-configmap env: - name: DB_HOST … -
Django: when debug mode is false not get exception emails
I'm getting not exception emails when debug mode is True But when debug mode is False emails are coming In setting.py Here is my logging dictoanry LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { 'format': '%(name)-12s %(levelname)-8s %(message)s' }, 'file': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' }, 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'console' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'formatter': 'file', 'filename': '../tmp_log/debug.log' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'simple' }, }, 'loggers': { '': { 'level': 'DEBUG', 'handlers': ['console', 'file'] }, 'django.request': { 'level': 'DEBUG', 'handlers': ['console', 'file','mail_admins'] } } } I have setup handlers for console, file and mail_admins Please suggected the changes -
ImportError: cannot import name 'UserUpdateForm' from 'register.forms'
i am beginner to the django and i am getting this error while loading server.So please help This is my register/views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST, instance=request.user) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'register/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'register/profile.html', context) This is my register/signal.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() This is my forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] This is … -
error while installing graphiql_django in anaconda shell
I am working on graphQL and Django for creating API but when i am trying to install graphiql_django by the following command pip install graphiql_django i am getting this error. ERROR: Could not find a version that satisfies the requirement graphiql_django (from versions: none) ERROR: No matching distribution found for graphiql_django. can any one suggest me how to rectify this.