Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display field from another model in django admin
Let say I have two model. I want to make subject field in Program model appear in UserProgramAdmin. What is the best way to do that? class Program(models.Model): name = models.CharField(max_length=15, blank=False) summary = models.CharField(max_length=200, blank=True) subject = models.ManyToManyField(Subject, related_name='all_subjects') is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) def __str__(self) -> str: return self.name class UserProgram(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) program = models.ForeignKey( Program, on_delete=models.CASCADE, ) is_active = models.BooleanField(default=True) is_finish = models.BooleanField(default=False, editable=False) /admin.py class UserProgramAdmin(admin.ModelAdmin): list_display = ('user', 'program' , 'is_active', 'is_finish') Thanks in advance -
How to change a field type in a Django model with existing data?
I have the following existing twitter field on the extended UserProfile model and I'd like to change the field type from a URLField to a CharField with max_length of 20. When I try to migrate the change, I get the error django.db.utils.DataError: value too long for type character varying(20). I do not care about existing data in that field and prefer they go blank if there is existing data when migrating. How can I change the field type and clear existing data? class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) # old field twitter = models.URLField(verbose_name="Twitter", blank=True) # new field # twitter = models.CharField( # max_length=20, verbose_name="Twitter Username", null=True, blank=True # ) -
dal.autocomplete and AutocompleteFilter don't work in model with foreign key to itself don't work in admin site
I wan't to make a filter on categories by parent category, I use a model and for parent category I linked to itself. the model: class Category(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="childs" ) description = models.TextField(null=True, blank=True) is_adult = models.BooleanField(default=False) is_active = models.BooleanField(default=True) in admin.py : class ParentCategoryFilter(AutocompleteFilter): title = "By parent category" field_name = "parent" autocomplete_url = "parent-category-autocomplete" is_placeholder_title = True class CategoryAdmin(admin.ModelAdmin): search_fields = ["name"] autocomplete_fields = ["parent"] fieldsets = ( ( _("Details"), { "fields": ( "name", "parent", "description", ), }, ), ) list_display = ( "name", "parent", ) list_filter = [ParentCategoryFilter] admin.site.register(Category, CategoryAdmin) and the views.py where ParentCategoryFilter is defined: class ParentCategoryAutocompleteView(autocomplete.Select2QuerySetView): permissions = [ "CategoryView", ] def get_queryset(self): qs = Category.objects.filter(parent__isnull=True) if self.q: qs = qs.filter(Q(name__istartswith=self.q)) return qs the problem I get is that in the filter I get the child's categories name. I don't know what the problem with it. -
ClientError at /saved_json/ An error occurred (403) when calling the HeadObject operation: Forbidden
I was trying to add images, json files to s3 bucket. It was going well about few months ago but i have opened it now and it shows an error on the line where the object of model is created. Error named: Exception Type: ClientError at /saved_json/ Exception Value: An error occurred (403) when calling the HeadObject operation: Forbidden for image in images: photo = Photo.objects.create( //eror is here email=data['email'], image=image, ) -
How to send emails with send_mass_mail in Django for more than one recipients dynamically?
I try to send an email to more than one recipients but I am doing something wrong. I try to use use a for loop to get the email addresses from the user. If I print the emails these are in this format: 'someone@xy.com'. But if I try to send them, only one user gets the email. views.py from django.shortcuts import render from django.core.mail import send_mass_mail from somemodels.models import Project import datetime import calendar def emails(request): today = datetime.date.today() weekday = today.weekday() month = datetime.date.today().month year = datetime.date.today().year cal = calendar.monthrange(year, month)[1] # az utolso nap az aktualis honapban firstday = datetime.date.today().replace(day=1) # az elso nap az aktualis honapban subject='hello' message='what's up?' from_email='myemail@gmail.com' for p in Project.objects.raw('SELECT * FROM somemodels_project INNER JOIN auth_user ON auth_user.id = othermodel_project.permitted_users'): recipient_list = p.email, print(recipient_list) if (today == firstday): messages = [(subject, message, from_email, [recipient]) for recipient in recipient_list] send_mass_mail(messages) print('Successfully sent') else: print('Not sent') return render(request, 'performance/emails.html') urls.py app_name = 'email' urlpatterns = [ path('emails/', login_required(views.emails), name='emails'), ] -
Django - dictionary update sequence element #0 has length 0; 2 is required
When I am logged out I cannot access my site anymore. Why does this happen? I doesn't matter what view I change I cannot access the site anymore. ValueError at /accounts/login/ dictionary update sequence element #0 has length 0; 2 is required Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/ Django Version: 3.2.5 Exception Type: ValueError Exception Value: dictionary update sequence element #0 has length 0; 2 is required Exception Location: /Users/lorenz/.conda/envs/netto_clone/lib/python3.10/site-packages/django/template/context.py, line 244, in bind_template Python Executable: /Users/lorenz/.conda/envs/netto_clone/bin/python Python Version: 3.10.4 Python Path: ['/Users/lorenz/PycharmProjects/netto_clone', '/Users/lorenz/PycharmProjects/netto_clone', '/Users/lorenz/Library/Application ' 'Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/213.6777.50/PyCharm.app/Contents/plugins/python/helpers/pycharm_display', '/Users/lorenz/.conda/envs/netto_clone/lib/python310.zip', '/Users/lorenz/.conda/envs/netto_clone/lib/python3.10', '/Users/lorenz/.conda/envs/netto_clone/lib/python3.10/lib-dynload', '/Users/lorenz/.conda/envs/netto_clone/lib/python3.10/site-packages', '/Users/lorenz/Library/Application ' 'Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/213.6777.50/PyCharm.app/Contents/plugins/python/helpers/pycharm_matplotlib_backend'] Server time: Fri, 01 Apr 2022 16:21:12 -0100 -
Django + Vue.js GET /ws HTTP/1.1 404 2292 error every second
I am building a project with Vue.js on the front-end and Django on the back-end. I am using port 8000 for Django and port 8080 for Vue.js. Every time I route to something on the 8080 port, I get this error like this that gets printed out every second: [01/Apr/2022 17:18:57] "GET /ws HTTP/1.1" 404 2292 Not Found: /ws I can't figure out why this happens or how to fix it. -
How to record audio from the mic and save it as a .wav file in django web app
I am trying to make and deploy speech emotion detection machine learning model using Django for that I have to take audio recording from the user before setting up the model, I am stuck at how can I take audio recording from the user and send it to my ML model to detect emotion. please help! -
Import csv file using django - form doesn't appear
I try to create a project and I need to import a csv file (Import csv file using django - Exception Type: DatabaseError) I want to display the form on other page, not on home. But, when I create a new path, it didn't display me that specific view. csvs/urls.py from django.urls import path from .views import upload_file_view app_name='csvs' urlpatterns =[ path('import/', upload_file_view, name='upload-view') ] csvs/views.py from django.shortcuts import render from .forms import CsvModelForm from .models import Csv import csv from django.contrib.auth.models import User from sales.models import Sales def upload_file_view(request): form = CsvModelForm(request.POST, request.FILES) if form.is_valid(): form.save() form = CsvModelForm() obj= Csv.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i==0: pass else: #row = "".join(row) #row = row.replace(";"," ") #row=row.split() #print(row) #print(type(row)) date = row[1] user = User.objects.get(username=row[0]) Sales.objects.create( date=date, product= row[2], user=user, ) obj.activated=True obj.save() return render(request, 'upload.html', { 'form': form }) main file - urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from sales.views import import_view, home_view urlpatterns = [ path('admin/', admin.site.urls), path('import/', import_view, name="import"), path('', home_view, name="home"), path('import/', include('csvs.urls', namespace='csvs')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) sales/views.py from django.shortcuts import render … -
How can I store data of registration into my django database?
I want to store data of patient from registration page to my django database using serializers but I am not sure how to do that!! Here I am attaching views.py file: from django.http import HttpResponse, HttpResponseForbidden from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout from rest_framework import viewsets from .models import * from .serializers import PatientSerializer class PatientView(viewsets.ModelViewSet): queryset = patient.objects.all() serializer_class = PatientSerializer def login_user(request): if request.method == 'POST': username = request.POST['Username'] password = request.POST['Password'] user_type = request.POST['user_type'] user = authenticate(username=username, password=password) #doctor is superuser and receptionist is normaluser if user is None: login(request, user) if user_type == 'Doctor': return render(request,'') elif user_type == 'Receptionist': return render(request, 'Auth/registration.html') else: return render(request,'') else: messages.error(request, "Bad Credentials") return redirect('login') return render(request, "Auth/login.html") def registration(request): if request.method == "POST": username = request.POST['username'] PID = request.POST['PID'] Name = request.POST['Name'] Age = request.POST['Age'] DOB = request.POST['DOB'] gender = request.POST['gender'] BG = request.POST['BG'] PN = request.POST['PN'] Add = request.POST['Add'] else: if request.user.is_staff: return render(request,'Auth/registration.html') else: return HttpResponseForbidden('<h1> 403 Forbidden <br>You are not allowed to access this page.</h1>') This is my registration.html file : <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> … -
Making a GET request with filter
My model is the following class PokerRoom(models.Model): STATUS = (("Pending", "Pending"), ("Finished", "Finished")) status = models.CharField( max_length=11, choices=STATUS, verbose_name=_("Status da Story"), default="Pending", ) name = models.CharField(max_length=200, verbose_name=_("room name"), validators=[alphanumeric]) slug = models.CharField(max_length=200, verbose_name=_("room slug"), null=True, blank=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) styleCards = MultiSelectField(choices=CHOICES, default=FIBONACCI) datetime = models.DateTimeField(null=True, blank=True) date = models.CharField(max_length=10, null=True, blank=True) user = models.ForeignKey(User, on_delete=DO_NOTHING) first_name_user = models.CharField( max_length=200, verbose_name=_("user name"), null=True, blank=True ) deck = models.ForeignKey(Pack, on_delete=models.CASCADE) index = models.IntegerField( null=True, blank=True, verbose_name=_("story being voted") ) I'm my application, I want to make a searchbar for "status" and "name" and do a GET request with those filter that would be provided by the client when he make the search. But I don't know how to do that in my views.py I was thiking in a GET method like this, but I don't know how to get the planningName and planningStatus from the frontend. def get(self, request, pk): """GET of PokerRoom historic""" user = request.user pk = self.kwargs["pk"] planningName = planningStatus = moderatorRoom = PokerRoom.objects.values("id", "first_name_user", "date", "name", "status", "styleCards", "datetime", 'slug' ).filter(Q(user= user) | Q(name=planningName) | Q(status=planningStatus)).order_by("-datetime") Can someone helpe me? -
How do I check if a record saved successfully in Django?
Could you take a look at this code below? It seems like the form is submitted and validated successfully. However, it doesn't seem to be saving to my database. Please check my comment in the post() method below starting with #####. I know in PHP one can print_r($var); exit; but can't seem to find equivalent in Python/Django. class ReportListView(ListView): model = ReportList form_class = ReportListForm initial = {} context_object_name = 'reportlists' template_name = "reports.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) #context['now'] = timezone.now() return context def get_queryset(self): return ReportList.objects.filter(user=self.request.user) def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): # process form cleaned data # name = form.cleaned_data.get('name') # .lower() new_report = form.save(commit=False) new_report.user = self.request.user new_report.save() ### what can I write to check if new report has been saved? ### also, how can I print something here to print that in the browser e.g. ### print(datavariable) ### exit() ?? or something to stop execution here so that I read previous print output return redirect('report') return render(request, self.template_name, {'form': form}) -
Queryset to filter exactly N objects from a table
I am trying to work out how to allocate exactly N available objects, in a way which is safe against concurrent activity. Is there a way to write a queryset that will fail if it cannot return at least N objects? This is probably an excess of caution for my particular application because the chances of a race are infinitesimal, but I'm curious What I know won't work is available = Foo.objects.filter( status=Foo.AVAILABLE).count() if available < N: #let the user know there aren't enough left # but now something concurrent may grab them! foo_qs = Foo.objects.select_for_update().filter(status=Foo.AVAILABLE)[:N] with transaction.atomic(): for foo in foo_qs: ... # quite a bit. In RL I will have locked related objects as well. foo.status=Foo.RESERVED foo.save() because slicing a queryset guarantees only no more than N objects. Removing the slice might lock a large number of rows that I don't need to lock. Is this inefficient? The whole Foo table won't be locked for long because I update only N objects and then exit the transaction. Is the only answer to grab the objects one at a time inside the transaction, or to get all of them as a list and re-check its length? with transaction.atomic(): foos … -
Django webhook receiver
I built a web hook receiver that takes JSON and creates a model object. It works fine with JSON. But someone I am receiving data from uses a different type of string data. I am currently just printing it out in the console. How would I convert this into a model object? The data they are sending looks like this: Phone1=4441114444&FirstName=Chris&LastName=Farley&DOB=1982-11-21&Email=test@test.com class Client(models.Model): first_name = models.CharField(blank =True, max_length=100) last_name = models.CharField(blank=True, max_length=100) phone = models.CharField(max_length=100, null=True, default="", blank=True) email = models.EmailField(max_length=100,default="", blank=True) @csrf_exempt def webhook(request): if request.method == 'POST': print(json.loads(request.body)) Client.objects.create( first_name=json.loads(request.body)['FirstName'], last_name=json.loads(request.body)['LastName'], phone=json.loads(request.body)['Phone1'], email=json.loads(request.body)['Email'] ) return HttpResponse(request.body, status=200) -
django problem trying to do mosh python Tutorial course
: [Errno 2] No such file or directory python manage.py runserver I tried the cd thing didn't workout Python Tutorial - Python Full Course for Beginners 5:05 project: building a website with Django -
why is the colour of button tag different as you can see in the image?
<!DOC TYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home Page</title> </head> <body> {%for message in messages%} <div class="alert alert-{{message.tags}}alert-disimissible fade show"role="alert"> <strong>Message:</strong>{{message}} <button type="button" class="close" data-dismiss="alert" aria-label="close"> <span aria-hidden="true">&times;</span> </button> </div> {% endfor %} <h3>Welcome!</h3> {%if user.is_authenticated%} <h3>hello{{fname}}</h3} <button type="submit"><a href="/signout">signout</a></button> {% else %} <button type="submit"><a href="/signup">SignUp</a></button> <button type="submit"><a href="/signin">SignIn</a></button> {% endif%} </body> </html> i am creating a django login form can you tell whats wrong with above code as the signout button is not displayed when i run it -
Geodjango Querying geometry returns pointer instead of geometry
I am trying to get a single MultiPolygon geometry in a Queryset from this model: class local_administrative_unit(models.Model): lau_id = models.IntegerField(primary_key=True) lau_name = models.CharField(max_length=150) adm_level_2 = models.ForeignKey('administrative_level_2', on_delete=models.PROTECT) geom = models.MultiPolygonField(srid=4326) trying it this way in the Django shell: local_administrative_unit.objects.get(lau_id=1).geom which returned: <MultiPolygon object at 0x7fb12af0ab10> when I pass this to the Centroid function, it does not what I was looking for: Centroid(Value(<MultiPolygon object at 0x7fb12af0ac90>)) Can you please tell me how I get the actual geometry to use it afterwards - for example for calculating the Centroid of that polygon? Looks like I am getting a pointer to what I am looking for instead of the actual thing. Thanks in advance. -
Import csv file using django - Exception Type: DatabaseError
I am trying to create a django project and I need to upload a csv file and create objects. I found a video: https://www.youtube.com/watch?v=t3BdM6JlAmY and https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html. My code: sales/model.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Sales(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.CharField(max_length=10, blank=False, null= False) product = models.CharField(max_length=10, blank=False, null= False) def __str__(self): return f"{self.user}" sales/admin.py from django.contrib import admin from .models import Sales admin.site.register(Sales) In the main project, settings, I added that part about Media. urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('csvs.urls', namespace='csvs')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) csvs/models.py from django.db import models class Csv(models.Model): file_name = models.FileField(upload_to='csvs') uploaded = models.DateTimeField(auto_now_add = True) activated = models.BooleanField(default= False) def __str__(self): return f"File id: {self.id}" csvs/forms.py from django import forms from .models import Csv class CsvModelForm(forms.ModelForm): class Meta: model = Csv fields =('file_name',) and views.py from django.shortcuts import render from .forms import CsvModelForm from .models import Csv import csv from django.contrib.auth.models import User from sales.models import Sales def upload_file_view(request): form = CsvModelForm(request.POST, request.FILES) if form.is_valid(): form.save() form = CsvModelForm() obj= Csv.objects.get(activated=False) with open(obj.file_name.path, 'r') … -
DJANGO update is_active when email_confirmed is checked
On the Django admin interface, when I check email_confirmed under the Profile model, is there a way for me to automatically update is_active under the Djangos authentication User model? Linking them together in a way. Would like the ability to be able to check both with 1 click if a user hasn't recieved their sign-up email. Profile.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) unique_id = models.UUIDField(null=False, blank=False, default=uuid.uuid4, unique=True, editable=False) email_confirmed = models.BooleanField(default=False) def __str__(self): return self.user.username admin.py @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'email_confirmed') search_fields = ('user__email',) readonly_fields = ('user', 'unique_id') fieldsets = ( ('Details', { 'fields': ('unique_id', 'user') }), ('Status', { 'fields': ('email_confirmed') }), ('Timezone', { 'fields': ('timezone') }), ) I have looked into using @reciever(setting_changed) in Profile.py, but didn't quite understand. Similarly I have looked into the following in admin.py, and trying to set is_active to true in there but to no avail. def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "email_confirmed": Thank you in advance for you help -
Referencing User ID in Django URL dispatcher
I'm trying to implement a search feature where user's can search an email on a React frontend and it'll return that email's top 5 love languages. Currently the url path requires the primary key of a love language model, but I want it to use the user id. I have this Django URL set as: path('love-languages/', LovesView.as_view(), name='love-languages'), path('love-languages/<int:pk>', LoveView.as_view(), name='love-languages') Relevant love language model: class Love(models.Model): # Obtaining the user from the user model user = models.ForeignKey( get_user_model(), on_delete = models.CASCADE ) # Defining the dropdown choices class LoveLanguages(models.TextChoices): ACTS_OF_SERVICE = 'Acts of Service' RECEIVING_GIFTS = 'Receiving Gifts' QUALITY_TIME = 'Quality Time' WORDS_OF_AFFIRMATION = 'Words of Affirmation' PHYSICAL_TOUCH = 'Physical Touch' one = models.CharField(max_length=20, choices=LoveLanguages.choices) two = models.CharField(max_length=20, choices=LoveLanguages.choices) three = models.CharField(max_length=20, choices=LoveLanguages.choices) four = models.CharField(max_length=20, choices=LoveLanguages.choices) five = models.CharField(max_length=20, choices=LoveLanguages.choices) and love language views: class LovesView(APIView): def get(self, request): loves = Love.objects.filter(user=request.user.id) data = LoveSerializer(loves, many=True).data return Response(data) def post(self, request): request.data['user'] = request.user.id love = LoveSerializer(data=request.data) if love.is_valid(): love.save() return Response(love.data, status=status.HTTP_201_CREATED) else: return Response(love.errors, status=status.HTTP_400_BAD_REQUEST) class LoveView(APIView): def get(self, request, pk): love = get_object_or_404(Love, pk=pk) # if request.user != love.user: # raise PermissionDenied('Unauthorized, you are not signed in as this user') # else: data = LoveSerializer(love).data … -
How to filter a queryset of objects created more than one hour ago from Django's DateTimeField?
Problem: I'm trying to filter a model where the status has not changed in over an hour. What I've tried: Product.objects.filter( Q(status="PENDING"), Q(created__hour__gt=1) ).all().order_by("-created") Expected Solution: Get a queryset of objects whose status is "PENDING" but has not changed in more than one hour. -
Fetch image and crop before save django
I'm using django. I have a code that will parse an HTML code and try to get and save the image to the database. Here is the code: link = content[content.find( 'src=')+5:content.find('alt')-2] img_data = requests.get(link).content with open('temp_image.jpg', 'wb') as handler: handler.write(img_data) with open('temp_image.jpg', 'rb') as handler: file_name = link.split("/")[-1] post.cover.save(file_name, files.File(handler)) os.remove("temp_image.jpg") But I also need to crop the image. How can I do that? Thank you. -
Customized CreateModelMixin - Object creation defined in my Model
My rest api view defines only two methods: class RequestSerializerViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): i have some experience overwriting the list, but i have no experience overwriting create as it seems to be a lot more complicated. What i want to achieve is following. My Request model has a special method which creates instance of Requests - start_request. This method creates not only the instance of Request, but also some additional foreign objects and assings them to the newly created Request. So my goal would be to modify rest api POST (create, perform_create, or serializer - i have no idea atm. which is the correct way) method so, that it does not create the Request on its own, instead, uses start_request method of the model. What would be the best django approach to this? -
not able to login with false credentials
Not able to login when I try to register user using react 0 upvotes Anil Kumar · Lecture 42 · 31 minutes ago when i tried to register user from react, the user was registered successfully, but when i tried to login with those credentials its showing "TypeError at /api/users/login/ Object of type Response is not JSON serializable" but I can login if i register the user using postman, class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): try: data = super().validate(attrs) # data['username'] = self.user.username serializer = UserSerializerWithToken(self.user).data for k, v in serializer.items(): data[k] = v return data except: message = {'detail': f'Cannot find the user!'} return Response(message) # @api_view(['POST']) def registerUser(request): data = request.data try: user = NewUser.objects.create_user( email=data['email'], first_name=data['first_name'], last_name=data['last_name'], password=data['password'], username=data['first_name'] + data['last_name'], is_active=True, is_student=True, ) serializer = UserSerializerWithToken(user, many=False) # successMessage = "user Registered successfully!" emailSending(user.email) return Response(serializer.data) except Exception as e: message = {'detail': f'User with email: {data["email"]} already exists'} # return Response(message, status=status.HTTP_400_BAD_REQUEST) return Response(message) here is the code in react export const register = (email, first_name, last_name, password) => { return dispatch => { dispatch(registerAuthStart()); const config = { headers: { 'content-type': 'application/json' } } const body = JSON.stringify({ email, first_name, last_name, password }); console.log(body); // … -
Why would object.pk be None in get_success_url in CreateView?
I have a CreateView to which after creation I'd like the user to be directed to the DetailView for that newly created instance. class ModelCreateView(LoginRequiredMixin, CreateView): model = Model template_name = 'models/model-create-template.html' In my get_success_url method, I use self.object.pk, but it is None. def get_success_url(self): return f'/model/{self.object.pk}' I can see that I reach a successful save() since my post_save signals are firing, and form_valid() is called as well, since I update the user in this method. When I look in my debugger at self.object, all of the other fields are populated, by id and pk are both None. Looking at the instance in admin, I can confirm these are actually being set correctly, but for some reason at the time of calling get_success_url I don't have access to this data. Is the instance in self.object actually the created instance, or is it just representing the fields submitted by the CreateView form? If its the former, how could I access the instance in get_success_url?