Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Translate SQL max() group by to Django
I have a table with two columns: listing and bid. Each listing can get multiple bids. I want to run a Django query that returns the highest bid for each listing. In SQL I would do this: SELECT listing, max(amount) FROM Bid GROUP BY listing In django I tried this. It only returns the single highest bid in the whole table Bid.objects.values('listing','amount').aggregate(Max('amount')) -
Boolean field is not updated via Queryset or save()
I have this code. def status(request, item_id): item = AuctionList.objects.get(id=item_id) statusitem = bool(item.status) if statusitem == True: item.status = False item.save() return HttpResponseRedirect(reverse("index")) else: item.status = True item.save() return HttpResponseRedirect(reverse("index")) When executing the page, the "view" is executed, but the change of status is not saved in the database. Do you know what could be happening? -
Can you have the same Django App on two different servers?
Can I have a Django App on Machine A, which takes care of all the routing and the same "stripped" App on Machine B (with some more computation power) that's only used for running jobs to modify some fields of a model thus don't have all the views, templates etc. but only used to call some MyModel.objects.get(user=my_user).save()? -
How to make a success ulr for my contact page
I want the client to be redirected to another HTML page as a successfully sent message in my contact form. But I don't know exactly what is wrong here. I can't redirect to my success page but the form works. #my main app's url.py urlpatterns = [ path('^contact/', include('contactus.urls')), ] #my contact app url.py from __future__ import unicode_literals from django.conf.urls import url from django.views.generic import TemplateView from .views import ContactUsView urlpatterns = [ url(r'^$', ContactUsView.as_view(), {}, 'contactus'), url(r'^success/$', TemplateView.as_view(), {}, 'contactus-success'), ] #contact app view.py from __future__ import unicode_literals from django.conf import settings from django.core.mail import EmailMessage from django.template import loader from django.views.generic.edit import FormView from contactus.forms import ContactUsForm class ContactUsView(FormView): template_name = 'contactus/contact.html' email_template_name = 'contactus/contact_notification_email.txt' form_class = ContactUsForm success_url = "/contact/success/" subject = "Contact Us Request" def get_initial(self): initial = super(ContactUsView, self).get_initial() if not self.request.user.is_anonymous: initial['name'] = self.request.user.get_full_name() initial['email'] = self.request.user.email return initial def form_valid(self, form): form_data = form.cleaned_data if not self.request.user.is_anonymous: form_data['username'] = self.request.user.username # POST to the support email sender = settings.SERVER_EMAIL recipients = (getattr(settings, 'CONTACT_US_EMAIL'),) reply_to = form_data.get('email') or sender tmpl = loader.get_template(self.email_template_name) email = EmailMessage( self.subject, tmpl.render(form_data), sender, recipients, reply_to=[reply_to], ) email.send() return super(ContactUsView, self).form_valid(form) #contact app forms.py from __future__ import unicode_literals from django … -
Django: unable to display iunformation using a TemplateView Class Based view
I'm using a Class Based view (TemplateView) to display some information from a User and a UserProfile model (onetoone between User and UserProfile) and this is working as expected. I decided to use the same TemplateView to display some other data from 2 models and I don't understand why I cannot retrieve and display information. I suspect this is because one of the models (UserSubscription) has 2 fks, one to User model, and another one to "Subscription" model. I've tried to use related_name in the fks but not sure I'm using it correctly. Hereunder the code: models.py class UserSubscription(models.Model): user = models.ForeignKey(User, related_name= 'tousers', related_query_name='touser', on_delete=models.CASCADE, null=True, blank=True) subscription = models.ForeignKey("Subscription", related_name = 'tosubscriptions', related_query_name='tosubscription',on_delete=models.CASCADE, null=True, blank=True) created_date = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name="Created Date") subs_status = models.BooleanField(default=False, verbose_name="Subscription Status") expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name="Expiry Date") class Meta: verbose_name = "User Subscription" verbose_name_plural = "User Subscriptions" def __str__(self): return 'User: ' + str(self.user) + ' ' + 'PK: ' + str(self.pk) + ' Subscription :' + str(self.subscription) + ' ' + 'Expiring the : ' + str(self.expiry_date) class Subscription(models.Model): plan_name = models.CharField(max_length=50, null=True, blank=True, verbose_name="Subscription Plan Name") description = models.TextField(verbose_name="Subscription Plan Description") price = models.FloatField(verbose_name="Subscription Plan Price") start_date = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name="Subscription … -
json merging two datasets on canvas - django
I have a django application which has a canvas that saves the drawing drawn on to the canvas as jason data with points and lines in the databse i am able to save and retrieve these drawings onto canvas i am trying to merge two datasets into one and get it onto canvas say i have a data-1 below {"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]} data-2 {"points":[{"x":524,"y":343,"r":1,"color":"black"},{"x":523,"y":342,"r":1,"color":"black"},{"x":521,"y":339,"r":1,"color":"black"},{"x":520,"y":334,"r":1,"color":"black"},{"x":514,"y":319,"r":1,"color":"black"}],"lines":[{"x1":524,"y1":343,"x2":523,"y2":342,"strokeWidth":"2","strokeColor":"black"},{"x1":523,"y1":342,"x2":521,"y2":339,"strokeWidth":"2","strokeColor":"black"},{"x1":521,"y1":339,"x2":520,"y2":334,"strokeWidth":"2","strokeColor":"black"},{"x1":520,"y1":334,"x2":514,"y2":319,"strokeWidth":"2","strokeColor":"black"}]} i am trying to combine these two datasets and load into as a single drawing onto canvas at present i am able to load single data by using following javascript if (document.getElementById('JSONLoadData') != null) { // Parsing the loaded drawing from server to a JSON Object var loadedData = JSON.parse(JSONLoadData.value) // Iterating through all the points in the loaded drawing for(let i = 0; i < loadedData['points'].length; i++) { // Saving the point and drawing the same in the svg canvas const point = svg.append('circle') .attr('cx', loadedData['points'][i]['x']) .attr('cy', loadedData['points'][i]['y']) .attr('r', loadedData['points'][i]['r']) .style('fill', loadedData['points'][i]['color']); // Pushing the point inside points array points.push(point); } // Iterating through all the lines in the loaded drawing for(let i = 0; i < loadedData['lines'].length; i++) { // Saving the line and drawing the same in the svg canvas const line = svg.append('line') .attr('x1', … -
DjangoFilterConnectionField query for all records
I'm using DjangoFilterConnectionField with a django-graphene and django-filter. and I'd like to know if it's possible to get all the records via a query? Consider the following code: class Query(graphene.AbstractType): txt = graphene.Field(LocalizedTxtType) all_txts = DjangoFilterConnectionField(LocalizedLocalizedTxtType) How can I get all records with no filter (i.e. allTxts) ? Do I need to add a resolve_all myself , or does DjangoFilterConnectionField provide a way to query for all records? -
How can I sort a django queryset by a value from a different table?
I have these models: class NHLTeam(models.Model): team_name = models.CharField(max_length=50) team_id = models.IntegerField() # The NHL API gives each team an id. Probably useful to save it. city = models.CharField(max_length=50) class NHLGame(models.Model): home_team = models.ForeignKey(NHLTeam, on_delete=models.CASCADE, related_name="home_team") away_team = models.ForeignKey(NHLTeam, on_delete=models.CASCADE, related_name="away_team") date = models.DateField() class Distance(models.Model): destination = models.ForeignKey(NHLTeam, on_delete=models.CASCADE) starting_country = models.CharField(max_length=2, choices=COUNTRY_CHOICES) starting_province = models.CharField(max_length=50) starting_city = models.CharField(max_length=50) distance = models.DecimalField(decimal_places=1, max_digits=6) So basically NHLTeam just contains the 31 teams currently in the NHL. NHLGame represents an actual game which contains a home_team, away_team and a date. Distance contains the distance from the city the user lives in to the team. If I get a list of the NHLGames with NHLGame.objects.all() I get this: <QuerySet [<NHLGame: 2021-02-05: Boston Bruins @ Philadelphia Flyers>, <NHLGame: 2021-02-05: Detroit Red Wings @ Tampa Bay Lightning>, <NHLGame: 2021-02-05: Nashville Predators @ Florida Panthers>, <NHLGame: 2021-02-05: Los Angeles Kings @ Vegas Golden Knights>, <NHLGame: 2021-02-05: San Jose Sharks @ Anaheim Ducks>, ....]> If I want to sort this by the Home team name i can do games.order_by('home_team__team_name') which gives me: <QuerySet [<NHLGame: 2021-02-05: San Jose Sharks @ Anaheim Ducks>, <NHLGame: 2021-02-06: San Jose Sharks @ Anaheim Ducks>, <NHLGame: 2021-02-18: Minnesota Wild @ Anaheim Ducks>, … -
Django admin - How to add request.user as default vaule for a Inline field?
I've written a small support application made out of 2 models, please see below. As I answere onto support tickets at the django admin panel, I dont always want to set the author name manully for each reply I add to the ticket. Instead I want that request.user I set as author automatically as initial vaule. Sadly I was not able to find any solution at the django docs that seem to solve this issue ... admin.py class SupportTicketRepliesInline(admin.TabularInline): model = SupportTicketReplies extra = 0 min_num = 1 class SupportTicketsAdmin(admin.ModelAdmin): list_display = ['requester', 'creation_date', 'status', 'category', 'subject'] actions = [set_ticket_open, set_ticket_waiting_for_requester, set_ticket_waiting_for_support, set_ticket_closed] ordering = ['-creation_date'] list_filter = ['creation_date'] inlines = [ SupportTicketRepliesInline, ] admin.site.register(SupportTickets, SupportTicketsAdmin) models.py ... class SupportTickets(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) requester = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) category = models.IntegerField(choices=TICKET_CATEGORY, verbose_name='Ticket Category') subject = models.CharFi[![enter image description here][1]][1]eld(max_length=30, validators=[MinLengthValidator(4)]) description = models.TextField(max_length=2000, blank=False, verbose_name='Problem description') status = models.IntegerField(choices=STATUS_OF_TICKET, verbose_name='Ticket Status', default=2) creation_date = models.DateTimeField(auto_now_add=True, blank=False) def publish(self): self.creation_date = timezone.now() self.save() class Meta: verbose_name = "Support Ticket" verbose_name_plural = "Support Tickets" ordering = ['-creation_date'] models.py class SupportTicketReplies(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ticket = ForeignKey(SupportTickets, related_name='replies', on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Author', blank=True) content = … -
Django ORM F expression and two dates fields of the same model
Given the model: class Ad(models.Model) : ... created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I launched the pyhton manage.py shell, and tried the following Query: from django.db.models import F from myapp.models import * a=Ad.objects.all().filter(created_at__day=F('updated_at__day')) a=Ad.objects.all().filter(created_at__date=F('updated_at__date')) I tried to find all the enteries that have been created & updated in the same day/date, but it doesn't work. Both return Empty Results.. What I missing here ? Thanks ! -
How to serve static images for Django REST framework
I'm trying to create Django REST app, however I cannot manage to allow the url of the image to be accessible. I managed to get the upload done, however when I have the URL there is no way to access the photo from browser. I stored them in folder profile_pictures and I was thinking of loading the image from localhost:8000/profile_pictures/image_name.jpg but I'm not sure how to setup this, as I tried linking static files to the urls but nothing seems to work. -
How to handle invalid input using django forms?
I am trying to build my first webiste using django and I encountered a problem: I am trying to render a form with personal details of a person for placing an order. Also, I added an extra validation in forms.py but I get a weird error and I do not understand why. urls.py ....... path("order", views.my_form_view, name='order'), ....... views.py @login_required @decorator_cart def my_form_view(request): """This function renders the order's form""" cart_items = UserItem.objects.all() form = OrderForm(request.POST) total_value = UserItem.total(cart_items) VAT = UserItem.VAT(total_value) shipment = UserItem.shipment(total_value) context = {"form": form, "total": total_value, "VAT": VAT, "shipment": shipment} return render(request, 'order.html', context=context) order.html {% block content %} <div class="updt"> <div class="containerLogin"> <h2>Order details</h2> <form action='{% url 'sent-form' %}' method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Place order"> <br><br> </form> <a href="{% url 'cart' %}">Back to cart</a> </div> <div style="right:0; position: absolute; margin-right: 50px;"> Total: {{ total }} <br> VAT: {{ VAT }} <br> Shipment: {{ shipment }} </div> </div> {% endblock %} forms.py class OrderForm(forms.Form): first_name = forms.CharField(max_length=30, required=True, help_text='Required') last_name = forms.CharField(max_length=30, required=True, help_text='Required') email = forms.EmailField(max_length=254, required=True, help_text='Enter a valid email address') street = forms.CharField(max_length=50, required=True, help_text='Required') number = forms.IntegerField(required=True, help_text='Required') city = forms.CharField(max_length=50, required=True, help_text='Required') country = forms.CharField(max_length=50, required=True, … -
How to display download button in Video in Javascript
I am running a Django project and using video.html file for displaying video. I have below code which is displaying video, but i want to change the play button of video and also introduce a download button like this <video id="{{portfolio.id}}" onclick="videoviews({{portfolio.id}})" class="video-js vjs-theme-forest" controls preload="auto" width="360" height="264" data-setup="{}"> <source src="{{ portfolio.file.url }}" type="video/mp4"> I have attached screenshot of current video frame. I am a beginner in Django and Javascript, Please help. -
Django BinaryField default value
What can I use to set default value for BinaryField in Django? Every example, I've found just use field = models.BinaryField() and everything works somehow. What should I user for BinaryField(default=something)? -
TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile error
TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile when i try to upload a image file and enter submit this error pops up please give me solution -
Have been sitting on this for an hour and cant figure our why /js/bootstrap.min.js is not found
I got the following code in base.html , were Im trying to make the bootstrap starter template. I have copy pasted from bootstrap but I get the following error when running :/js/bootstrap.min.js. Could you please let me know whats wrong? Thanks ! <!DOCTYPE html> <html lang="en"> <head> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Bootstrap 101 Template</title> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> {% if title %} <title>Django Blog - {{title}}</title> {% else %} <title>Django Blog </title> {% endif %} </head> <body> <div class="container"> {% block content %}{% endblock %} !-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/bootstrap.min.js"></script> </div>`enter code here` </body> </html> -
Why does importing "from .forms import LoginForm" return an error in django?
This is my "login/views.py" file. As you can see I am importing "from .forms import LoginForm". I checked my "login/models.py" file and I have the right imports and class that I need. This returns error: "ModuleNotFoundError: No module named 'login.forms'". Any help would be greatly appreciated. from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import LoginForm def login(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): return HttpResponseRedirect("/home/") else: form = Form() return render(request, "login/login.html") -
Cannot Update Custom User (AbstractUser)
I am using a custom user model which inherits from the AbstractUser and when I save a user it works well. But whenI need to update the model and I click on my submit button on my template nothing happens. Nothing shows in the console, the page does not reload, nothing. I would really appreciate some guidance here? #models from django.core.validators import RegexValidator from sos.models import Company from django.db import models from django.contrib.auth.models import AbstractUser from django.core.validators import MinValueValidator, MaxValueValidator from django.urls import reverse # page 138 Django for Beginneers # Create your models here. # https://stackoverflow.com/questions/19130942/whats-the-best-way-to-store-phone-number-in-django-models/19131360 class CustomUser(AbstractUser): position = models.CharField(max_length=30, null=True ) email = models.EmailField(null=True, blank=False, unique=True ) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") mobile_phone = models.CharField(validators=[phone_regex], max_length=17, blank=False, null=True, unique=True) date_created = models.DateTimeField(auto_now_add=True, editable=True) is_staff = models.BooleanField(verbose_name="Is Staff Admin?", help_text="Designates whether this user should be able to log in the Admin Interface.") company = models.ForeignKey(Company , on_delete=models.CASCADE, verbose_name="Company Name") def __str__(self): return self.username def get_absolute_url(self): return reverse("customuser_detail", args=[str(self.id)]) class Meta: ordering = ["username"] # forms from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser from .models import UserTargets # cripsy forms imports … -
Storing raw text data vs analytics
I’ve been working on a hobby project that’s a django react site that give analytics and data viz for texts. Most likely will host on AWS. The user uploads a csv of texts. The current logic is that they get stored in the db and then when the user calls the api it runs the analytics on them and sends the analytics. I’m trying to decide whether to store the raw text data (what I have now) or run the analytics on the texts once when they're uploaded and then discard them, only storing the analytics. My thoughts are: Raw data: pros: changes to analytics won’t require re uploading probably simpler db schema cons: more sensitive data (not sure how safe it is in a django db on AWS, not sure what measures I could put in place to protect it more) more data to store (not sure what it would cost to store a lot of rows of texts) Analytics: pros: less sensitive, less space cons: if something goes wrong with the analytics on the first run (that doesn’t throw an error), then they could be inaccurate and will remain that way -
I can't running django on port 80
I can't running django in my website server at port 80... because It gives me that port is already in use?? may I know what's the problem exactly? this is the link for my website It only gives me a html page (zabarjad.co). but when I type in command line to run django this is what happen: aziz@zabarjad-djangostack-vm:/var/www/zabarjadprod$ sudo python3 manage.py runserver 0.0.0.0:80 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 06, 2021 - 17:40:17 Django version 2.2.15, using settings 'zabarjadprod.settings' Starting development server at http://0.0.0.0:80/ Quit the server with CONTROL-C. Error: That port is already in use. -
django application latency response on server
Application works proper on local but on server its behaves like , I am getting inconsistent behavioral response while reading and deleting json object from .json file in django application. inconsistent means if file containing 10 records, to each (django API call)get request it returns different number of records. Not always return all objects. Please give me some idea. -
Local and Global Variables in If statement (Error)
I have been having a problem with a bit of code. I have readed Python documentation about local and global variables. As I understand it, local and global scope isn't affected by if statements. My code is the follow: user = request.user if user == auction.user: owner = True print(owner) Nevertheless, i have this error: UnboundLocalError: local variable 'owner' referenced before assignment. Can you tell me what's the cause of this error? And, how can i fix it? Thx. -
Update values in Django model from other machine
I have a Django App which runs on GAE at the moment. I want to do some backend operations and update some of the fields in one of my models, say my_model, but from another machine since the computation is rather heavy (they are both Google App Engines) i.e Model-modifying (GAE2) <----> Django App (GAE 1) What is the best way to do so to prevent e.g database locking or issues if a model object is modified by a user when I push changes to it at the same time? I've thought about just having a python script running on GAE2 which pulls and pushes the data from/to the Django Database using pandas but I don't know if that is safe. -
How to reload multiple HTML elements with one 'GET' method
Here is part of my code: function x(action) { if (action == 'reload') { $("#a").load(" #a > *"); $("#b").load(" #b > *"); $("#c").load(" #c > *"); $("#d").load(" #d > *"); } } I want these #a,#b,#c,#d elements reload themselves after some actions. My code is working but I get multiple same GET records in my backend everytime I trigger the function, like this: [07/Mar/2021 01:09:02] "GET /xxx/ HTTP/1.1" 200 12250 [07/Mar/2021 01:09:02] "GET /xxx/ HTTP/1.1" 200 12250 [07/Mar/2021 01:09:02] "GET /xxx/ HTTP/1.1" 200 12250 [07/Mar/2021 01:09:02] "GET /xxx/ HTTP/1.1" 200 12250 I wonder if there is an easy way to reload these elements by using 'GET' method only once, and without using location.reload() -
Djoser Access base endpoints with JWT token
i'm using djoser and simplejwt for my django rest API and I was wondering how I could access the /users/me djoser endpoint with a jwt token. When I try accessing the endpoint with the header: Authorization: JWT my-jwt-token It returns 403 Forbidden and it's saying that credentials were not provided. Can someone explain me how I could do such a thing? Thanks for reading.