Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Django function based view to update a model?
I used a class based view to update a user profile using this code class EditProfileViewClass(generic.UpdateView): model = UserProfile fields = ['bio', 'profile pic'] template_name = 'users/update.html' success_url = reverse_lazy('home') path('profile/<int:pk>/update', EditProfileViewClass.as_view(), name="profile"), <a href="{% url 'profile' user.id %}">Your Profile</a> the issue right now is, Instead of having the url like the one above, I want it to be like path('profile/<str:username>/update', EditProfileViewClass.as_view(), name="profile"), but unfortunately I get an attribute error saying: Generic detail view EditProfileView must be called with either an object pk or a slug in the URLconf. So I tried making a function based view so I can get the "username" from the url, doing that didn't allow me to get the form I needed to update the specific username. Any help would be great. Thanks. -
Why am I getting CORS error on some devices, while others are working fine?
I am using django-cors-headers for CORS in django. It is working fine for some devices, but some devices get CORS error. I tested it out in some of my devices, some worked, and some didn't. I also cleared entire browser data on all those devices. But it still didn't help :( My settings: from corsheaders.defaults import default_headers INSTALLED_APPS = [ ... 'corsheaders' ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', "https://www.example.com", "http://www.example.com", "https://example.com", "http://example.com", ] CORS_ALLOW_HEADERS = list(default_headers) + [ 'upload-length', 'upload-metadata', 'upload-offset', 'x-http-method-override', 'x-request-id', 'tus-resumable', 'location', 'content-type', ] CSRF_TRUSTED_ORIGINS = [ "localhost:3000", "example.com", "www.example.com" ] CORS_EXPOSE_HEADERS = [ "Location", "Upload-Offset", "Upload-Length" ] -
adding .annotate foreign key in objects does not give distinct result
When i run following query its working fine query= UserOrder.objects.filter(order_date__range=( Request['from'], Request['to'])).values('user_id__username','user_id__email').annotate( total_no_of_order=Count("pk")).annotate(total=Sum('total_cost')) But i also want to know the number of services related to order .annotate(total_no_of_services=Count("userorderservice__pk")) by adding above code in query total_no_of_order and total_cost getting changed too and by putting distinct=True in total_cost its only considering for single unique total_cost value Modles.py class UserOrder(models.Model): order_id = models.AutoField(primary_key=True) user_id = models.ForeignKey(AppUser, on_delete=models.CASCADE) total_cost = models.FloatField() ... class UserOrderService(models.Model): order_id = models.ForeignKey(UserOrder, on_delete=models.CASCADE) ... -
request.POST.get didn't get the input value
So, what I was trying to do is that user input a base64 encoded image and than convert it to text via pytesseract OCR. The problem is every time I tried to input it only reload the page and nothing happens. Here's my html snippet : <form method="POST" action="{% url 'ocr-view'%}"> {% csrf_token %} <label for="base64"> Input Base64 :</label> <input type="text" class="form-control" id="text" name="base64" /> <button type="submit" class="btn btn-primary mt-3" name="submit"> <i class="fas fa-search"></i> Submit </button> </form> <div class="card-body"> <label> Result : </label> <br> <span class="h3">{{text}}</span> </div> Here's my views.py : class IndexView(LoginRequiredMixin, CreateView): model = Ocr template_name = "ocr/ocr.html" fields = ['input'] def get_context_data (self): text = "" if self.request.method == 'POST': imgstring = self.request.POST.get('base64') imgstring = imgstring.split('base64,')[-1].strip() image_string = BytesIO(base64.b64decode(imgstring)) image = Image.open(image_string) text = pytesseract.image_to_string(image) text = text.encode("ascii", "ignore") text = text.decode() context = { 'text': text, } return context But if i put the base64 code directly to views.py the OCR function work perfectly. imgstring = 'data:image/jpeg;base64,/9j/somerandomcode' imgstring = imgstring.split('base64,')[-1].strip() image_string = BytesIO(base64.b64decode(imgstring)) image = Image.open(image_string) text = pytesseract.image_to_string(image) text = text.encode("ascii", "ignore") text = text.decode() context = { 'text': text, } return context I assume there is something wrong with my post method, please review … -
Is there a way to keep alive request longer than 60s in EC2 instance?
Hello everyone I've been trying to execute our django app on amazon aws ec2 instance. Everything works fine except for requests longer than 60s. Those requests automatically get 504 Gateway Time-out. I configured all needed ports in Security Groups for my EC2 instance. We are using nginx and my nginx.conf looks like: user nginx; worker_processes auto; error_log /var/log/nginx/error.log notice; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; 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; sendfile on; #tcp_nopush on; keepalive_timeout 3600s; client_max_body_size 500M; client_body_timeout 86400s; client_header_timeout 86400s; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; proxy_connect_timeout 86400s; proxy_send_timeout 86400s; proxy_read_timeout 86400s; send_timeout 86400s; #gzip on; include /etc/nginx/conf.d/*.conf; } I tried to play with keepalive_timeout as many posts suggest but it's not working. There are also a lot of posts mentioning load balancer configuration but I'm not even using load balancer so this should not be related to it. How do I manage my instance to process requests longer than 60s? -
How to convert json to form in Django?
I'm developing a Django project, and the team want to seperate the front-end and the back-ed, so I'm using Django to develop api. The format of the data transmitting is json. However, I want to use the defalt user package (django.contrib.auth), and I have to use Form. How could I convert the json received from the frontend to the form that I'm going to use in backend? thanks! I have tried the silly code as below and it does not work. @require_http_methods(["POST"]) def register(request): form = CustomUserCreationForm(data=request.POST) response = {"status": "success"} if form.is_valid(): new_user = form.save() print("valid") return JsonResponse(response) -
Reverse look-up with related name
Suppose these models: class Person (models.Model): pass and class Marriage (models.Model): person = models.ForeignKey(Person, on_delete = models.CASCADE, related_name='person') person_2 = models.ForeignKey(Person, on_delete = models.CASCADE, related_name='person_2') How can I filter persons through the ID of a Marriage field (e.g. the ID)? That is, my goal is to do something like Person.objects.filter(marriage__id=32). I understand that the related name has some role there, but for example Person.objects.filter(person_2__marriage__id=32) doesn't seem to work either. Thank you! -
Weird behavior when accessing request.user in django
I have a simple view which requires a user to be logged in AND belongs to a specific group as the following class IndexView(LoginRequiredMixin, UserPassesTestMixin, generics.GenericAPIView): serializer_class = IndexSerializer def test_func(self): print(self.request.user) // User object return self.request.user.groups.filter(name='Poster').exists() def get(self, request, *args, **kwargs): print(self.request.user) // AnonymousUser print(request.user) // Anonymous User return HttpResponse('Welcome') The thing is when I print the user inside the get method it returns AnonymousUser but it returns a User object inside the test_func method. I am clueless of why this is happening so any help would be appreciated. -
REST Api Django - create new model-object and add currently logged in user to it
I have an endpoint, where a currently logged in user can create an object called 'project' . I want to show the user all of his own projects, so when he creates a new one, I want the user to be automatically added to the projects user fields. How would I achieve that? Both the user and the Project objects do have an ID, so I would like to have an own model wich combines those two. My idea was to create a new view wich takes a userID and a projectID and puts them together as ManyToMany relationship. Can I somehow call the view right inside the 'create project' view without the need of a new POST ? I want to be able to use the view at an other point as well, thats why I want to split this. my current model looks like this models.py class Project(models.Model): id = models.AutoField(db_column = 'db_ID', primary_key = True) name = models.CharField(max_length=500, default = None) descriptor = models.CharField(max_length = 1000, default = None) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'Projects' def __str__(self): return self.name views.py class ProjectView( APIView, ): def post(self, request): serializer = ProjectSerializer(data = request.data) … -
View counter using IP address in Django app
I am working on Django app and I want to know how many people use it, so I decided to add view counter on the page. I created view counter (watched some tutorial) but it doesn't work. I don't know where is a problem. Here is the code: models.py: class User(models.Model): user=models.TextField(default=None) def __str__(self): return self-user admin.py: admin.site.register(User) There is a problem with views.py. It says that "return can be used only within a function". I know that but what can I do to make this work? def get_ip(request): address=request.META.get('HTTP_X_FORWARDED_FOR') if address: ip=address.split(',')[-1].strip() else: ip=request.META.get('REMOTE_ADDR') return ip ip=get_ip(request) u=User(user=ip) print(ip) result=User.objects.filter(Q(user__icontains=ip)) if len(result)==1: print("user exist") elif len(result)>1: print("user exist more...") else: u.save() print("user is unique") count=User.objects.all().count() print("total user is", count) return render(request, 'index.html', {'count':count}) index.html: {% load static %} <html> <head> <title>Hello World Django App</title> </head> <h1>Hello World!</h1> <div>Total visits: {{count}} </div> </html> -
How many websocket connection should to ı use in my chat application?
I am developing a django chat application for my website and I am using websockets for that.My system like a real chat ,you can enter a system and you can see different user in your dashboard to send message.And every time you click different user for chat, I connected websocket every two person for chatting.Is that true or just one websocket connection should I use for the all system and I can save message with using users Id.Or this way will slow down my website?Which one is better? -
Wagtail - pass parameters to struct block
I'm trying to pass parameters to a struct block, which also has child struct blocks to load the choices dynamically through choice block. Tried the concept with init method, but no success yet. Below is my implementation code - class DefaultThemeTemplate(blocks.StructBlock): template = blocks.ChoiceBlock(choices=[], label=_('Select a template'), required=False) def __init__(self, folder=None, **kwargs): self.template = blocks.ChoiceBlock(choices=get_designs(folder), label=_('Select a template'), required=False) super(DefaultThemeTemplate, self).__init__(**kwargs) class Meta: label = _('Default Theme') class ThemeOneTemplate(blocks.StructBlock): template = blocks.ChoiceBlock(choices=[], label=_('Select a template'), required=False) def __init__(self, folder=None, **kwargs): self.template = blocks.ChoiceBlock(choices=get_designs(folder), label=_('Select a template'), required=False) super(ThemeOneTemplate, self).__init__(**kwargs) class Meta: label = _('Theme One') class ThemeTwoTemplate(blocks.StructBlock): template = blocks.ChoiceBlock(choices=[], label=_('Select a template'), required=False) def __init__(self, folder=None, **kwargs): self.template = blocks.ChoiceBlock(choices=get_designs(folder), label=_('Select a template'), required=False) super(ThemeTwoTemplate, self).__init__(**kwargs) class Meta: label = _('Theme Two') class Templates(blocks.StructBlock): default_theme = DefaultThemeTemplate(folder='', required=False) theme_one = ThemeOneTemplate(folder='', required=False) theme_two = ThemeTwoTemplate(folder='', required=False) def __init__(self, folder=None, **kwargs): self.default_theme = DefaultThemeTemplate(folder=folder, required=False) self.theme_one = ThemeOneTemplate(folder=folder, required=False) self.theme_two = ThemeTwoTemplate(folder=folder, required=False) super(Templates, self).__init__(**kwargs) class Meta: label = _('Template') class StaticPage(Page): template = StreamField([ ('template', Templates(required=False, folder='pages')) ], null=True, blank=True, verbose_name=_('Template')) Here's the screenshot with the blank choice fields - Please help me find out what am I doing wrong here. Thanks in advance. -
How to add PDF created by ReportLab into a FileField in a model of Django
In the viws.py, I can create a PDF file. However, I can't add it into a FileField in a model. from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase import pdfmetrics buffer = io.BytesIO() cc = canvas.Canvas(buffer, pagesize=A4) # describe something font_name = "HeiseiKakuGo-W5" pdfmetrics.registerFont(UnicodeCIDFont(font_name)) pdfCanvas.setFont(font_name, 7) pdfCanvas.drawString(65*mm, 11*mm, 'test') cc.showPage() cc.save() cc.seek(0) # I can't add a PDF created above into a FileField in a model # someObject.someField.save('test.pdf', File(buffer)) # someObject.save() return FileResponse(buffer, as_attachment=True, filename='receipt_pdf.pdf') -
How to make queryset equal to list in django webapp?
Suppose that i have a model called "Test" in models.py, and the view function in views.py as follows: def app_view(request): if request.method == 'POST': form = AppForm(request.POST) if form.is_valid: ... else: form = AppForm() the_query = Test.objects.all().values_list('test_field') the_list = list(the_query) the_length = len(the_list) form.fields['test_field'].queryset = [the_list[x] for x in range(0,the_length)] return render(...) because the item in "the_query" is tuple type, but i need str type, so i convert the queryset to list, but at the second last row i neet make the queryset equal to the list, but i got an AttributeError, so i want to know is there any other way to achieve my demand? -
Twilio Voice Gather + Django Regex Validation
How do I use regular expressions to validate user input collected via dtmf? For example: I want to apply validation on multiple views within the same views.py. If user input passes validation then redirect to the next view. If user input fails validation then use the verb to give an error message and redirect to current view so that they can try again. Example: Please press 123 User presses 384 Input is checked against regex and it fails validation Say: I'm sorry, but that is incorrect. redirect to current view, so user may retry Please press 123. Example: Please press 123 User presses 123 Input is checked against regex and it passes validation User is redirected to the next view I'm using: Python 3.9.5 Django 3.2.8 twilio 7.1.0 -
calling create_superuser and create_user function in abstractuser in DRF
I have customuser model which inherits the Abstratuser from Django. However, I didn't understand the create_user and create_superuser. For eg when is the create_user function is called and when the create_superuser function is called. The model looks like this. class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self,first_name,last_name,email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError("The email must be set") first_name = first_name.capitalize() last_name = last_name.capitalize() email = self.normalize_email(email) user = self.model( first_name=first_name, last_name=last_name, email=email, **extra_fields ) #user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, first_name,last_name,email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(first_name,last_name,email, password, **extra_fields) ROLE = (('admin','ADMIN'),('manager','MANAGER'),('staff','STAFF')) class CustomUser(AbstractUser): username = None email = models.EmailField(unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] role = models.CharField(max_length=15, choices=ROLE, default='staff') objects = CustomUserManager() def __str__(self): return self.email For eg for other regular models like Contacts, … -
Token invalid : Token must be in class <'bytes'>
I am trying to decode the token from the user.Every Time I run the code it show Decode error class PasswordChange(generics.GenericAPIView): model = CustomUser serializer_class = PasswordChangeSerializer def patch(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) payload = jwt.decode(serializer['token'], settings.SECRET_KEY,algorithms=['HS256']) user = CustomUser.objects.get(id=payload['user_id']) if user.check_password(serializer['old_password']): user.set_password(serializer['new_password']) user.save() -
Django REST Framework - XMLRenderer modifying my simple XML response
I want to send a simple CXML text string as below as a response to a DRF POST request to a django view (see my django view below) <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE cXML SYSTEM "http://xml.cXML.org/schemas/cXML/1.2.011/cXML.dtd"><cXML payloadID="2021-10- 19T03:57:08.416995@example.com" timestamp="2021-10-19T04:01:56.530426+00:00"><Response><Status code="200" text="Success" /></Response></cXML> (Above string is value of 'response_cxml' variable in my django view below) But what django sends and is received by the remote app is: <?xml version="1.0" encoding="utf-8"?> <root>&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;!DOCTYPE cXML SYSTEM "http://xml.cXML.org/schemas/cXML/1.2.011/cXML.dtd"&gt;&lt;cXML payloadID="2021-10- 19T05:10:41.115609@example.com" timestamp="2021-10- 19T05:10:41.115674+00:00"&gt;&lt;Response&gt;&lt;Status code="200" text="Success" /&gt;&lt;/Response&gt;&lt;/cXML&gt;</root> XMLREnderer I believe is adding extra duplicate version tag and 'root' tag.It is also urlencoding xml characters like <,> etc.How can I prevent XMLREnderer modifying my response? The sender HTTP headers are Accept= "text/xml and content-type='text/xml' My view: @csrf_exempt @api_view(['PUT','POST']) @authentication_classes((TokenAuthentication,)) @permission_classes((IsAuthenticated,)) @renderer_classes([XMLRenderer]) @parser_classes([XMLParser]) def purchase_order(request): """ Receives the purchase order cXML and saves PO details to database. Sends a 200 response back """ if request.method == 'PUT' or request.method == 'POST': po_cxml = request.body.decode() response_cxml = process_po_cxml(po_cxml) return Response( response_cxml.encode('utf-8')) -
How to automatically archive the content of a page when the csv file(the data holder) changes
I am developing a sports site that will require data feeding using csv file from a dynamic source. I am done with the scripting but what I don't know is how to still be able to show the previous information on the old csv file as the newly uploaded csv will automatically replace the view output. -
how to check if a model table is created or not
Im trying to create a tuple from another model's objects and use it in another model. it works just fine but when when I want to start my app and makemigrations, it gives me the error that the model you are trying to use is not created yet, obviously! therefore, I need an if statement to check if that model table is not created dont do anything. this is my Model: class Field(models.Model): id = models.AutoField(primary_key=True) slug = models.CharField(max_length=16, default='default') title = CharField(max_length=32) and my tuple: INTERESTS = (Field.objects.values_list('slug', 'title')) and this is the error I get: django.db.utils.OperationalError: no such table: reg_field how can I bypass this error? I need something like this: if Field exists then: INTERESTS = the above, else INTERESTS = () -
Double AWS S3 model for Heroku
I have tried to figure out why my dynamic url that I deployed with heroku. Have anyone else experienced this with AWS s3 deploying to heroku. If so please give me some insight because it would be very helpful <img src="https://python-nailsent-demo.herokuapp.com/https://nailsent-demo.s3.amazonaws.com/media/media/abstract_art.jpg?AWSAccessKeyId=AKIAU7F3NAWYGCEKU6OL&amp;Signature=NsgA9TPSrDCw%2FwEdlr3bLP7tPew%3D&amp;Expires=1634627743" alt="0 Slide"> -
Error occur when trying to run server in django project
You have 2 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): appname. Run 'python manage.py migrate' to apply them. -
Django how to add html style for javascipt loadmore button?
I added load more button using JavaScript in my blog page which will dynamically load content. But I don't know how to implement my original html style to JavaScript load more button. This is my original html style: {% for filt in object_list %} <div class="card mb-4"> {% if not filt.blog_cover_image %} <img class="img-fluid rounded" style="max-height:1000px;max-width:1200px;" src="https://via.placeholder.com/900x300" alt="..." /> {% else %} <img class="img-fluid rounded" style="max-height:1000px;max-width:1200px;" src="{{ filt.blog_cover_image.url }}" alt="..." /> {%endif%} <div class="card-body"> <h2 class="card-title"><a href="{% url 'blog:blog-detail' filt.slug %}">{{filt.title}}</a></h2> <p class="card-text">{{filt.body|striptags|safe|slice:":250" }}</p> <a class="btn btn-primary" href="{% url 'blog:blog-detail' filt.slug %}">Read More →</a> </div> <div class="card-footer text-muted"> Posted on ({{filt.created_at}}) <div class="author">{{filt.author.first_name}}&nbsp{{filt.author.last_name}}&nbsp;{% if user.is_authenticated %}{% if user.id == blog.author.id or user.is_superuser %}<a href="{% url 'blog:blog-update' filt.slug %}"><b>(Edit Blog)</b></a>&nbsp;<a href="{% url 'blog:blog-delete' filt.slug %}"><b>(Delete Blog)</b></a>{% endif %}{% endif %}</div> </div> </div> {% endfor %} <----javascript load more html---> <div id="posts-box"></div> <div id="spinner-box" class="not-visible"> <div class="spinner-border text-primary" role="status"></div> </div> <div id="loading-box"> <button class="btn btn-primary" id="load-btn">Load more</button> </div> here is my javascript code: const postsBox = document.getElementById('posts-box') console.log(postsBox) const spinnerBox = document.getElementById('spinner-box') const loadBtn = document.getElementById('load-btn') const loadBox = document.getElementById('loading-box') let visible = 3 const handleGetData = () => { $.ajax({ type: 'GET', url: `/posts-json/${visible}/`, success: function(response){ maxSize = response.max const data … -
Django send email: django.core.exceptions.ImproperlyConfigured error
I am trying to send a test email in Django with "send_email" function but getting an exception of "django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." Via py shell however everything works. I have tried to set "set DJANGO_SETTINGS_MODULE=mysite.settings" (Windows), and include it in PyCharm Env Variables and also run "django-admin dbshell --settings mysite.settings". The last produced an exception ModuleNotFoundError. I cannot get what it the problem, sending email via python smtp lib works and via django does not. -
Heroku error H10 when deploying Django app
my problem is that when i'm trying to deploy Django app on heroku, i get that H10 error, and obviously cant access the site. heroku logs --tail dont show anything specific beside that H10 error code at=error code=H10 desc="App crashed" method=GET My Procfile is loading web processes, so it's in the right place i guess, but i belive that maybe configuration of that web process is wrong. I had a problem with H14 error which was caused, because i had Procfile in wrong directory. It was directory of the project where manage.py file is sitting. I had to move it one directory above, because it was root file of my repository(.git file was sitting there). This is my Procfile: web: gunicorn api_project.wsgi My directory tree is like: ROOT/ ├─ .git/ ├─ Procfile ├─ api_project/ │ ├─ api_project/ │ ├─ manage.py │ ├─ robots.txt ├─ .gitignore And wsgi file is inside that send api_project dir. Maybe the path inside the Procfile should be diffrent?