Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - jinja syntax help - how do i pass the value of {{ title }} into the href url args?
so i have this html : {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} <h1>{{ title }}</h1> {% autoescape off %} <p>{{ entry|safe }}</p> {% endautoescape%} <br> <a href="{% url 'edit' 'cat' %}"><button type="button" name="button">Edit</button></a> {% endblock %} i want the url 'edit' to also get the value of the {{ title}} - instead of 'cat' ..i just used this value to test the rest of the code, but i don`t want to hard code it like that ... here are my urls.py: urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.title, name="title"), path("edit/<str:title>", views.edit, name="edit"), path("error/", views.error, name="error"), path("new/", views.new, name="new"), ] this is the code in views.py : def title(request, title): entry = util.get_entry(title) if entry == None: return redirect("error") entry_html = md.convert(entry) return render(request, "encyclopedia/title.html", { "entry": entry_html }) def edit(request, title): if request.method == "POST": # get the changes from the user form = EditEntryForm(request.POST) if form.is_valid(): content = form.cleaned_data["content"] # save the entry and redirect to the updated page util.save_entry(title, content) return redirect("title", title=title) else: redirect("edit", title=title) entry = util.get_entry(title) form = EditEntryForm(initial={'content': entry}) return render(request, "encyclopedia/edit.html", { "form": form }) as i said the code … -
Create unique id by combining Charfield and ForeignKey from other model
I am having trouble with setting up the flow of my site with manytomany relationships. For example, there are many models that have many types and vice versa. I am thinking I can circumvent this by creating variables that literally link the model to type to let it be used as a foreign key by another model. However, I am having trouble pulling the values. If there is an easier way to solve this problem please let me know! class typed(models.Model): typed = models.CharField(max_length=200, help_text='Enter MFG - Type') model = models.ForeignKey('model', on_delete=models.SET_NULL, null=True) model_type = model + typed def get_absolute_url(self): return reverse('typed-detail', args=[str(self.model), str(self.model_type)]) def __str__(self): return self.model_type I get this error: TypeError: unsupported operand type(s) for +: 'ForeignKey' and 'CharField' -
Django, allow business admin to set 12/24 hour clock?
Hi everyone I am working through a issue I've been dealing with to allow business admin to change their company's system time clock from either 12 hour to 24, and vice versa. I have tried a couple different ways, but unable to find a way to display the change in the view. I have 2 views, a basic display View and an UpdateView class DateTimeConfig(View): def get(self, request): business = Business.objects.filter(**get instance here) business_tz = business.timezone # Default to 12 hour clock current_time = datetime.datetime.now().strftime(f"%m/%d/%Y, %I:%M%p") context = { 'timezone': business_tz, 'current_time': current_time } return JsonResponse(context, status=200) class DateTimeConfigUpdate(UpdateView): model = Business form_class = SystemUpdateForm def get_object(self, queryset=None): business = self.get_queryset().filter(**get instance here) return company def form_valid(self, form): form.save() return JsonResponse({'message': 'Business date/time updated successfully.'}, status=200) I have a simple form here, to change the Timezone and a dropdown for 12, or 24. class SystemUpdateForm(ModelForm): clock = forms.ChoiceField(choices=(('12', '12'), ('24', '24'))) class Meta: model = Business fields = ['timezone', 'clock'] def save(self, commit=True): if self.cleaned_data.get('clock') == '24': logger.debug('24 hour clock') else: logger.debug('12 hour clock') Now, I know the form does work, because the appropriate logged message changes based on the 12, and 24 dropdown. My issue is figuring a way … -
How do I implement multiple user types with Django-allauth
I am trying to implement multiple user types in Django-allauth while using a Profile model. How do I g about it? I am creating a model StudentProfile with a OnetoOne relationship with the User model. How do I have both forms on the same template, and save them both (and also check for errors in both forms? -
How best to capture variables from within a for-loop in Django template
I have two querysets: type and age_group. type queryset: <QuerySet [<Type: Cat>, <Type: Dog>, <Type: Other>]> age_group queryset: <QuerySet [<AgeGroup: Young>, <AgeGroup: Baby>, <AgeGroup: Adult>, <AgeGroup: Senior>]> I loop through these from within my template form so that I can grab the pk when one has been selected, but I cannot capture the variable from within the for loop. How do I capture a variable from within a for loop when using Django? Template: {% extends 'base.html' %} {% block content %} <h1>Animal Search</h1> <form class="form-inline" action= '.' method="post"> {% csrf_token %} <select name= "TypeSearch" class="custom-select my-1 mr-sm-2" id="animal_list_type"> <label class="sr-only type" for="animal_list_type">SEARCH</label> {% for i in animal_type_list %} <option value="{{i.pk}}">{{i}}</option> #how to capture the selected pk?? {% endfor %} </select> <select name="AgeSearch" class="custom-select my-1 mr-sm-2" id="animal_list_ageGroup"> <label class="sr-only ageLabel" for="animal_list_ageGroup">SEARCH</label> {% for j in age_group_list %} <option value="{{j.pk}}">{{j}}</option> #how to capture the selected pk?? {% endfor %} </select> <input type="submit" value="SEARCH" onclick="window.location='{% url 'animals:matches_list' pk=4 %}'; return false;"> <input type="submit" onclick="window.location='{% url 'animals:animals' %}'; return false;" value="Cancel"> </form> {% endblock %} Outside of Django, this would be a simple problem to solve. How do I capture a variable from within a for loop when using Django? I have tried … -
Django Product Filter Queryset
my current problem is that when a customer accesses my product page, I want them to first see all the available colors for the product and then after they select the color, I want them to see all the sizes in which the product is available in that color. In my database I store the data with the following model: class Stock(models.Model): class Meta: unique_together = (("product","color","size"),) product = models.ForeignKey(Product, on_delete=models.CASCADE) color = models.ForeignKey(Color, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE) stock = models.PositiveIntegerField() -
django-allauth Google login not working on iOS
I'm building a PWA with django and have this issue with django-allauth Google login. Everything works well on a Windows PC with Chrome and Edge. But when trying to login with Google on iOS devices, I get the social network login failure with code: 'unknown', exception: 'PermissionDenied()' Any ideas what could be the reason or where to search for it? -
No ready() function when starting django with uvicorn
I have a problem because when starting a Django application by uvicorn, Django's AppConfig don't seem to be running ready() function. Can you help me to overcome this problem? -
How to make DecimalField use only whole numbers in some cases?
class TransactionHistory(models.Model): from_account = models.ForeignKey( 'Account', on_delete=models.CASCADE, related_name='from_account' ) to_account = models.ForeignKey( 'Account', on_delete=models.CASCADE, related_name='to_account' ) amount = models.DecimalField( max_digits=12, decimal_places=2, ) created_at = models.DateTimeField(default=timezone.now) I am using a DecimalField to represent account's balance. It's ok if I want to represent USD using it, but if I want to represent currencies like BTC, I need to save it as an integer, representing it as the number of satoshi. Also I could use decimal_places=6 to represent bitcoin, but how to make decimal_places set dynamically, based on account currency? -
How can I fetch data where my condition uses data from another row of same table?
I have this table: | id | created_at | updated_at | visited_page | visited_date | user_id | +----+----------------------------+----------------------------+-------------------+--------------+----- | 1 | 2020-12-28 18:09:40.243560 | 2020-12-28 18:09:40.244170 | 1 | 2020-12-28 | 78557 | | 2 | 2020-12-28 18:10:41.290824 | 2020-12-28 18:10:41.291217 | 1 | 2020-12-29 | 78557 | | 3 | 2020-12-28 18:19:36.948853 | 2020-12-28 18:19:36.949289 | 3 | 2020-12-29 | 78557 | +----+----------------------------+----------------------------+-------------------+--------------+----- Here I want to fetch user_ids where the updated_at difference between two different pages visited by the same user is greater than 6 minutes on a particular date (in above tables case date = 2020-12-29). Please answer how can I fetch this information using a single query in Django? Also, please explain how this query will look in SQL? -
Django - Deduplicate based on multiple attributes
I have a model representing an answer (can be correct or incorrect) to a question. A user might give multiple incorrect and multiple correct answers. class Answer(models.Model): match_event_id = models.UUIDField( primary_key=True, default=uuid.uuid4 ) user_profile = models.ForeignKey(UserProfile, null=True, on_delete=models.SET_NULL) test_session = models.ForeignKey(TestSession, null=True, on_delete=models.SET_NULL) question = models.ForeignKey(Question, null=True, on_delete=models.SET_NULL) # The actual text answer provided by the user event_text = models.TextField(default="") # Indicate if the answer is correct or not match_success = models.BooleanField(default=False) # Client name client = models.TextField(default="Unknown") I'd like to create a query which counts the number of correctly answere questions but not the number of correct answers. Currently my basic query looks like this: count_success = Answer.objects.filter(user_profile=self.user_profile_id, match_success=True).count() This gives me the number of all correct answers but since there might be multiple correct answers per question this is not what I want. How can I do some kind of deduplication based on user_profile, test_session, question and match_success? So whenever there is one correct answer by the user to one question in a test session I'd like to add 1 to the count. Thank you !! -
Django: using data from entries for many views functions
I'm new in Django and now I'm working on my first project. My home.html file includes form (bootstrap class) with contains entries to fill with data. These data are integer type. In views, in function home, where this home.html file is used , data from entries are taken by 'get' method and used for calculations and results are displaying in labels in mentioned form. My question is how can I use these data from entries or results of calculations or both of them by another function in views called some_view with generates PDF file using ReportsLab. Thanks home.html <!DOCTYPE html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>Title</title> <style> body { margin: 40px } .my-container { border: 1px solid green} .my-row { border: 2px solid blue} .my-col { border: 2px solid red} btn-primary { margin-left: 50px} .align-right { text-align: center; border: 0; } </style> </head> <body> <div class="container my-container"> <form method="get"> <div class= "row my-row"> <div class="col-3 my-col"> <input type="text" placeholder="0" name="li200" size="1" /> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if liczba %} {{ liczba }} {% endif %} </span></h3> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if ls %} {{ ls }} {% endif %} … -
recaptcha not working properly in django project
This is the first time I am trying to apply Recaptcha to my contact form, but I keep receiving an error in the console as following: Uncaught Error: Missing required parameters: sitekey at bW.<anonymous> (recaptcha__en.js:355) at new bW (recaptcha__en.js:466) at $7.<anonymous> (recaptcha__en.js:137) at new $7 (recaptcha__en.js:400) at Array.<anonymous> (recaptcha__en.js:320) at recaptcha__en.js:269 at Array.forEach (<anonymous>) at Array.<anonymous> (recaptcha__en.js:269) at Array.<anonymous> (recaptcha__en.js:373) at recaptcha__en.js:285 I'd like some help in understanding what is there as every time I try to submit a form I am receiving an error that Oops, you have to check the Recaptcha which I have set. Here is the views.py def home(request): template_name = 'base/home.html' if request.method == 'POST': if request.POST.get('rechaptcha', None): form = MessageForm(request.POST) if form.is_valid(): form.save(commit=False) data = { 'name': request.POST['name'], 'email': request.POST['email'], 'message': request.POST['message'] } email_send(data) form.save() return JsonResponse({'success': True}) else: return JsonResponse({'success': False, 'errors': form.errors}) return JsonResponse({'success': False, 'errors': "Oops, you have to check the recaptcha !"}) if request.method == 'GET': form = MessageForm() context = { 'form': form, } return render(request, template_name, context) def email_send(data): subject = 'Portfolio : Mail from {}'.format(data['name']) message = '{}\nSender Email: {}'.format(data['message'], data['email']) email_from = settings.EMAIL_HOST_USER recipient_list = ['email', ] send_mail(subject, message, email_from, recipient_list) Here is the template: <form … -
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