Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I try to bind the country name state name and city names in the database by using Django
enter image description here enter image description here/lpIu8.jpg -
add avatar in AbstractUser and Django-allauth
My code works fine and I do migration to add avatar to my user. But when I signup, avatar field does not show. this is my code: models.py from django.db import models from django.contrib.auth.models import AbstractUser def get_path_name(instance, filename): path = 'media/avatar/' name = instance.user.id + "-" + instance.user.email path = path + name return path # custom User model class CustomUser(AbstractUser): avatar = models.ImageField(upload_to= get_path_name, blank=True, null=True) my form: from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.core.files.images import get_image_dimensions from django import forms class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'username', 'avatar') def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) # validate dimensions max_width = max_height = 100 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) # validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, ' 'GIF or PNG image.') # validate file size if len(avatar) > (20 * 1024): raise forms.ValidationError( u'Avatar file size may not exceed 20k.') except AttributeError: """ Handles case when we are … -
Django: Problem with saving model instances with ForeignKey-relation to database
I would like to create and save model instances with Django. These are my models: class Customer(models.Model): id = models.IntegerField(primary_key=True, unique=True) user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) ... class Order(models.Model): id = models.IntegerField(primary_key=True, unique=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) comment = models.TextField() ... While processing a form, customer will be created: customer = Customer.objects.create( user=user, first_name=storage_space_order["customer_firstname"], last_name=storage_space_order["customer_lastname"], ) As far as I've learned, Django will save the object on calling create as well. Now, I would like to create my order object Order.objects.create( customer=customer, comment=data["customer_comments"], ... ) While saving, I get the following error message: save() prohibited to prevent data loss due to unsaved related customer What I don't get; customer is already there and saved in the database. There are no changes on the customer in between. Also, I've tried customer_id=customer.id/pk, - but both ID and PK return None. Why is this and what do I need to change? Loading the object again is not the preferred way, as I only got the ID which marks it as unique. Thanks for your input :) -
How can i, from a simple form, insert many values into the database in Django?
I have a simple form, like this: <form method="post"> {% csrf_token %} {{ add_boat.non_field_errors }} <div class="form-group"> {{ add_boat_type.name.errors }} <label for="{{ add_boat.name.id_for_label }}">Type</label> <input type="text" name="{{ add_boat.name.html_name }}" class="form-control" placeholder="Ex. Suspekt" value="{{ name.value }}" id="{{ add_boat.name.id_for_label }}"> </div> <div class="form-group"> <input type="hidden" name="{{ add_boat.added_by.html_name }}" id="{{ add_boat.added_by.id_for_label }}" value="{{ user.id }}"> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Add"> </div> </form> where one of the form groups handles a name. The other one is hidden and is for adding what user added this specific entry (this can probably be done in a better way in my model or my view...). But my question is: do i need a hidden form group for every value I want to enter into the database? If i don't include the hidden form group above I get an error saying that that field can not be empty per the database definition (null = 0). I would idealy like to insert a lot of data into the database based on only the name from the form. My form class looks like this: class BoatForm(ModelForm): class Meta: model = Boat fields = [ 'name', 'added_by' ] and my iew looks like this: if(request.user.is_authenticated): add_boat_form = BoatForm(request.POST … -
NotImplementedError: `create()` must be implemented
When i pass the serializer data in postman then it's throwing this error: raise NotImplementedError('create() must be implemented.'). If anyone could figure out where i made any wrong....would be much appreciated. thank you so much in advance. serializers.py : class EditProfileSerializer(Serializer): gender = CharField(error_messages={"required": "gender key is required", "blank": "gender is required"}) profile_visibility = CharField(error_messages={"required": "profile_visibility key is required", "blank": "profile_visibility is required"}) avatar = CharField(allow_blank=True,) token = CharField(allow_blank=True, read_only=True) #some logic goes here... return data def update(self, validated_data): gender = validated_data['gender'] profile_visibility = validated_data['profile_visibility'] avatar = validated_data['avatar'] user_profile_obj = UserProfile( gender = gender, profile_visibility = profile_visibility, avatar = avatar if avatar else None, ) #user_profile_obj.create() user_profile_obj.save() payload = jwt_payload_handler(user_profile_obj) token = jwt_encode_handler(payload) validated_data['token'] = 'JWT' + str(token) return validated_data views.py : class EditProfileAPIView(UpdateAPIView): serializer_class = EditProfileSerializer model = UserProfile permission_classes = (IsAuthenticated,) def update(self, request, format=None): data = request.data profile_serializer = EditProfileSerializer(data=data) if profile_serializer.is_valid(): profile_serializer.save() new_profile = new_profile.data return Response({'success':'True','message':'Profile Updated Successfully', 'data':new_profile}, status=HTTP_200_OK) else: return Response({"message":profile_serializer.errors}, status=HTTP_400_BAD_REQUEST) -
Django Social Authentication Create New User With Custom Model
I'm trying to develop a Facebook social authentication feature on an application that uses a custom Django user model and django-rest-framework-social-oauth2 as the social authentication package. My custom user model is called 'Account' and it inherits from the AbstractBaseUser class. The Account model is shown below: class Account(AbstractBaseUser): # Account model fields: email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=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) # The user will log in with their email instead of username: USERNAME_FIELD = 'email' # Required fields when registering, other than the email: REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] # Telling the Account object how to use the account manager: objects = MyAccountManager() The function that handles creating a new user is called 'create_user' and is defined within my custom written MyAccountManager class which extends the Django BaseUserManager class. This is given below: class MyAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password=None): # Checking to see if correct function parameters have been passed in: if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have … -
How to use sekizai's addtoblock tag inside a form widget template
I am writing a custom form field which has a custom widget. The widget needs some static assets. Its template looks like this: {% load sekizai_tags static %} <div id="myWidget"> ... </div> {% addtoblock "css" %} <link rel="stylesheet" href="{% static 'my_app/css/widget.css' %}">{% endaddtoblock %} {% addtoblock "js" %} <script src="{% static 'my_app/js/widget.js' %}"></script>{% endaddtoblock %} However, this doesn't work. I get: You must enable the 'sekizai.context_processors.sekizai' template context processor or use 'sekizai.context.SekizaiContext' to render your templates. I guess this is because the form (and widget) has no access to the request object?! Is there a way around this? I found in the sekizai source a mention of SekizaiContext as... An alternative context to be used instead of RequestContext in places where no request is available. ... but I can't figure out how exactly I would do that. Note that I do not want to start passing the request around. This would not be an acceptable solution, as my custom field is meant to be reusable; it should just work in any form without further modifications. -
how to design a user based DB system in django
I am working on a Django system that lets multiple individual users store the same type of files and related data. for now, I am storing the user Id in the individual related tables. (i.e) table =>User(id,name,password,email) table =>File(id,url,User.Id) but now I need to store its related data, in few other tables.(i.e) table =>FileInfo(id,File.id,desc,otherInfo) so now when I query the FileInfo table from a user's login, it is fetching info of all the files(i.e all records) since there is no hold in the table. it is also not feasible to store user.id in all the tables, (maybe in the future it may grow to tens or hundreds of table) so kindly suggest me(design change that can to retrieve the current user data alone or any django functionality that supports this use case or any Django package that helps to achieve it) how can I get the data that pertains to the current logged in user without explicitly storing the userid in every table. -
How to restrict overlapping datetimes in django model at DB level using CheckConstraint
I have the following fields in my Model: class Event(models.Model): starts = models.DateTimeField() ends = models.DateTimeField() I want to restrict overlapping dates (starts, ends). I have managed to do this in model validation, but now I want this enforced at database level such that an IntegrityError exception is thrown if an insert happens outside the model's save method. My Validation was as follows: ... def clean(self): if self.starts and self.ends: if self.__class__.objects.filter( models.Q(ends__gte=self.starts, starts__lt=self.starts) | models.Q(ends__gte=self.ends, starts__lt=self.ends) | models.Q(starts__gt=self.starts, ends__lt=self.ends) ).exists(): raise ValidationError('Event times overlap with existing record!') This works. Say an event starting 2020 Oct 11 @ 19:00, and ending 2020 Oct 11 @ 20:00, the following values will prompt an overlap: same date, starting @ 18:00, ending @ 21:00 same date, starting @ 19:30, ending @ 19:50 same date, starting @ 19:30, ending @ 20:50 But there are situations where the model's .clean() method will not be invoked, which may result in invalid data to be inserted. My question is, how can I enforce a constraint on the model, which will apply on the database itself, like unique_together does. I have used postgres specific fields like DateRangeField but in this case, their functionality is limited as they can … -
Google authentication using django-rest-auth and allauth
I am trying to create an authentication API for a flutter app that will log users in with a google authentication signup/login form. I followed this tutorial to achieve this. So far so good, except that the tutorial is based on a GitHub sign in rather than Google. I managed to get it working up till step "connecting" step. I am able to get the code from the redirect but when I access http://127.0.0.1:8000/auth/google/ I see it's asking for a two fields (access_token, code). When I try to just post with the information I do have I get the following error: "non_field_errors": [ "View is not defined, pass it as a context variable" ] -
How to user AJAX call to django DeleteView or CreatView or UpdateView?
class RegisterUser(CreateView): template_name = 'new_register.html' form_class = SignUpForm success_url = '/' def form_valid(self,form): user = form.save() password = form.cleaned_data.get('password') user.set_password(password) user.save() return JsonResponse({'url':reverse_lazy('accounts:dashboard')}) This is my CreateView and I want to return the redirection URL when the form submitted. I want to handle this URL in AJAX -
Querying and Filtering related models in DRF
I have Contact model to list the followers of an User object, I try to filter the contacts of a User but I still could not manage get a correct queryset. My Contact model is simple with two ForeignKey: class Contact(models.Model): user_from = models.ForeignKey(User,related_name='rel_from_set', on_delete=models.CASCADE,) user_to = models.ForeignKey(User,related_name='rel_to_set', on_delete=models.CASCADE,) def __str__(self): return '{} follow {}'.format(self.user_from, self.user_to) I have created serializers for User and Contact: ##Contact Serializer class ContactsSerializer(serializers.ModelSerializer): user_from = serializers.StringRelatedField(read_only=True) user_to = serializers.StringRelatedField(read_only=True) class Meta: model = Contact fields = ["user_from", "user_to"] ##UserSerializer class UserInformationSerializer(serializers.ModelSerializer): followers = ContactsSerializer(many=True, read_only=True) class Meta: model = User fields = ['first_name', 'last_name', 'followers'] And try to make a query through views: class FollowerListView(APIView): queryset = Contact.objects.all() serializer_class = ContactsSerializer lookup_field = "username" def get(self, request, format=None, slug=None): kwarg_username = self.kwargs.get("slug") user = User.objects.filter(is_active=1).filter(username=kwarg_username) print(user.username) contacts = Contact.objects.filter(user_to=user.id) serializer = ContactsSerializer(contacts) return Response(serializer.data) Now I get error message: AttributeError at /api/member/ytsejam/followers/ 'QuerySet' object has no attribute 'username' print(user.username) If i try print(user) I can see the user an Object. Can you guide me how to correct? Thanks -
Django wont save form data to postgres database
I have a from that won't save any data with form.save() method. It worked before I migrated my whole db to postgres. I think the problem might be in my models file. I'm really new to postgres. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.postgres.fields import ArrayField # Create your models here. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) weight = ArrayField( models.FloatField(max_length=20, blank=True, null=True), null=True, ) height = models.FloatField(max_length=20, blank=True, null=True) date = ArrayField( models.DateField(auto_now_add=True), null=True, ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) views.py from django.shortcuts import render from django.contrib import messages from django.contrib.auth.models import User from django.http import JsonResponse from django.shortcuts import get_object_or_404 from users import models from users.models import Profile from django.core import serializers from .forms import WeightForm import logging import json def home(request): form = WeightForm() if request.is_ajax(): profile = get_object_or_404(Profile, id = request.user.id) form = WeightForm(request.POST, instance=profile) if form.is_valid(): form.save() return JsonResponse({ 'msg': 'Success' }) return render(request, 'Landing/index.html',{'form':form}) -
Django - page doesn't reflect changed contents
So, I am talking about the basic stuff as well....when I make a change in some text it is not getting changed when I refresh, I have to stop the server and again do python manag.py runserver to see the changes -
How to use the created objects from get_or_create method?
Here if the object created I want to use this object in another model. How can I do it ? I suppose created returns the Boolean value so How can I get the created object ? value, created = MyModel.objects.get_or_create(field1=field1, field2=field2) if created: another_model_obj.manytomanyfield.add(created) -
Python, Graphql Mutation and Dango API
I am working on a project that takes signups from a Django form and transfers them to a website, the info is mainly the data ( Name, surname, email...) and some extra-information (tags). One of the scripts give me the following error in the cronjob_logs; Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django_cron/management/commands/runcrons.py", line 71, in run_cron_with_cache_check manager.run(force) File "/usr/local/lib/python2.7/dist-packages/django_cron/init.py", line 215, in run self.msg = self.cron_job.do() File "/home/django/django_project/ogx/cron.py", line 31, in do ep_id = get_ep_id(ep.email) File "/home/django/django_project/ogx/graph_helper.py", line 75, in get_ep_id ''', {"query": email}) File "/usr/local/lib/python2.7/dist-packages/graphqlclient/client.py", line 11, in execute return self._send(query, variables) File "/usr/local/lib/python2.7/dist-packages/graphqlclient/client.py", line 34, in _send raise e HTTPError: HTTP Error 500: Internal Server Error The script was working normally some time ago, as for the graph_helper.py it is as follows; def get_ep_id(email): client = GraphQLClient( '*this part I took off for confidentiality*') result = client.execute(''' query Myquery($query: String!){ allPeople(q:$query) { data { id full_name } } } ''', {"query": email}) data = json.loads(result) if len(data['data']['allPeople']['data']) > 0: return data['data']['allPeople']['data'][0]['id'] else: return None The cron.py in question is the following; class FetchEPsIDs(CronJobBase): RUN_EVERY_MINS = 30 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'ogx.FetchEPsIDs' # a unique code def do(self): eps_query = mc_ogx_app.objects.filter(ep_id__isnull=True) for ep in eps_query: ep_id = get_ep_id(ep.email) … -
Cross-app join queries for retrieving linked data
I am working on an app that will store customers and addresses in seperate apps. Some addresses will be customer linked, which I planned on doing by storing the pk for the customer against the address and for primary addresses I planned to link the opposite (address pk to customer field). I am unsure on how to pull the data from both apps into the table I'm populating to "view all". def customers(request): customer_list = customer.objects.all() context = { 'customer_list': customer_list, } return render(request, 'customers.html', context) The goal I am trying to achieve is to turn these 2 pk's into the addresses stored in my address app. I tried to implement foreignkeys with my current structure and was returned an error when creating a foreignkey in my customer model linking to addresses; primary_address = models.ForeignKey('addresses.addresses', on_delete=models.CASCADE) #django.db.utils.OperationalError: no such column: customers_customer.primary_address_id The goal I have set is to replace the primary keys in the below table with the addresses from the address model. I am newer to django and I could be approaching this the wrong way. File structure address.models from django.db import models # Create your models here. class addresses(models.Model): tenant_code = models.CharField(max_length = 6) customer_id = models.IntegerField(blank = … -
Submit python script through PHP/AJAX
I made a python script who can convert .MOV to .MP4 the thing is I want to execute the script from my website made on PHP. So the example is I'm browsing a video on the web page then I click on submit and I'm waiting for the python script executing. It's working already but now I need to adapt it to my actual website and the session cookie (PHP). But I don't know how to do that.. I saw on some forum that they use Flask or Django but my website is already built and I don't want to rebuilt it. Thank you -
django, typeerror: missing 1 required positional argument
models.py: class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) def doctor_code_create(DoctorList): last_doctor_code = DoctorList.objects.all().order_by('d_code').last() testhospital = DoctorList.objects.filter().values('h_code') if not last_doctor_code: return 'd' + '001' d_code = last_doctor_code.d_code doctor_int = int(d_code[3:7]) new_doctor_int = doctor_int + 1 new_d_code = 'd' + str(testhospital) + str(new_doctor_int).zfill(3) return new_d_code d_code = models.CharField(primary_key=True, max_length = 200, default = doctor_code_create, editable=False) error code: Got a `TypeError` when calling `DoctorList.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `DoctorList.objects.create()`. You may need to make the field read-only, or override the DoctorListSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\rest_framework\serializers.py", line 948, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\query.py", line 445, in create obj = self.model(**kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\base.py", line 475, in __init__ val = field.get_default() File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\fields\__init__.py", line 831, in get_default return self._get_default() TypeError: doctor_code_create() missing 1 required positional argument: 'DoctorList' I want to use h_code that exists in class DoctorList (models.Model) by putting it in doctor_code_create. I think it's right to use it like this, but I don't know what went wrong. Do I … -
ValueError: Field 'length' expected a number but got ''
models from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now from django.contrib.auth.models import User # Create your models here. class Allmusic(models.Model): sno=models.AutoField(primary_key=True) name=models.CharField(max_length=100,default="") author=models.CharField(max_length=100,default="") description=models.TextField(default="") movie=models.CharField(max_length=100,default="") category=models.CharField(max_length=100,default="") subcategory=models.CharField(max_length=100,default="") image=models.ImageField(upload_to='images', default="") musicfile=models.FileField(upload_to='music_file', default="") def __str__(self): return self.name class Watchlater(models.Model): watch_id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE) video_id=models.CharField(max_length=100000,default="") class BlogComment(models.Model): sno=models.AutoField(primary_key=True) comment=models.TextField() user=models.ForeignKey(User,on_delete=models.CASCADE) post=models.ForeignKey(Allmusic,on_delete=models.CASCADE) timestamp=models.DateTimeField(default=now) class History(models.Model): history_id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE) music_id=models.CharField(max_length=100000,default="") views.py from django.shortcuts import render,HttpResponse,redirect from .models import Allmusic,Watchlater,BlogComment,History from math import ceil from django.contrib.auth.models import User from django.contrib.auth import login,authenticate,logout from django.contrib import messages from django.db.models import Case,When # Create your views here. def home(request): return render(request,'home.html') def index(request): allProds = [] catprods = Allmusic.objects.values('category', 'sno') cats = {item['category'] for item in catprods} for cat in cats: prod = Allmusic.objects.filter(category=cat) n = len(prod) nSlides = n // 4 + ceil((n / 4) - (n // 4)) allProds.append([prod, range(1, nSlides), nSlides]) params = {'allProds':allProds} return render(request,'index.html',params) def indexmovie(request): allProds = [] catprods = Allmusic.objects.values('movie', 'sno') cats = {item['movie'] for item in catprods} for cat in cats: prod = Allmusic.objects.filter(movie=cat) n = len(prod) nSlides = n // 4 + ceil((n / 4) - (n // 4)) allProds.append([prod, range(1, nSlides), nSlides]) params = {'allProds':allProds} return render(request,'indexmovie.html',params) def about(request): return render(request,'about.html') def contact(request): return render(request,'contact.html') #Authenciation APIs … -
ImportError: cannot import name 'InvalidTokenError' from 'jwt'
ImportError: cannot import name 'InvalidTokenError' from 'jwt' -
How to generate presigned S3 urls using django storages?
I have a Django form which saves a file to s3 through the django-storages library and works fine. How can I generate and return a pre-signed url so the user can access the file temporarily after it is uploaded ? I have spent hours going through the Django-storages documentation however it is not very clear how to do this .. form.py class DocumentForm(forms.Form): docfile = forms.FileField( label='Select a file', help_text='max. 42 megabytes' ) name = models.CharField(max_length=20) uploaded_at = models.DateTimeField(auto_now_add=True) views.py def upload_file(request): if request.method == 'POST: form = DocumentForm(request.POST) if form.is_valid(): form.save() url = #generate pre-signed url of uploaded file here return render(request, 'upload_response.html, url) -
Wagtail modeltranslation language switcher doesn't work on /search page
I have added search url to i18n_patterns, but the language switcher doesn't work on that page. urls.py: urlpatterns += i18n_patterns( path("search/", search_views.search, name="search"), path("", include(wagtail_urls)), ) language switcher: {% get_available_languages_wmt as languages %} <div class="nav-item dropdown float-right"> <p class="nav-link dropdown-toggle m-auto" data-toggle="dropdown" role="button" aria-expanded="false"> {{ request.LANGUAGE_CODE|upper }}</p> <div class="dropdown-menu w-25"> {% for language in languages %} {% if language != request.LANGUAGE_CODE %} <a class="dropdown-item" href="{% change_lang language page %}">{{ language|upper }}</a> {% endif %} {% endfor %} </div> </div> Furthermore, when i add search url above root one the search page raises 404 page. How can i make the language switcher work on the search page? -
The view account.views.signup didn't return an HttpResponse object. It returned None instead
Trying to register user in Django. it keep giving me HttpResponse error signup.html templates location is : templates/registration/signup.html Here's what i tried: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): username = forms.CharField(max_length=50) class Meta: model = User fields = ('username', 'email', 'password1', 'password2', ) views.py from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.decorators import login_required from .forms import SignUpForm @login_required def home(request): return render(request, 'registration/home.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') user = authenticate(email= email, password= raw_password) login(request, user) return redirect('registration/home') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) I did tried replacing redirect with HttpResponseRedirect but it did't work Account urls.py from django.contrib.auth import views as auth_views from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ path("login/", auth_views.LoginView.as_view(template_name = "registration/login.html"), name='login'), path("logout/", auth_views.LogoutView.as_view(), name='logout'), path('home/', views.home, name='home'), url('signup/', views.signup, name='signup'), ] Error ValueError at /accounts/signup/ The view account.views.signup didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 3.0.3 Exception Type: ValueError Exception Value: The view account.views.signup didn't return an … -
How do I use the manyToMany relationship in a graphene scheme?
I'm trying to do a graphql query in django. I have a problem with the manuToManu relationship. Can I ask for help? I don't know where I go wrong. Part written in Python models.py class Topping(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) def __str__(self): return self.name class Pizza(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) toppings = models.ManyToManyField(Topping) schema.py class Query(graphene.ObjectType): pizza = graphene.List(PizzaType) topping = graphene.List(ToppingType) @staticmethod def resolve_pizza(parent, info): return Pizza.objects.all() @staticmethod def resolve_topping(parent, info): return Topping.objects.all() types.py class ToppingType(graphene.ObjectType): id = graphene.NonNull(graphene.Int) name = graphene.NonNull(graphene.String) class PizzaType(graphene.ObjectType): id = graphene.NonNull(graphene.Int) name = graphene.NonNull(graphene.String) toppings = graphene.List(ToppingType) Part written in Graphql query graphql query { pizza{ name toppings { name } } } response graphql { "errors": [ { "message": "User Error: expected iterable, but did not find one for field PizzaType.toppings." } ], "data": { "pizza": [ { "name": "mafia", "toppings": null } ] } }