Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Understanding PDF response
I have no idea of naming this post so you can change the title, up to you. Currently I'm working on Facebook Messenger platform (it is bot using Django). Bot sends attachment to the user. I'm sending my attachment by following code: { "messages": [ { "attachment": { "type": "file", "payload": { "url": "https://example.com/file.pdf" } } } ] } If I change the url to url of a file hosted on different website (eg: PDF Link), bot is sending the pdf to user successfully. But when I change the url to url of a file hosted on my own website(PDF File I want) it is not sending my file. I did following things: X_FRAME_OPTIONS = 'SAMEORIGIN' SECURE_CONTENT_TYPE_NOSNIFF = False SECURE_REFERRER_POLICY = None Added messenger.com and facebook.com to CORS_ORIGIN_WHITELIST I changed the pdf file and it didnt work None of these didn't work. And I have several questions: Are there response headers I should change? Does nginx blocking requests from facebook? What should do now? I'm using django 3.1.1, gunicorn 20.0.4, nginx: 1.18.0 -
problem changing from WebsocketConsumer to AsyncWebsocketConsumer
i'm making a chat app with django, everything is fine and working with the WebsocketConsumer and async_to_sync, but when i change to the AsyncWebSocket i get an error : django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. any idea or suggestion on why is that happening or what i can do here ? thanks for your help. this is my consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.generic.websocket import WebsocketConsumer #from asgiref.sync import async_to_sync from django.utils import timezone from .models import Message from django.shortcuts import render, redirect, get_object_or_404 from courses.models import Course class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope['user'] self.id = self.scope['url_route']['kwargs']['course_id'] self.room_group_name = 'chat_%s' % self.id # join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name) # accept connection await self.accept() async def disconnect(self, close_code): # leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name) # receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] now = timezone.now() course = get_object_or_404(Course,id=self.id) messages = Message.objects.create(author=self.scope['user'], content=message,course=course) # send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user': self.user.username, 'datetime': now.isoformat(), } ) # receive message from room group async def chat_message(self, event): # Send message to … -
How to make django summernote field show font styles imported from google fonts?
So I was trying to use fonts from google in django summernote and did the following config. # Summernote SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 SUMMERNOTE_CONFIG = { 'attachment_filesize_limit': 1024*1024*10, # specify the file size 'summernote': { 'fontNames': ['Spectral', 'Quicksand'], 'fontNamesIgnoreCheck': ['Spectral', 'Quicksand'], }, } The font shows up in the font list in summernotefield in django admin and works fine when the post is displayed in the frontend but when editing from the django admin, the font doesn't change the style and displays the basic font. Django Admin Screenshot. Is there something that needs to be done? I can't seem to find a solution. -
How to show and use only days in datetime in DRF model fields and send requests to fill the field
my model class Reservation(models.Model): user = models.ForeignKey( User, verbose_name='owner', on_delete=models.CASCADE, default=User.objects.all()[0].pk ) RESERVATION_TYPES = ( ('office', 'office'), ('workplace', 'workplace') ) reservation_type = models.CharField( verbose_name='reservation type', choices=RESERVATION_TYPES, max_length=9, default='workplace' ) office = models.ForeignKey( Office, verbose_name='offices for reservation', on_delete=models.CASCADE, default=Office.objects.all()[0].pk ) workplaces = models.CharField( verbose_name='workplaces for reservation', blank=True, max_length=9 ) initial_day = models.DateField( verbose_name='days delta initial day', default=datetime.now() + timedelta(days=1) ) days_delta = models.DurationField( verbose_name='days delta', null=True, default=timedelta(days=0) ) my serializer class ReservationDetailSerializer(serializers.ModelSerializer): reservation_days = serializers.SerializerMethodField('get_reservation_days_list') class Meta: model = Reservation fields = ( 'id', 'reservation_type', 'office', 'workplaces', 'initial_day', 'days_delta', 'reservation_days', 'user' ) def get_reservation_days_list(self, reservation_model): initial_day = reservation_model.initial_day days_delta = reservation_model.days_delta reservation_days = [] for delta in range(days_delta.days): reservation_days.append(date.isoformat(initial_day + timedelta(days=delta))) return reservation_days def validate(self, validated_data): validated_data['days_delta'] = validated_data['days_delta'] * 86400 if validated_data['reservation_type'] == 'office': workplaces = [] for workplace in Workplace.objects.all().filter(office=validated_data['office']): workplaces.append(workplace.pk) validated_data['workplaces'] = workplaces return validated_data my view class ReservationCreateView(generics.CreateAPIView): serializer_class = ReservationDetailSerializer permission_classes = (IsAuthenticated,) request days_delta in seconds then multiply by 86400 (seconds in a day) to write the correct interval to the database days_delta in seconds then multiply by 86400 (seconds in a day) to write the correct interval to the database { "reservation_type": "office", "office": 1, "initial_day": "2020-12-31", "days_delta": 5, "user": 2 } response days_delta … -
Django 3.1 gives error | URLconf does not have any pattern in it, If you see valid patterns in the file then the issue is probably
Python: 3.6.0 | Django: 3.1.4 By going through the documentation, I created one app, below is my app url.py (from app) file from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] My site urls.py file from django.contrib import admin from django.urls import path, include urlpatterns = [ path('npimgapp/', include('npimgapp.urls')), path('admin/', admin.site.urls) ] My view.py file in app from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Welcome ...") On executing this code I am getting below error: django.core.exceptions.ImproperlyConfigured: The included URLconf 'npimgpro.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular i mport. Also, below is my directory structure for ref: -
"Update" instead of "save" in Django model without the primary key
How to do an "Update" instead of "save". I want to make a new entry only if "name", "age" already does not exists. I cannot handle/pass the primary key. class Author(models.Model): name = models.CharField(max_length=50) age = models.PositiveIntegerField(null=True, blank=True) alias = models.CharField(max_length=50, null=True, blank=True) goes_by = models.CharField(max_length=50, null=True, blank=True) flag = models.PositiveIntegerField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name objects = models.Manager() def saveauthor(request): if request.method == "POST": nname = request.POST['name'] nage = request.POST['age'] nalias = request.POST['alias'] ngoes_by = request.POST['goes_by'] nflag = request.POST['flag'] new = Author(name = nname, age = nage, alias = nalias, goes_by= ngoes_by, flag=nflag) new.save() else: pass return JsonResponse("Ok", safe=False) -
Decrease counter based on html element
I passed a integer variable as a context when i rendered a webpage. That variable is the initial number of untagged images that i have uploaded to my web application. I then display my images in a table with the first column being the image and second column being the tag name and the third containing a button which leads to a modal that allows me to edit the tags for the images. How am i able to decrease the count of untagged images counter whenever i fill in an empty tag? -
Modify the class based view object to save
I currently have the model such class Newsletter(models.Model): email = models.EmailField(null=False, blank=True, max_length=200, unique=True) conf_num = models.CharField(max_length=15) confirmed = models.BooleanField(default=False) def __str__(self): return self.email + " (" + ("not " if not self.confirmed else "") + "confirmed)" And I have the class based view class NewsletterView(SuccessMessageMixin, CreateView): template_name = 'newsletter.html' success_url = reverse_lazy('newsletter') form_class = NewsletterRegisterForm success_message = "Check your inbox for the verification email" def form_valid(self, form): self.conf_num = random_digits() subject = 'Newsletter Confirmation', html_content = 'Thank you for signing up for my email newsletter! \ Please complete the process by \ <a href="{}/confirm/?email={}&conf_num={}"> clicking here to \ confirm your registration</a>.'.format(self.request.build_absolute_uri('/confirm/'), self.email, self.conf_num) sender = "noreply@example.com" recipient = form.cleaned_data['email'] msg = EmailMultiAlternatives(subject, html_content, sender, [recipient]) msg.send() return super().form_valid(form) I'm slightly confused as to how I would be able to set via the class based view, the conf_num? Would I have to say in my form_valid function correctly call self.conf_num = number? When I try either of these methods I either get that the email is not unique or that the newsletter object has no email. Any help would be apprecicated. -
Trying to query database if user inputted city and state is there and redirect if True or False in Django
I have a sorting page that the visitor to my website enters in a city and state where they want to live. I need to check against out database if we have any results in or near that city. Below is my code. def address(request): if request.method == 'POST': form = CityStateForm(request.POST) if form.is_valid(): obj = Location_Targeting() city = request.POST.get("city") state = request.POST.get("state") homeAvailable = Home.objects.get(city = city, state=state) obj.city = form.cleaned_data["city"] obj.state = form.cleaned_data["state"] obj.save() return render(request, 'app/success.html') else: obj = Location_Targeting() obj.city = form.cleaned_data["city"] obj.state = form.cleaned_data["state"] obj.save() return render(request, 'app/failed.html') return render(request, 'GMH_app/address.html') I want to save the form to my database in its own table which it should, but doesn't do. Then I want it to query the Home table in my database and look up the city and state and if there are homes in the city or surrounding area it redirects to a success page otherwise it redirects to a failure page. In my debugger it shows the correct kwargs but returns a does not exist but I know it does. Also it seems to be case sensitive which wont be user friendly. I know this probably seems like a lot but I have … -
MQTT inside django application vs MQTT as script in django application?
i want to initialize a mqtt client in a django application and i just want to have one client that will subscribe on more than one topic and each topic will have it's own callback.then i will put this application in the INSTALLED_APPS settings in django application. my question : Is the above scenario applicable ? as django run on multiple threads in production , and i'm afraid that the mqtt client will be loaded more than one time and the callbacks will be done more than one time? or it's better to put the mqtt as a script outside the django application and just load the django environment ? -
How to create a profile page for students in Django
I want to create a profile page for every student of faculty, I already have a model called Student in this model I store all the information about the student, but I have to create a profile page for each student separately so I don't need any extra fields in my Profile model I want to bring the exact information form Student model. How can I do that? -
dbbackup task registered but not running
I try to implement celery and celery-beat to run periodic task. My goal is to backup Postgresql database using Django-dbbackup but only my test tack hello is running whereas the 3 tasks are registered celery_1 | [tasks] celery_1 | . cafe.tasks.backup celery_1 | . cafe.tasks.hello celery_1 | . core.celery.debug_task celery_1 | [2020-12-28 17:05:00,075: WARNING/ForkPoolWorker-4] Hello there! celery_1 | [2020-12-28 17:05:00,081: INFO/ForkPoolWorker-4] Task cafe.tasks.hello[5b3e46b5-16bc-4d6a-b608-69ffdf8e5664] succeeded in 0.006272200000239536s: None -
using flags as options for languages in django
I'm trying to add flags to my dropdown for i18n, so far I've tried adding an img tag and using as background image but none of them seem to work <ul class="nav navbar-nav ml-auto"> <li class="nav-item"> {% get_current_language as LANGUAGE_CODE %} <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ redirect_to }}"> <select name="language" id="" class="icon-menu"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{language.code}}" {% if language.code == LANGUAGE_CODE %} selected {% endif %} {% if language.code == "en-gb" %} style="background-image:url(/static/img/en-gb.png);" alt="english">english {% elif language.code == "pt-br" %} >portugues<img src="/static/img/pt-br.png" alt=""> {% else %} {{ language.name_local }} {% endif %} </option> {% endfor %} </select> <input type="submit" value="{% trans 'Go' %}"> </form> </li> -
Error while opening Django admin: "Error at /admin/ Incorrect padding"
I was making a web app using Django. I was using Django 3.0.7 for the sake. Then I upgraded to Django 3.1.1. When I reinstalled Django 3.0.7 I am unable to open Django Admin. While I try to get into my Django admin an error shows up saying: Error at /admin/ Incorrect padding Exception Location: ...\python\python38\lib\base64.py in b64decode, line 87 -
How to write a TestCase for user login
I should test login functionality for this Django project, but it seems it can't login properly. This is the login method on views.py def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) request.session['username'] = username # Session test if user is not None: login(request, user) messages.info(request, "You are now logged in as {username}.") # Redirect da login alla dashboard dell'utente return redirect("dashboard") else: messages.error("Invalis User") #return render(request=request, template_name="dashboard.html", context={}) else: messages.error(request, "Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form": form}) After login, it redirects to the dashboard which shows boards linked to the user, with this code def dashboard(request): usern = request.session.get('username') userlog = User.objects.get(username=usern) boards = BoardMember.objects.all().filter(user=userlog) return render(request, "dashboard.html", {'board': boards, 'user': userlog}) Everything works fine, but when I test it in TestCase the error is "User matching query does not exist", test code is: self.client.post("/", {"username": self.user2.username, "password": self.user2.password}) response = self.client.get(reverse("dashboard")) self.assertEqual(response.content, self.user2.username) -
How to create a template creator with moveable objects?
Good day, I am currently working on an automatic system that generates invoices with data that it receives from an API. I am currently doing this with Django (Python) to create some variation. Well, I want to create a system with which you can easily create templates for these invoices. You have seen these kinds of systems before. You can move blocks with items such as a logo or text wherever you want. Well I know that these templates are further stored as HTML. Only nowhere I can find clear information about how I can easily assemble such a system or how such a system works. Below I show a GIF of the system what I want. If anyone has any information on this I will be very happy if you can share that with me :) -
Django model order the results according to the entry date
How do order the DB query result according to the entry date? I want to order the output from the latest entry added, using MySQL DB creation timestamp. class Author(models.Model): name = models.CharField(max_length=50) age = models.PositiveIntegerField(null=True, blank=True) alias = models.CharField(max_length=50, null=True, blank=True) goes_by = models.CharField(max_length=50, null=True, blank=True) flag = models.PositiveIntegerField() def __str__(self): return self.name objects = models.Manager() def getAuthor(request): if request.method == "POST": result = list(Author.objects.filter(flag=0).values_list("name").order_by('-date')) else: pass return JsonResponse(result, safe=False) -
Can't access django development server on a remote vps
I've just got a VPS with Ubuntu 18.04 on it. Now I want to move my Django app I've been developing on a local PC to the VPS. I moved it and it starts okay - it says the server is running on 0.0.0.0:8000. So the server is running fine, but I can't connect to it from a web browser on my local PC. I have port 8000 enabled with netstat and I have added the IP to ALLOWED_HOSTS. -
Django Subquery/Window function
I'm trying to create a subquery that would produce the same result as a window function. I have following models: class BookQuerySet(models.QuerySet): def with_reviews(self): return self.annotate(score=models.Avg('review__score')) def with_reviews_per_category(self): categories = Category.objects.filter( book=models.OuterRef('pk') ).annotate( cs=models.Avg('book__review__score') ) qs = self.annotate( category_score=models.Subquery(categories.values('cs')[:1]) ) return qs def with_reviews_per_category_window(self): return self.annotate( category_score=models.Window( expression=models.Avg('review__score'), partition_by=[models.F('category_id')] ) ).distinct() class Category(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=200) authors = models.ManyToManyField('Author', related_name='books') category = models.ForeignKey('Category', on_delete=models.CASCADE) objects = BookQuerySet.as_manager() class Author(models.Model): # Irrelevant class Review(models.Model): summary = models.CharField(max_length=200) book = models.ForeignKey('Book', on_delete=models.CASCADE) score = models.PositiveSmallIntegerField( default=1, validators=[ MinValueValidator(1), MaxValueValidator(5) ], ) The reviews have following values: [{'score': 5, 'book': 5, 'book__category': 3}, {'score': 2, 'book': 4, 'book__category': 2}, {'score': 4, 'book': 1, 'book__category': 1}, {'score': 4, 'book': 2, 'book__category': 1}, {'score': 4, 'book': 3, 'book__category': 1}, {'score': 5, 'book': 1, 'book__category': 1}, {'score': 5, 'book': 2, 'book__category': 1}, {'score': 5, 'book': 3, 'book__category': 1}, {'score': 5, 'book': 3, 'book__category': 1}] And the window function produces correct results: In [11]: list(Book.objects.with_reviews_per_category_window().values('id', 'category', 'category_score')) Out[11]: [{'id': 4, 'category': 2, 'category_score': 2.0}, {'id': 3, 'category': 1, 'category_score': 4.571428571428571}, {'id': 2, 'category': 1, 'category_score': 4.571428571428571}, {'id': 5, 'category': 3, 'category_score': 5.0}, {'id': 1, 'category': 1, 'category_score': 4.571428571428571}] I can confirm that … -
Error submitting a modified field of a form
I am having a problem with my form, and it is that when trying to persist my data in the database this is not done correctly, because in my form the developer field is not being validated in the correct way because it does not show an error to the client, but the browser console shows me the following error, an invalid form control with name = 'developer' cannot be focused. This is my form: class ProjectForm(ModelForm): developer = forms.ModelMultipleChoiceField( queryset=User.objects.filter(groups__name='desarrolladores'), label='Desarrolladores', ) class Meta: model = Project fields = ( 'developer', 'name', 'status' ) labels = { 'name': 'Nombre de Proyecto', 'status': 'Estado', } def clean_developer(self): developer = self.cleaned_data.get('developer') if developer is None: raise forms.ValidationError('El campo es obligatorio') return developer -
Django: Unable to access attribute of foreign key
I have a Comment model with User as a foreign key, and simply want to render the username of the comment. The comment shows up on the page but the username doesn't, I'm not sure why my code doesn't work.. Sorry if this is a really basic question. class Comment(models.Model): comment = models.TextField(default="") user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) listing = models.ForeignKey(Listing, on_delete=models.CASCADE, default=1) def comment(request, listing_id): listin = Listing.objects.get(id=listing_id) if request.method == "POST": comment = CommentForm(request.POST) if comment.is_valid(): comment = comment.save(commit=False) comment.user = request.user comment.listing = listin comment.save() return redirect("listing", listing_id=listing_id) HTML code: {% for comment in comments %} <p>{{ comment.user.username }}: {{ comment.comment }}</p> {% endfor %} -
Proper way to use a counter variable in HTML with Chart.js on Django
I am relatively new to Django and Chart.js. To create charts using Chart.js, I need the charts to have different names. For this, I have thought about using a counter variable. <script>**var count = 0;**</script> <ul> {% for object in objects %} <li> ... <script> {% block jquery %} console.log(count); var endpoint = '/api/chart/data/'; fetch(endpoint, { method: "GET", }).then(response => response.json()) .then(data => { console.log('Success:', data); **count = count + 1;** ... eval('var chart_id = "myChart{{ count }}"'); eval('var ctx{{ count }} = document.getElementById(chart_id)'); eval('var myChart = new Chart(ctx{{ count }}, graph_data)'); console.log("myChart{{ count }}") }) .catch((error) => { console.log("Error:") console.log(error); }); {% endblock %} </script> <canvas id= "myChart{{ count }}" width="400" height="400"></canvas> ... </li> {% endfor %} </ul> However, when I look in the source code on my dev server, I can see that the id for all of the canvas tags is simply "myChart". Why is this? What am I doing wrong? -
Filter not null dates with Django and GraphQL
We have a tour node with feauted_date (DateTime) field, that can also be nullable. class TourFilter(OrderByMixin): class Meta: model = TourModel fields = { 'featured_date': ['exact', 'lt', 'gt'], } class TourNode(DjangoObjectType): class Meta: model = TourModel filter_fields = TourFilter.Meta.fields interfaces = (relay.Node, ) Currently we use featured_date for sorting with OrderMixin, but is there any way to filter them by not null? -
Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? --> WSGI.PY file
When I try to execute py manage.py runserver I had the following message: Message of Import Error I found a lot of possible solutions on the internet. Ayway, I suggest firt, try the following. Go to the wsgi.py file, inside MySite. wsgi.py file Verify that Django is imported. I use Pycharm, the IDE allowed me to import directly from there. After this I was able to run manage.py -
Why does my Bootstrap and/or CSS look different on localhost:8000 than on 127001:8000 for my Django website? And how can I fix this issue?
For some reason my website looks different for both ports. Here is what I mean