Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pgAdmin4 queries lead to BAD REQUEST when left idle for too long or when the docker service is restarted
I run pgAdmin4 (6.18 at the time of writing) as a dockerized application in my web browser, but sometime, somehow, e.g. when the docker service is restarted or when the computer is left idle for too long, whatever request I type ends on a BAD REQUEST in the messages panel. I have to close the tab and open a new one, losing my current work and queries. This is also showing in the logs: pgadmin4 | ::ffff:172.24.0.1 - - [12/Feb/2024:22:22:20 +0000] "GET /sqleditor/status/7821587 HTTP/1.1" 400 120 "http://localhost:8080/sqleditor/panel/7821587?is_query_tool=true&sgid=2&sid=31&did=5&database_name=postgres" "Mozilla/6.0 (X11; Ubuntu; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0" pgadmin4 | 2023-02-09 13:23:23,873: ERROR pgadmin: 400 Bad Request: The CSRF tokens do not match. pgadmin4 | Traceback (most recent call last): pgadmin4 | File "/venv/lib/python3.10/site-packages/flask_wtf/csrf.py", line 261, in protect pgadmin4 | validate_csrf(self._get_csrf_token()) pgadmin4 | File "/venv/lib/python3.10/site-packages/flask_wtf/csrf.py", line 115, in validate_csrf pgadmin4 | raise ValidationError("The CSRF tokens do not match.") pgadmin4 | wtforms.validators.ValidationError: The CSRF tokens do not match. pgadmin4 | pgadmin4 | During handling of the above exception, another exception occurred: pgadmin4 | pgadmin4 | Traceback (most recent call last): pgadmin4 | File "/venv/lib/python3.10/site-packages/flask/app.py", line 1515, in full_dispatch_request pgadmin4 | rv = self.preprocess_request() pgadmin4 | File "/venv/lib/python3.10/site-packages/flask/app.py", line 1857, in preprocess_request pgadmin4 | rv … -
ImportError: cannot import name '_imaging' from 'PIL' in my django project
I deployed my django site online on apache in mod_wsgi everything works so far I then installed: pip install --pre xhtml2pdf to generate pdf documents with the code that goes with it, after restarting the server and when I refresh my site I have an Internal Server Error error, And then after consulting the error.log file I have this: ImportError: cannot import name '_imaging' from 'PIL' (/home/ubuntu/myproject/env/lib/python3.10/site-packages/PIL/__init__.py) where is the problem ??? -
500:INTERNAL_SERVER ERROR when deploying in vercel
iam a student trying to build django project and deploy it to vercel since heroku is not free anymore i follow the tutorial step by step correctly, then when i deploy i got 500 internal server error when i check the log, it gave me [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django'Traceback (most recent call last): how can i fix this error since i'am pretty new to Vercel i have try to search online for the solution yet none satisfy the similiar problem i have -
how can I use django model method for ordering in meta class
class Post(models.Model): title = models.CharField(max_length=255, verbose_name="ady") text = RichTextField(verbose_name="text") tagList = models.ManyToManyField(Tag, verbose_name="taglar", related_query_name="tagList") image = models.ImageField(upload_to="postImage/", verbose_name="surat") seen = models.ManyToManyField(UserId,verbose_name="görülen sany", blank=True, related_name="gorulen") like = models.ManyToManyField(UserId,verbose_name="like sany", blank=True) share = models.PositiveIntegerField(verbose_name="paýlaşylan sany", null=True, blank=True, default="0") createdAt = models.DateTimeField(auto_now_add=True, verbose_name="goşulan güni") class Meta: verbose_name_plural="Makalalar" # ordering = ("-createdAt",) ordering = ["-hotness",] def __str__(self): return self.title def likes(self): return self.like.count() likes.short_description = "Like sany" likes.allow_tags = True def seens(self): return self.seen.count() seens.short_description = "Görülen sany" seens.allow_tags = True @property def hotness(self): return self.likes() + self.seens() + self.share how can I user hotness function value to ordering in meta class -
how to properly implement Django (Wagtail CMS) pagination in modal window using Select html tag?
I have a list view in a modal window, once the user chooses the option of the select element, the pagination changes the url queryset (?p=<page_number>), although, in a normal list view there is no issue,as it changes the url, in a modal, it changes the entire page's location (URL address), which of course causes the lost of changes in the main page (document form), I just need the modal list to be changed by the number of pagination-page. I have searched and read almost all documentations pages related to pagination of a list view using Django, however I was unable to find the solution. here is the modal pagination template code (see the comments that indicates not working parts): {% load wagtailadmin_tags %}{# Changed by HH #} {% if linkurl %}{% url linkurl as url_to_use %}{% endif %} {% if items.has_previous or items.has_next %} <div class='pagination center' aria-label="Pagination"> <!-- this is working --> {% if items.has_previous %}<div class="l_arrow previous"><a href="{{ url_to_use }}{% querystring p=items.previous_page_number %}" class="icon">Previous</a></div>{% endif %} <p>{% with pr=items.paginator.page_range page_num=items.number total_pages=items.paginator.num_pages %} Page {{ page_num }} of {{ total_pages }} <!-- this is NOT working --> <select onchange="gotopage(this)" name="pg_selector" title="pg_selector" id="pg_selector" disabled> {% for i in pr … -
I need to create documentation API for Django with MongoDB project
I need to create documentation API using swagger or anything I'm using drf-spectacular but do not support mongodb -
Nginx Gives 502 Error but config should be correct; Please I need advise on how to debug the issue?
I have a CentOS 8 (fedora) server running and I'm trying to run my Django Webapp on it through Nginx It runs on port 8000, and I want to access it on my browser through nginx (so port 80?) These commands on the server itself This shows my webapp HTML page fine curl http://127.0.0.1:8000 curl http://0.0.0.0:8000 but these show me the Nginx 502 Bad Gateway page curl http://0.0.0.0 curl http://127.0.0.1 No errors in the nginx log files This is my nginx.config: events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; server_tokens off; server { listen 80; server_name $hostname; # I tried this with an '_' also no help location / { proxy_pass http://0.0.0.0:8000; # also tried with 127.0.0.1 proxy_set_header Host $host; } } } Running nginx -T shows the config has been loaded Any advise on what to look for? (perhaps my firewall is blocking it somehow? idk) Kind regards I'm trying to get my webpage working through Nginx -
Django Admin inline-editable like Flask admin?
Flask Admin has this really nice inline-editable option. Is there something similar in Django-Admin? Yes, there is "list_editable". Unfortunately, this is poor usability and I much more prefere the flask-Admin approach: editable fields are underlined Click -> popup opens where you can edit Save -> save via Ajax -
Django ValueError: Cannot serialize: <User: username>
When I'm trying to make migrations of my models in Django, I keep getting the same error, even after I've commented out all the changes: (.venv) C:\Users\jezdo\venv\chat\chat_proj>python manage.py makemigrations chat Migrations for 'chat': chat\migrations\0002_alter_customusergroup_custom_group_name_and_more.py - Alter field custom_group_name on customusergroup - Alter field users on customusergroup Traceback (most recent call last): File "C:\Users\jezdo\.venv\chat\chat_proj\manage.py", line 22, in <module> main() File "C:\Users\jezdo\.venv\chat\chat_proj\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 239, in handle self.write_migration_files(changes) File "C:\Users\jezdo\.venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 278, in write_migration_files migration_string = writer.as_string() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 99, in serialize _write(arg_name, arg_value) File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 63, in _write arg_string, arg_imports = MigrationWriter.serialize(_arg_value) File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\writer.py", line 282, in serialize return serializer_factory(value).serialize() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 221, in serialize return self.serialize_deconstructed(path, args, kwargs) File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 99, in serialize_deconstructed arg_string, arg_imports = serializer_factory(arg).serialize() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 50, in serialize item_string, item_imports = serializer_factory(item).serialize() File "C:\Users\jezdo\.venv\lib\site-packages\django\db\migrations\serializer.py", line 50, in serialize item_string, item_imports = serializer_factory(item).serialize() File … -
Django - images upload in wrong folder
Making some kind of blog website and can't make homepage to show article images... Images should be uploaded to media/profile_pics , but it just makes profile_pics folder in app folder and uploads images there. my models.py : class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default="YNTN") #author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) image = models.ImageField(upload_to="profile_pics", blank=True, null=True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) likes = models.ManyToManyField(User, related_name="blog_posts") def total_likes(self): return self.likes.count() def __str__(self): return (self.title + " | " + str(self.author)) def get_absolute_url(self): return reverse("home") my views.py: class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' my forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'title_tag', 'body', 'image') widgets = { 'title': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Title of the Blog'}), 'title_tag': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Copy the title with no space and a hyphen in between'}), 'body': forms.Textarea(attrs={'class':'form-control', 'placeholder':'Content of the Blog'}), } my home.html <div class="row"> {% for post in object_list %} <div class="col-lg-4 my-4"> <div class="card shadow" style="width: 20rem; height: 33rem;"> <img src="/media/{{post.image}}" class="card-img-top" alt="..." height="250px"> <div class="card-body"> <h5 class="card-title">{{post.title}} <br><small>by {{ post.author.first_name }} {{ post.author.last_name }}</small></h5> <p class="card-text">{{post.body|slice:":100"|safe}}</p> <a href={% url 'article-details' post.pk %} class="btn btn-primary">Read More {% if user.is_superuser %}<a href="delete_blog_post/{{post.slug}}/" class="btn btn-danger mx-4">Delete Blog</a>{% … -
Django crispy forms language settings
I am a beginner at web application development using django framework. I am creating a crispy form to update the user information and upload an image. The html file contains two forms, one for updating the information and second for uploading the image. While the rest of the form language setting is us-en, only the button and text next to the upload button are seen in german language. The settings.py file has the chosen language code as 'en-us'. In the model.py file the forms are defined like below: The forms are then used in the html file: But the webpage shows the following: could anyone please help me understand, what is making only the upload button language change to german and how could I possibly fix it? Thank you :) already tried: checking the language code in the settings.py file -
I am trying to call "sqlite db.sqlite" in my django project but i found the error mentiod below
`sqlite : The term 'sqlite' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 sqlite db.sqlite3 + CategoryInfo : ObjectNotFound: (sqlite:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException ~~~~~~` When I try to run this in the cmd it wrok fine the error is in visual studio terminal I have also installed sqlite viewer -
How to pass InMemoryUploadedFile as a file?
User records audio, audio gets saved into audio Blob and sent to backend. I want to get the audio file and send it to openai whisper API. files = request.FILES.get('audio') audio = whisper.load_audio(files) I've tried different ways to send the audio file but none of it seemed to work and I don't understand how it should be sent. I would prefer not to save the file. I want user recorded audio sent to whisper API from backend. -
duplicate key value violates unique constraint error in Django
I have a model named package in an app named exam. I use Django rest framework and have the following View: class PackageListCreaet(ListCreateAPIView): queryset = Package.objects.all() serializer_class = PackageSerializer permission_classes = (IsAdminAndReadOnlyForStaff,) @method_decorator(rest_error_decorator(logger)) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) and the following serializer: class PackageSerializer(serializers.ModelSerializer): class Meta: model = Package fields = ('pk','name','price','exams','active') when I try creating a new package from Django admin it works just fine. But when I try creating a new package using the API above it throws the following error: duplicate key value violates unique constraint \"exam_package_pkey\"\nDETAIL: Key (id)=(1) already exists I looked around a bit to find a solution and realized the problem is that the id field of exam_package table is out of sync. I tried syncing it like this and it didn't work. Then I tried removing all records (which happened with no error) and setting the primary key to 1 like this. And it still doesn't work. I looked into this link and realized maybe my probmlem is the same and maybe DRF is creating two new instances which is why I get the error. But I have no idea how to fix it. -
How I'm be able to query a multiple data in single model?
How do I able to query if have three Car Models Car A, Car B andCar C and I wanted to switch this position base on their ordering? How do I able to perform that and what class based view should I use or just a function-based view? Original DB : Car A --> Car B --> Car C Alter DB : Car C --> Car B --> Car A class CarColor(models.Model): colors = models.CharField(max_length=50) def __str__(self) -> str: return self.colors class Car(models.Model): car_name = models.CharField(max_length=50) car_model = models.CharField(max_length=200) car_description = models.TextField(max_length=200) car_color = models.ForeignKey(CarColor, on_delete=models.CASCADE) car_image = models.ImageField(null=True, blank=True, upload_to='media', default='imageholder.png') date_manufactured = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): """ After creating or updating a Car, this function will be triggered and redirection using reverse""" return reverse("car_detail", kwargs={"pk": self.pk}) class Meta: ordering = ['date_manufactured'] def __str__(self): return f'{self.car_name}' -
Django tests AssertionError for update view
I tried to create Django test for UpdateView but I have such problem as: self.assertEqual(application.credit_purpose, 'House Loan') AssertionError: 'Car Loan' != 'House Loan' Car Loan House Loa def test_application_update(self): application = Application.objects.create(customer=self.customer, credit_amount=10000, credit_term=12, credit_purpose='Car Loan', credit_pledge=self.pledge, product=self.product, number_request=2, date_posted='2020-01-01', reason='None', repayment_source=self.repayment, possible_payment=1000, date_refuse='2020-01-02', protokol_number='123457', status=self.status, language=0, day_of_payment=1, credit_user=self.user) response = self.client.post( reverse('application_update', kwargs={'pk': application.id}), {'credit_purpose': 'House Loan'}) self.assertEqual(response.status_code, 200) def test_application_update(self): application = Application.objects.create(customer=self.customer, credit_amount=10000, credit_term=12, credit_purpose='Car Loan', credit_pledge=self.pledge, product=self.product, number_request=2, date_posted='2020-01-01', reason='None', repayment_source=self.repayment, possible_payment=1000, date_refuse='2020-01-02', protokol_number='123457', status=self.status, language=0, day_of_payment=1, credit_user=self.user) response = self.client.post( reverse('application_update', kwargs={'pk': application.id}), {'credit_purpose': 'House Loan'}) self.assertEqual(response.status_code, 200) self.assertEqual(application.credit_purpose, 'House Loan') -
Templates are not found in django deployed project
I have got a Django Project. It runs perfectly using "python2 manage.py runserver". I have deployed the project in a server and I get "Template not found" error. I have changed the path in views file for the main page and now it works, but I have got two new issues: I have got an {% include "/lateral/menu.html" %} line that does not work in main.html All the href in buttons that redirect the user to other html files do not work either. I think it has something to do with the paths, how should I added them in order to be relative path? My structure: -APP1 -APP2 -WEB ---manage.py ---TEMPLATES ------main.html ------logout.html ------loging.html ------LATERAL ---------menu.html Some lines of my views file in order to check how I add the paths: def loging(request): # Función vista return render(request, "loging.html") I have tried changing to some variations of the paths and with absolute paths too without success. All was working perfectly locally. -
when i submit my form My Comment form dosen't save in database
I create a 5 star rating system using django with javascript and i want to user comment like this: i want to click on the stars and then return the value that is an integer this is my models: class Review(models.Model): course = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='reviews') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) rating = models.IntegerField(null=True, validators=[MinValueValidator(1), MaxValueValidator(5)]) comment = models.TextField() created = models.DateField(auto_now_add=True) active = models.BooleanField(default=False) def __str__(self): return f'{self.first_name} {self.last_name} my views: @csrf_exempt def productDetailView(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) new_comment = None if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.course = product new_comment.rating = request.POST['rating'] new_comment.save() else: form = ReviewForm() return render(request, 'shop/product_detail.html', {'product': product, 'form': form}) js function: $(document).ready(function(){ $('.rate .rate-item').on('click', function(){ var value = $(this).data('value'); $.ajax({ url: '{{ product.get_absolute_url }}', type: 'POST', data: {'rating': value}, success: function(response){ alert('Rating saved successfully!'); } }); }); }); and my template: <form method="post"> <div class="form-singel"> {{ form.first_name|attr:" placeholder:Fast name" }} </div> <div class="form-singel"> {{ form.first_name|attr:" placeholder:Last Name"}} </div> <div class="rate-label">Your Rating:</div> <div class="rate"> <div data-value="1" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="2" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="3" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="4" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div> <div data-value="5" class="rate-item"><i class="fa fa-star" … -
How to delete File Field and File(in project root) in django?
I want to delete the data inside the file field and the file uploaded through the file field. I'm beginner. models.py class Fruits(Signable): name = models.CharField( _('Name'), max_length=200, ) description = models.TextField( _('Description'), null=True, blank=True, ) this_is_my_file = models.FileField( _('Photo image'), null=True, blank=True, upload_to='myfile/' ) def __str__(self): return self.name def delete(self, *args, **kwargs): if self.this_is_my_file: self.this_is_my_file.delete() super().delete(*args, **kwargs) Like the code above, I added 'def delete' to the existing model as shown above through search. But I don't know how to use this function. How do I use this in view and template? My part of view is below. views/fruits.py class FruitsDetailView(LoginRequiredMixin, DetailView): template_name = 'frutis/detail.html' login_url = 'login' model = MyObjects def get_context_data(self, **kwargs): pk = self.object.pk context = super().get_context_data(**kwargs) ... return context How do I execute the delete function in this view? I want to delete it when I press the 'delete' button on the template. Should I send a post request from template and receive it from view? I've been thinking about it for 4 days, but I don't know what to do. -
Single model instances on separate html
What is a best way to display single model instances on different html? I know how it is done on single page (forloop), but could not figure out how the same would be possible on different html. i.e. single question per page? my pseudo model: class Question(models.Model): desc = models.CharField() -
Remote DRF Auth and handle payload with JWT
I have auth_service, tpm_api and frontend enviroments. All services use the same secret_key. My users and permissions are on the auth_service. I am using jwt_simple for Authentication on auth_service. On the frontend service, I get token from auth_service with username and password. I am sending requests to endpoints in my tpm_api service with this token. I'm parsing the response and displaying it in my frontend service. So far, no problem. However, I am not getting the token.payload data within the tpm_api service. I added REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), } in settings.py. When I send request to tpm_api service, under self.request.authenticators there is <rest_framework.authentication.BasicAuthentication object 0x000001668986C430> and <rest_framework.authentication.SessionAuthentication object at 0x000001668986C6A0>. I need <rest_framework_simplejwt.authentication.JWTAuthentication object at 0x000001FFDCD23790>. I don't have user model anywhere except auth_service. ##### auth_service model.py ##### from django.db import models from django.contrib.auth.models import AbstractUser perm_parent_choices = [ ("app", "app"), ("factory", "factory"), ("department", "department"), ("role", "role"), ] class User(AbstractUser): perms = models.ManyToManyField("login.Perm", related_name="user_perms", blank=True) gsm = models.CharField(max_length=15, null=True) class Perm(models.Model): parent = models.CharField(max_length=50, choices=perm_parent_choices, null=True) name = models.CharField(max_length=50) short_code = models.CharField(max_length=5) def __str__(self): return self.short_code ##### auth_service views.py ##### class UserViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserSerializer queryset = models.User.objects.all() def list(self, request, *args, **kwargs): ############################## from rest_framework_simplejwt.authentication import … -
Django FileSystemStorage does not save anything to media folder
I'm working on a Django backend deployed on a server, here's my settings: DEBUG = False STATIC_URL = "/staticfiles/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") And I want to save the users' images outside the django folder, so I've created a custom FileSystemStorage in this way: from django.core.files.storage import FileSystemStorage key_store = FileSystemStorage(location="/home/usr/project/media/", base_url="/media") Where I put the absolute path of ubuntu server. def profile_picture_url(instance, *_): return f"{instance.user.uuid}/profile.picture.png" picture = models.FileField( storage=key_store, default=None, upload_to=profile_picture_url ) But it doesn't create any file inside media folder. Any solution? -
Adding image for blog posts
Coding some kind of blog with django, and I can't make homepage to contain images of the articles... It just doesn't upload a image... my Views.py : class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' my Models.py: class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default="YNTN") #author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) image = models.ImageField(upload_to="profile_pics", blank=True, null=True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) likes = models.ManyToManyField(User, related_name="blog_posts") def total_likes(self): return self.likes.count() def __str__(self): return (self.title + " | " + str(self.author)) def get_absolute_url(self): return reverse("home") My Forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'title_tag', 'body', 'image') widgets = { 'title': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Title of the Blog'}), 'title_tag': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Copy the title with no space and a hyphen in between'}), 'body': forms.Textarea(attrs={'class':'form-control', 'placeholder':'Content of the Blog'}), } and my add_post.html : {% extends 'base.html' %} {% block title %}Make an article{% endblock %} {% block content %} {% if user.is_authenticated %} <h1>Make an article</h1> <div class="form-group"> <form method="POST"> <br/> {% csrf_token %} {{ form.media }} {{ form.as_p }} <button class="btn btn-dark">POST</button> </div> {% else %} <h1>You are not allowed to post! You need to <a href="{% url 'login' %}">Log in</a> or <a href="{% … -
Rest api detail User Not Found code user not found Error postman
i am generating a token for each logged in user. But on Get request through postman i am getting this error. please guide me what's wrong ! postman error screenshot my models.py class allmodelfields(AbstractBaseUser): USERNAME_FIELD = 'email' #id_no = models.BigAutoField(primary_key=True,serialize=False,verbose_name="ID",) email = models.EmailField(verbose_name='Email',max_length=255,unique=True,) password = models.CharField(max_length=255) confirm_password = models.CharField(max_length=255) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30,blank = True) last_name = models.CharField(max_length=30,blank = True) number_code = models.CharField(max_length=10) phone_no= models.CharField(max_length=10) pincode = models.CharField(max_length=10) house_no = models.CharField(max_length=50) street = models.CharField(max_length=50,blank = True) locality = models.CharField(max_length=50,blank = True) state = models.CharField(max_length=50) city = models.CharField(max_length=50) country = models.CharField(max_length=50) ip = models.CharField(blank = True,max_length = 20) # auto filled fields full_name = models.CharField(max_length=100,)#default = first_name + middle_name + last_name) full_number = models.CharField(max_length = 23)#f'{number_code} {phone_no}' created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) is_ active = models.BooleanField(default=False) unique_id = models.CharField(max_length = 10, editable=False) def __str__(self): return self.email def full_name_func(self): return f'{self.first_name} {self.middle_name} {self.last_name}' def full_number_func(self): return f'{self.number_code}|{self.phone_no}' class Meta: abstract = True class Customer(allmodelfields): account_type = models.CharField(max_length=20,choices=customer_account_choices,default=" ") class Dealer(allmodelfields): account_type = models.CharField(max_length=20,choices= dealer_account_choices,default=" ") serializers.py class customerprofileserializer(serializers.ModelSerializer): class Meta: model = Customer fields = ['id','full_name','email','unique_id','full_number'] class dealerprofileserializer(serializers.ModelSerializer): class Meta: model = Dealer fields = ['id','full_name','email','unique_id','full_number'] urls.py path("customerprofileview/", customerprofileview.as_view(),name='customerprofileview'), path("dealerprofileview/", dealerprofileview.as_view(),name='dealerprofileview'), views.py class customerloginview(APIView): renderer_classes = [apirenderer] def post(self,request,format=None): … -
Django Rest api Update View form can't update single attribute
I have created an Employee CRUD in Django REST using generic views. when update view page is loaded I couldn't find the current values in the fields. so I can't update a single value. when i update a single value it shows other fields must be required. I need to update a single value. eg: Phonenumber How can i do that? class EmpUpdateView(UpdateAPIView): queryset = Employee.objects.all() serializer_class = EmpModelSerializer lookup_field = 'id' [enter image description here](https://i.stack.imgur.com/7Slum.png) enter image description here