Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python django webapp packaging sdist
When I run python setup.py sdist in my project directory and check the contents with tar --list -f .\dist\my_project_name-1.0.tar.gz I see one important python file (manage.py) and a couple of directories templates, which contains .html files, and static, containing .css files, are missing. I've looked at many questions: Q1 Q2 Q3 Q4 but adding a MANIFEST.in or adding the following lines to my setup.py didn't change anything. And what about my manage.py? Shouldn't python files be included by default with sdist? include_package_data=True, data_files=[('templates','my_app/templates/my_app/*.html']), ('static', ['my_app/static/my_app/static/css/*.css'])] Also, I get the same exact result with python setup.py sdist bdist_wheel (although I'm not sure what's the difference with the two commands). -
flow of code from view to serializer class in django rest framework
I am trying to understand the code flow in Django rest framework from view class to serializer class. Like we know if we create an object of a class, the class gets instantiate with that object. And if there are other functions inside that class, we can call that function using the object we just created followed by dot and that function name. It looks something like this. class Person: def __init__(self, name, address): self.name = name self.address = address def details(self): print (f"My name is {self.name} and I live in {self.address}") obj1 = Person("John","London") obj1.details() For example in the above code, when we run obj1= .... , the person class will instantiate with values name and address. And then we can call the details function using the class object that we just created obj1. Now in Django Rest, class LeadsView(APIView): permission_classes = [IsAuthenticated] def put(self, request, pk=None, *args, **kwargs): id = pk abc = Lead.objects.get(id=id) print("before serializer") serializer = LeadSerializer(abc,data=request.data) if serializer.is_valid(): print("after serializer validation") serializer.save() print("after save") return Response({ "message": "Coupon hase been updated", "data": serializer.data }, status=status.HTTP_200_OK) return Response(serializer.data) class Leadserializer(serializers.ModelSerializer): class Meta: model = Lead fields = 'all' def update(self,instance,validated_data): .......... print("iam inside the serializer class") … -
How to fix "assess has been blocked by CORS policy: No 'Access-Control-Allow-Origin' in react
I have a web application with react frontend and django backend. Some of the APIs from the backend are being blocked by cors policy whereas others are not. For example, The API to fetch blog posts const res = await axios.get(`${process.env.REACT_APP_API_URL}/blog/posts`) is returning data but the API for individual posts const res = await axios.get(`${process.env.REACT_APP_API_URL}/blog/${slug}`); is blocked. The register and login APIs are blocked too. I have added the domain to the list of allowed url in settings.py but that didn't solve the issue. The error I'm getting in the detail page is: undefined:1 Access to XMLHttpRequest at 'https://.api.example.co/blog/undefined' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. When I use Postman to test the API's everything works properly. But In react app it's only the API that list posts or items that are returning data, others are blocked. Why such behaviour, and how do I fix it? -
gcloud builds submit of Django website results in error "does not have storage.objects.get access"
I'm trying to deploy my Django website with Cloud Run, as described in Google Cloud Platform's documentation, but I get the error Error 403: 934957811880@cloudbuild.gserviceaccount.com does not have storage.objects.get access to the Google Cloud Storage object., forbidden when running the command gcloud builds submit --config cloudmigrate.yaml --substitutions _INSTANCE_NAME=trouwfeestwebsite-db,_REGION=europe-west6. The full output of the command is: (the error is at the bottom) Creating temporary tarball archive of 119 file(s) totalling 23.2 MiB before compression. Some files were not included in the source upload. Check the gcloud log [C:\Users\Sander\AppData\Roaming\gcloud\logs\2021.10.23\20.53.18.638301.log] t o see which files and the contents of the default gcloudignore file used (see `$ gcloud topic gcloudignore` to learn more). Uploading tarball of [.] to [gs://trouwfeestwebsite_cloudbuild/source/1635015198.74424-eca822c138ec 48878f292b9403f99e83.tgz] ERROR: (gcloud.builds.submit) INVALID_ARGUMENT: could not resolve source: googleapi: Error 403: 934957811880@cloudbuild.gserviceaccount.com does not have storage.objects.get access to the Google Cloud Storage object., forbidden On the level of my storage bucket, I granted 934957811880@cloudbuild.gserviceaccount.com the permission Storage Object Viewer, as I see on https://cloud.google.com/storage/docs/access-control/iam-roles that this covers storage.objects.get access. I also tried by granting Storage Object Admin and Storage Admin. I can't add a "Viewer" role too (https://stackoverflow.com/a/68303613/5433896), it's not one of the options in the permissions list. I enabled Cloud run in the Cloud … -
Unable to do migrations using docker.yml file- django+postgres
I get the following error while I try to run my django project on docker. relation "DBTable" does not exist at character 218 I figured out it was because the migrations weren't being applied. So I changed my Dockerfile as follows to make migrations before starting the server: FROM python:3.7 WORKDIR /ServerCode2/ COPY . /ServerCode2/ RUN pip install -r req.txt EXPOSE 8000 CMD ["python", "manage.py", "makemigrations" ] CMD ["python", "manage.py", "migrate" ] CMD ["python", "manage.py", "runserver", "--noreload" ] Below is my docker-compose.yml file version: '3.7' services: server: build: context: ./Appname dockerfile: Dockerfile image: serverimgtest1 container_name: servercontest1 ports: - 8000:8000 links: - db:db depends_on: - db db: image: postgres environment: POSTGRES_DB: "DBname" POSTGRES_HOST_AUTH_METHOD: "trust" ports: - 5432:5432 client: build: context: ./appfrontend dockerfile: Dockerfile image: clientimgtest1 container_name: clientcontest1 depends_on: - server ports: - 3000:3000 However, I still see the error which says the relation does not exist. Is there any way I could achieve migrations through commands in dockerFile? -
I've a problem with django admin login with abstract superuser
I am developing a separate author abstract model for my blog site. The authors in this abstract model connect to my post application, another application of mine, with a foreign key and create the author-post relationship. However, I can't even log in to the django admin panel, it says my password is wrong, but I'm sure it's correct. what is the reason of this? this is my abstract user model code from django.contrib.auth.base_user import BaseUserManager from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin,) class CustomAccountManager(BaseUserManager): def create_superuser(self,email,firstName,lastName,password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get("is_staff") is not True: raise ValueError("Buraya erişim izniniz bulunmamaktadır. Lütfen yöneticiyle iletişime geçiniz.") if other_fields.get("is_superuser") is not True: raise ValueError("Buraya erişim sadece En üst düzey kullanıcılar içindir. Lütfen yöneticiyle iletişime Geçiniz") return self.create_user(email,firstName,lastName,password, **other_fields) def create_user(self, firstName,lastName,email,password, **other_fields): if not email: raise ValueError(_("Email Adresinizi Doğrulamalısınız!")) email = self.normalize_email(email) user = self.model(email=email,firstName=firstName,lastName=lastName, **other_fields) user.set_password(password) user.save() return user class Author(AbstractBaseUser,PermissionsMixin): id = models.AutoField(primary_key=True) firstName = models.CharField(max_length=100) email = models.EmailField(_("email adresi"),max_length=100,unique=True) lastName = models.CharField(max_length=100) displayName = models.CharField(max_length=300) gender = models.CharField(max_length=50) avatar = models.ImageField(upload_to="avatar") bgImage = models.ImageField(upload_to="background") slug = models.SlugField(editable=False, unique=True) desc = models.TextField() jobName = models.CharField(max_length=50,default="Author Job") … -
ModuleNotFoundError: No module named 'tokenize'
So I tried to start a Django project called 'Tokenize' and it gave me the error - Command Error: 'tokenize' conflicts with the name of an existing Python module and cannot be used as a project name. Please try another name. I then deleted all of my tokenize.py files from my computer and it's now giving me this error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/bin/pip", line 5, in from pip._internal.cli.main import main File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pip/_internal/cli/main.py", line 4, in import logging File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/logging/init.py", line 26, in import sys, os, time, io, re, traceback, warnings, weakref, collections.abc File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/traceback.py", line 5, in import linecache File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/linecache.py", line 11, in import tokenize ModuleNotFoundError: No module named 'tokenize' I searched everywhere and can't out how to fix this issue. I know I screwed up but any assistance is appreciated. -
(Django) type object 'User' has no attribute 'USERNAME_FIELD'
Down here I'm trying to create a custom user registration form and this is the error I keep getting: That is the result of me using UserCreationForm in place of forms.ModelForm according to many sources. I tried setting USERNAME_FIELD = username but it said The field 'username' clashes with the field 'username' from model 'members.user' Before I switched to UserCreationForm the registration did not even create any new user. I successfully created the login functionality, but failed when it came to the registration. It did not show any response after registration form submission. My code is as followed: members/models.py class User(models.Model): username = models.CharField(max_length=50, error_messages=login_errors_mess) password = models.CharField(max_length=50, error_messages=password_errors_mess) members/forms.py class RegisterForm(UserCreationForm): class Meta: model = User fields = [ 'username', 'password', ] widgets = { 'username': forms.TextInput(attrs={ 'class': 'form-control', 'data-val': 'true', 'data-val-required': 'Please enter your user name'}), 'password': forms.TextInput(attrs={ 'class': 'form-control', 'data-val': 'true', 'data-val-required': 'Please enter your password' }), } members/views.py def register(request): form = RegisterForm() if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('login') # return redirect('login') form = RegisterForm() return render (request, "registration/register.html", context={"form": form}) templates/registration/register.html <form method="POST" action="/register/"> {% csrf_token %} {% comment %} {{ form }} {% endcomment %} <div class="form-group"> <label … -
JWT authentication returns AnonymousUser in Django Rest Framework with SimpleJWT
I am opening this question as a last resort. I am learning JWT and want to implement it on my django app. I didn't have any issues regarding Basic auth and Token auth, but JWT doesn't authenticate my user... This is my settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', 'api.permissions.AdminOrTeacherOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } This is my view: class StudentList(APIView): authentication_classes = [] permission_classes = [AdminOrTeacherOnly] def get(self, request, format=None): students = Student.objects.all() serializer = StudentListSerializer(students, many=True) if not serializer.data: return Response(status=status.HTTP_204_NO_CONTENT) return Response(serializer.data, status=status.HTTP_200_OK) This is my AdminOrTeacherOnly permission class: class AdminOrTeacherOnly(permissions.BasePermission): """ Object-level permission to only allow teachers of a student to edit. Assumes the model instance has an `owner` attribute. """ message = 'Only admin or teacher can edit student detail.' def has_permission(self, request, view): # Only teacher and/or admin user will be able to, # edit and/or list this view. is_staff = bool(request.user and request.user.is_staff) is_teacher_group = str(request.user.groups.all().first()) == 'teacher' return is_staff or is_teacher_group I am able to get refresh and access token successfully: Then, I am adding this to Headers as follows and send a request: On debugger, when it enters the permission class: Here, request.user returns <django.contrib.auth.models.AnonymousUser object at 0x104f5afd0> I don't … -
How can I solve it - Django problem with sql on heroku
I have such a problem with Django and possibly sql on herok. The localhost application works without errors. However, after uploading to the heroku, an error was received. ProgrammingError at / relation "zpiappa_images" does not exist LINE 1: INSERT INTO "zpiappa_images" ("name", "user_id", "images", ".. My code in models looks like this: class Images(models.Model): name = models.CharField(max_length=64) user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, ) images = models.ImageField(upload_to='images') editted_images = models.ImageField(upload_to='filters', null=True, blank=True) is_editted = models.BooleanField(default=False, null=True, blank=True) def __str__(self): return self.name def save(self): self.editted_images.save(self.images.name, self.images, save=False) super(Images, self).save() class Meta: verbose_name = 'Image' verbose_name_plural = 'Images' How can I solve it? -
How to display particular table row in javascript
I want to display the table row based on the checkbox selection where I need to display only the particular row. I'm noob in JavaScript and took this snippet from stackoverflow. I tried to modify the code as per the requirement but I couldn't able to figure out. this is my data which I retrieve from the database In the JS script it matching the td value but I don't mention the table value explicitly all it comes from the db.im trying to figure it out since 2days ur help will be much appreciated <div>Country</div> <div class="row" name="country_checkbox" id="id_row" onclick="return filter_type(this);"> <ul id="id_country"> <li><label for="id_country_0"><input type="checkbox" name="country" value="NORTHAMERICA" placeholder="Select Country" id="id_country_0"> NORTHAMERICA</label> </li> <li><label for="id_country_3"><input type="checkbox" name="country" value="LATAM" placeholder="Select Country" id="id_country_3"> LATAM</label> </li> <li><label for="id_country_2"><input type="checkbox" name="country" value="ASIA" placeholder="Select Country" id="id_country_2">ASIA</label> </li> </ul> </div> <table class="datatable" id='table_id'> <thead> <thead> <tr> <th>Region</th> <th> Area </th> <th> Country </th> </tr> </thead> <tbody> <tr id="trow"> {% for i in database%} <td>i.Region</td> <td>i.Area </td> <td>i.Country</td> </tr> </tbody> <script> // checkbox selection function filter_type(box) { //alert("checked"); var cbs = document.getElementsByTagName('input'); var all_checked_types = []; for(var i=0; i < cbs.length; i++) { if(cbs[i].type == "checkbox") { if(cbs[i].name.match(/^country/)) { if(cbs[i].checked) { all_checked_types.push(cbs[i].value); } } } } if … -
Directly render html page on specific element without scroll (Django/JavaScript)
My question is about controlling page scrolling/anchor targets while using Django and Bootstrap. I have a Django project styled using Bootstrap. Information is rendered sequentially on a page. New information is added to the bottom of the page each time a user presses a button. This is achieved through loading all the information into a dictionary, but only rendering specific sections of it depending on a variable count which stores how far the user is through the case. When the button is pressed, information is passed to a view which checks its integrity and if acceptable increments a count variable and redirects the user back to the original page. The original page now shows new information because of the incremented count variable. I am trying to use anchors with the URL redirect to ensure the page loads on the new information. These anchors work, but the page is loading from the top each time a user presses the button to advance and then the page scrolls down. Ideally the page would load directly on the new information or reload where the user clicked submit and then scroll to the new information. A section of the view to demonstrate the current … -
django filter user for send activate sms
When the user fills in the registration form, the information entered in the database is saved and an account activation SMS is sent to him, but if the user for any reason can not enter the activation code and wants to fill out the registration form from the beginning, he will encounter an error. I used ---- filter(phone_number=phone_number, verify = False).exists(): ----- to filter the user, but I think there is a problem with how i write the code forms class RegistrationForm(forms.ModelForm): user_name = forms.CharField( min_length=4, max_length=50, help_text='Required' ) phone_number = forms.CharField(max_length=11, error_messages={ 'required': 'با عرض پوزش ، شما به یک شماره تلفن نیاز دارید'}, validators=[RegexValidator(regex=r'09(\d{9})$')], ) password = forms.CharField(widget=forms.PasswordInput) def clean_phone_number(self): phone_number = self.cleaned_data['phone_number'] if User.objects.filter(phone_number=phone_number).exists(): raise forms.ValidationError( 'Please use another Email, that is already taken') return phone_number views def account_register(request): if request.user.is_authenticated: return redirect("store:home") if request.method == "POST": registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.phone_number = registerForm.cleaned_data["phone_number"] user.set_password(registerForm.cleaned_data["password"]) user.is_active = False user.save() code_user = f"{user.code}" print(code_user) #send_sms return render(request, "verificationpage.html", {"form": registerForm}) else: return HttpResponse("Error handler content", status=400) else: registerForm = RegistrationForm() return render(request, "login.html", {"form": registerForm}) -
Counting items in a queryset
This works RoomBookings.objects.filter(HotelName__HotelName__icontains=hotel.HotelName, RoomType__icontains= hotel.RoomType).count() But this doesn't work queryset2 = RoomBookings.objects.filter(HotelName__HotelName__icontains=hotel.HotelName, RoomType__icontains= hotel.RoomType), print(queryset2.count()) And I have also tried print(queryset2.objects.count()) print (queryset2.objects.all().count()) print (queryset2.objects.all().len()) print (queryset2.objects().filter().count()) print (queryset2.len()) print (queryset2.all().len()) print (queryset2.objects.len()) -
Django unit testing if a POST request properly updates a model instance
I'm having trouble understanding why my test keeps failing. I have two models (only showing relevant code): class Listings(models.Model): listing_instagram = models.URLField(null=True, blank=True) listing_facebook = models.URLField(null=True, blank=True) ... class ListingsDescription(models.Model): listing = models.OneToOneField(Listings, on_delete=models.CASCADE) space_description = models.TextField(max_length=1000, blank=True) accessibility_description = models.TextField(max_length=1000, blank=True) ... I have a properly functioning view that processes two forms (one form per model): def some_view(request, listing_id): listing = get_object_or_404(Listings, id=listing_id) listing_description = listing.listingsdescription if request.method == "POST": form_a = ListingForm(request.POST or None, instance=listing) form_b = ListingDescriptionForm(request.POST or None, instance=listing_description) if form_a.is_valid() and form_b.is_valid(): form_a.save() form_b.save() messages.success(request, "Changes Made") return HttpResponseRedirect(reverse('destination') Manual testing on my browser works fine, and all fields are properly saved in the database. However, running below test: class ListingJourney(TestCase): @classmethod def setUpTestData(cls): cls.client = Client() # Create Listing cls.listing = ... def listing_post(self): self.assertTrue(Listings.objects.filter(id=self.listing.id).exists()) response = self.client.get(reverse('new_listing', kwargs={'listing_id': self.listing.id}), follow=True) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name='foo/listing.html') response = self.client.post(reverse('new_listing', kwargs={'listing_id': self.listing.id}), follow=True, data={ 'space_description': "Lorem ipsum dolor", 'neighborhood_description': "Lorem ipsum dolor", 'listing_instagram': "https://www.instagram.com/listing/", 'listing_facebook': "https://www.facebook.com/listing/", # some more data }) self.assertRedirects(response, reverse('redirect', kwargs={'listing_id': self.listing.id}), status_code=302, target_status_code=200, fetch_redirect_response=True) self.assertEqual(self.listing.listingsdescription.space_description, "Lorem ipsum dolor") self.assertEqual(self.listing.listing_facebook, "https://www.facebook.com/listing/") self.assertEqual(self.listing.listing_instagram, "https://www.instagram.com/listing/") The test fails at: self.assertEqual(self.listing.listing_facebook, "https://www.facebook.com/listing") Traceback (most recent call last): File "...\tests.py", line 153, in listing_post self.assertEqual(self.listing.listing_facebook, "https://www.facebook.com/listing/") AssertionError: … -
How to create factory-boy factories for Django models with foreign key
Im trying to test api post method with factory boy, but im getting errors. I get error: ValueError: Cannot assign "'User 0'": "CustomUser.user" must be a "User" instance. tests.py: class UserFactory(factory.django.DjangoModelFactory): class Meta: model = CustomUser user = factory.Sequence(lambda n: "User %d" % n) class EventFactory(factory.django.DjangoModelFactory): class Meta: model = Event user = factory.SubFactory(UserFactory) john = EventFactory() my model: class Event(models.Model): name = models.CharField('the name of the event', max_length=255) created_at = models.DateTimeField(default=timezone.now, validators=[LessThanNowValidator()]) additional_data = models.CharField(max_length=300, blank=True, default='') created_by = models.ForeignKey(User, on_delete=models.CASCADE) class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) api_token = models.CharField(max_length=100, blank=True, null=True, unique=True) -
Access content for Anonymous and logedIn User
How best can I access content while the user is not logged in. For example, I have the View which handles both Listing and posting blog posts , though I want someone to access content even without being logged In, though the person shouldn't create a blog post, unless logged In. Below is my current implementation : class PostList(generics.ListCreateAPIView): """Blog post lists""" queryset = Post.objects.all() serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = [permissions.IsAuthenticatedOrReadOnly] def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context=request) if serializer.is_valid(): serializer.save() return response.Response(serializer.data, status=status.HTTP_201_CREATED, ) return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) So how best can I play with these lines : authentication_classes = (JWTAuthentication,) permission_classes = [permissions.IsAuthenticatedOrReadOnly] because when I remove this line : authentication_classes = (JWTAuthentication,) I can access the lists of blogs, though I will need an endpoint of creating a blog posts to be protected, how best can this be achieved -
I am having trouble my forms.py file, got an error "KeyError 'request' "
view.py class AssignAgentView(OrganizerLoginRequired, FormView): template_name = "leads/assign_agent.html" form_class = AssignAgentForm def get_from_kwargs(self): return { "request": self.request } def get_success_url(self): return reverse("leads:lead-list") form.py class AssignAgentForm(forms.Form): agent = forms.ModelChoiceField(queryset=Agent.objects.none()) def __init__(self, *args, **kwargs): request = kwargs.pop('request') agents = Agent.objects.filter(organization=request.user.userprofile) super(AssignAgentForm, self).__init__(*args, **kwargs) self.fields["agent"].queryset = agents As you can see I am passing request as a key-value and runserver i got this File "C:\Users\sarfa\Desktop\tutorial\leads\forms.py", line 42, in __init__ request = kwargs.pop('request') KeyError: 'request' -
Extra tables in Django's admin group permission list
I have run a few fake migrations yesterday and also renamed a few tables of my database direcly yesterday due to foreign key constraints and other similar errors Django kept throwing at me after renaming some models. I know this is not standard procedure and it's prone to messing up things. It did solve everything for me though, without the need of wiping out the database, as I was almost resolved to do. Anyway, as I said, all is working great, expect for the list shown in the 'available permissions' in the Group management. The following (and other) tables are not in the database, and indeed are not even prepended with the applications's name: Where are those sourced from? How can I get rid of them? -
How to pass aggregate array to javascript?
I have a list in Django views, and I want to pass it to Javascript for iteration, I've tried serveral way but seems like the data can't be used by the js, could anyone have a look, please? views.py ''' def visualisation(request, project_id): project = Project.objects.get(id=project_id) todos = project.todo_set.filter(status='to_do') progresses = project.todo_set.filter(status='in_progress') dones = project.todo_set.filter(status='done') counts_data = Todo.objects.aggregate( to_do_count = Count('pk', filter=Q(status='to_do')), in_progress_count = Count('pk', filter=Q(status='in_progress')), done_count = Count('pk', filter=Q(status='done')) ) return render(request, 'todo_lists/progress.html', counts_data) ''' html ''' data: { labels: ['todo','inprogress','done'], datasets: [{ label: '# of Votes', data: [{% for todo in data %} {{ todo }}, {% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)' ], borderWidth: 1 }] } ''' -
Using a model as a source for a PK for diffrent model?
So if I have a simple model that I want as a source of my PK like so: class PostCreation(models.Model): pk = models.AutoField(primary_key=True) post = models.OneToOneField(Post, on_delete=models.CASCADE) What I want to do is create a PK of a blog post before the post has been created. My reasoning is I want the images/files I upload to be in a format of /media/blogPK/files So my Post will have a id/PK field set from the PostCreation class above And the Pseudo code is below: id = PostCreation() FileField(upload_to='{}{}{}'.format(id, '/', files)) But how can I create the PK first and then pass it to my Post model and then set the Post is/pk to that of PostCreation? I's going to be using ModelForm to output the fields for the Post content, Description/Date etc so when I goto visit that view I want the pk/id already made even if the user does submit the content of the Post model. How can I do this? Is it possible? Thx -
Django Token objects update error : django.db.utils.IntegrityError: UNIQUE constraint failed: authtoken_token.user_id
I was using django user class and rest_framework Token class to store the user info and the token. For the same I was using serializers.ModelSerializer class. But when I am making update request(check update method) to update the user info as well as the token that I have, its giving me error. Here is serializers.py from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.authtoken.views import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] extra_kwargs = { 'password' : { 'write_only':True, 'required': True } } def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) # create token for the user return user def update(self, instance, validated_data): instance.username = validated_data['username'] instance.set_password(validated_data['password']) instance.save() Token.objects.update(user=instance) return instance views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsAuthenticated, IsOwnerOfObject] authentication_classes = (TokenAuthentication,) urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('users', UserViewSet, basename = 'users') urlpatterns = [ path('api/', include(router.urls)), ] Error : django.db.utils.IntegrityError: UNIQUE constraint failed: authtoken_token.user_id This is how I am making the request with the authorisation token in the header field: -
AJAX response doesn't print in console
I am using ajax to get form data from Django application and I want to print the response in the console. $.ajax({ type: 'GET' , url: url, data: {'PUITS': PUITSId }, dataType: "json", success: function (response){ console.log(response) var response = JSON.stringify(response); var response = JSON.parse(response); console.log(response.PUITS); console.log(response.DUSE); console.log(response.CS); the first console.log(response) gives me this data: [{"model": "measure.surveillancedespuits", "pk": 15, "fields": {"PUITS": "1", "DATE_TEST": "2021-09-10", "MODE": "GL", "CS": "1", "SITUATION": "O", "DUSE": "27", "PRES_TBG": "27", "PRES_CSG": "27", "PRES_AVD": "27", "RESEAU_GL": "27", "ANNULAIRE_TECH": "27", "OBSERVATION": "Nothing", "Controle_Pression_ENSP": true, "Test_Puits": false, "Controle_Pression_DP": false, "post_date": "2021-09-10T08:56:16.864Z", "author": "smail"}}] and I want to print also some individual data from fields like PUITS, DATE_TEST, post_date in the console but it shows an error!?. -
djagno NotImplementedError: Django doesn't provide a DB representation for AnonymousUser
from django.shortcuts import render, redirect from django.db import transaction from .models import User from .forms import RegisterForm, LoginForm, CheckPasswordForm from .decorators import login_required from django.views.decorators.http import require_POST @require_POST def profile_delete(request): if request.method == 'POST': request.user.delete() return redirect('users:login') return render(request, 'users/delete.html') users view raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") NotImplementedError: Django doesn't provide a DB representation for AnonymousUser. I'm trying to delete user information in django, but I get an error like the title. What should I do? I have also tried the @login_require method and middle_classes in settings, but the error is not resolved. -
dealing with foreign keys in Django
i am creating a doctor appointment system, and i did include prescriptions too class Prescription(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) doctor = models.ForeignKey(Doctor, null = True, on_delete=models.SET_NULL) clinic = models.ForeignKey(Clinic, on_delete=models.SET_NULL) i was thinking what if the doctor delete his account for some reasons, can the doctor or the clinic set to null if this happen?