Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django Rest Framework: Second parameter in url being constructed with a dot (.) instead of /
I've got the following method in my View: @action(detail=True, methods=['delete']) def remove(self, request, *args,**kwargs): print("here") I've created a test for this endpoint. But haven't been able to get the correct url. When I do url = reverse('order-remove', kwargs={'pk':1234, 'product_id':1}) I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'order-remove' with a keyword arguments ... not found. 2 pattern(s) tried: ... and when I try: pk=1234 product_id=1 url = reverse('order-remove', args=(pk, product_id,)) I got the following url: /orders/1234/remove.1 instead of what I'd be expecting which is: orders/1234/remove/4 with an / instead of . What am I missing? -
How to update html form from two models form? The views don't works correctly with two models
Hear is my views.py which works with one models form and when I add some code for another >form, nothing add to db tables. It save only default data membership table. Html form fields looks like this {{ m_form.subscription_type }} MWhat else can be wrong? def add_user(request): view_all = User.objects.all() success = 0 current_user = request.user user = User.objects.get(username=current_user) m_user = Membership.objects.create(users=request.user) if request.method == 'POST': m_form = MembershipForm(request.POST, instance=m_user) form = AddUserForm(request.POST, instance=user) if form.is_valid() and m_form.is_valid(): temp = form.save(commit=False) temp.first_name = request.POST.get('first_name').capitalize() temp.last_name = request.POST.get('last_name').capitalize() temp.date_joined = parser.parse(request.POST.get('date_joined')) temp.save() m_form.users = form m_form.save() success = 'Successfully Added user' form = AddUserForm(initial={ 'username': request.user.username}, instance=request.user) user = User.objects.last() m_user = Membership.objects.last() context = { 'add_success': success, 'form': form, 'm_form': m_form, 'user': user, 'm_user': m_user, } return render(request, 'membership/add_user.html'.format(user.id), context) Hear is another file models.py class User(AbstractUser): birth_date = models.DateField(null=True, blank=True) height = models.DecimalField(max_digits=3, decimal_places=1, default=0) class Membership(models.Model): users = models.ForeignKey('User', on_delete=models.CASCADE, related_name="users") price = models.DecimalField(max_digits=5, decimal_places=2, default=0) subscription_type = models.CharField( ('Subscription Type'), max_length=30, choices=SUBSCRIPTION_TYPE_CHOICES, default=SUBSCRIPTION_TYPE_CHOICES[0][0] ) def __str__(self): return f"{self.first_name} - {self.last_name}" and forms.py class AddUserForm(ModelForm): def __init__(self, *args, **kwargs): super(AddUserForm, self).__init__(*args, **kwargs) self.fields['first_name'].error_messages = {'required': 'Please enter first name'} self.fields['last_name'].error_messages = {'required': 'Please enter last name'} self.fields['username'] class … -
type object 'HttpResponse' has no attribute 'User'
I am trying to create projects to currently signed in users. I've tried many different things with my CreateProjectView class however keep running into errors. My codes are below. Models.py models.py Views.py views.py error code AttributeError: type object 'HttpResponse' has no attribute 'User' [06/Mar/2021 11:55:09] "POST /add HTTP/1.1" 500 88813 -
Django with a Python API?
I have a python script that scrapes tweets off of Twitter and wanted to make it into a website. My script outputs a text file with the scraped tweets. I figured out how to render the contents of this text file onto my Django website but I don't know how to get the scraper to run every time someone refreshes the website so they get the latest tweets. Does anyone know how to make that work or point me in the right direction? I'm kind of a complete beginner when it comes to web development so I might not fully understand how this exactly works. -
how to use custom js in django inlineformset?
i have used Inlineformset in my django project , but i have to use my own js for increasing forms ! but i didnt find any way to make it work this is my models.py class Invoice(models.Model): seller = models.ForeignKey(User,on_delete=models.CASCADE) customer = models.CharField(max_length=50) items = models.ManyToManyField(Item,through='InvoiceItem') class InvoiceItem(models.Model): item = models.ForeignKey(Item,on_delete=models.CASCADE) invoice = models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='invoice') quantity = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=3) cash = models.DecimalField(max_digits=20,decimal_places=3) discount = models.DecimalField(max_digits=20,decimal_places=3) and this code is my views.py , i have used Class Based View class CreateClientInvoiceView(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = CustomerInvoice form_class = ClientInvoiceForm template_name = 'invoiceapp/create_invoice.html' def get_context_data(self,*args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['items'] = CustomerInvoiceInlineFormset(self.request.POST) data['items'].full_clean() else: data['items'] = CustomerInvoiceInlineFormset() return data def form_valid(self, form): res = super().form_valid(form) self.object = form.save() context = self.get_context_data() items = context['items'] with transaction.atomic: form.instance.seller = self.request.user if form.is_valid() and items.is_valid() and items.cleaned_data !={}: items.instance = self.object items.save() form.save() else: return render(self.request,self.template_name,context) return super().form_valid(form) def get_success_url(self): return reverse_lazy('invoiceapp:customer-invoice',kwargs={'pk':self.object.pk}) this is my html + js code {% extends 'base.html' %} {% load widget_tweaks %} {% load static %} {% block title %} create new invoice {% endblock %} {% block content %} <form method="POST">{% csrf_token %} {{items.management_form}} <div class="w-full md:w-11/12 mx-auto realative p-2 bg-gray-200 invoice" style="direction: ltr !important;"> <div class="p-1 pr-2 … -
how to pass django params in react components
i am new to react , i am building simple blog where user can post with title and body in html its done with listview with: {% for x in object_list %} {% endfor %} but in react component its not getting good result and showing error here is my code: models class post(models.Model): title = models.CharField(max_length=100) body=models.TextField() views class list(ListView): model = post template_name = 'index.html' post.js function Post(){ return( {% for x in object_list %} {% endfor %} ) } in react what can i do to retreive data from model like we used to do in normal html, or show the object from model in components??