Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What Should I choose Django projects Or Start JS & React
If I should focus some more time on django and python. Can You please suggest me some projects for practice. Else: I should start react or Js or AWS? Thank You In Advance! -
Django server does not serve static files for admin page
I have a Django server running with nginx and gunicorn. All static files are served correctly, only the admin page has no css, js, etc. . I already ran collectstatic and restarted nginx and gunicorn. Nothing changed. What can I do? -
Accessing different `pk` values in Django
How do I show just a certain pk value of my sqlite database in django? I have a database that has a bunch of entries. I am currently accessing them through a DetailedView and they are all showing up nicely on the screen. i have called the entries post and i have given them title and body elements, which are just of type TextField() home.html {% block content %} {% for post in object_list %} <div class="post-entry"> <h2> <a href="{% url 'post_detail' post.pk %}">{{ post.title }}</a> </h2> <p>{{ post.body }}</p> </div> {% endfor %} {% endblock content %} What I now want to do is to place the 10th Database entry in the footer of my Home.html. So obviously this databases pk value is 10. i am just having trouble accessing this 10th value. I have tried {{ post.pk.10 }} but that doesn't work. What am i missing in order to access only the 10th value? -
How is the flow of interpretation(python interpreter) in this block of code?
def product_create_view(request): form = ProductForm(request.POST or None) if form.is_valid(): form.save() form = ProductForm() context = {'form': form} return render(request, "product_create.html", context) This is a part of the views.py file.I was thinking, about what happens first, is the html file reached out and the view rendered, and then the validation etc takes place?Or the interpreter first goes through the block of code(validation,etc) and then, it renders the html file If it is the second case(Which it seems to be, since the block of code is written first), how does the interpreter know what the form looks like, without reaching out to the html file?(Or does it not need to? and does something else?) -
Django showing error on {% extends "base.html" %}
I am a beginner in Django. I am using {% extends "base.html" %} but it is not working. The "base.html" is in templates directory. -
Django templates escape filters issue
I am trying to avoid XSS on my website. for testing purpose, I gave a username like this: ali <script>alert('xss not escaped')</script> and in my template I tried escape and force_escape filters but none of them is working. Here is Django template code: <label for="user_name" id="user_name_label" class="user-name font-weight-samibold mb-0"> {{ username | force_escape }} </label> I am not able to understand, why these filters are not working, each time when the page is loaded, alert box appears. -
Django model to save a stock portfolio to db
I'm trying to build a financial app in Django. The goal of the app is: A user will have the ability to save a portfolio to the database, and the app will run different types of financial metrics on the data, as standard deviation, beta, alpha, ect.. The issue I'm facing is that the number of stocks a user has in their portfolio is different for each user. A user who is a risk-averse investor would maybe have ten stocks, while an investor who is trading in the short term might only have 2-3 stocks in the portfolio. Each transaction consists of 5 elements: the direction the user has traded, either "long" or "short." The ticker, volume of the trade, price paid, and the transaction date. So, for example, a user has three stocks the transactions would look something like this: Transaction example How can I give the user the ability to choose how many stocks they would like to record in the portfolio? My code: Models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings class Portfolio(models.Model): direction_option = ( ('Long','Long'), ('Short','Short') ) portfolio_name = models.CharField(max_length=200) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) direction = models.CharField(max_length=200, null=True, … -
using aggregate with values : group by : django
i want to return a product names in distinct , and also i've used aggregate to some calculation as well this is my models.py class CustomerInvoice(models.Model): customer = models.CharField(max_length=50) items = models.ManyToManyField(Product,through='ProductSelecte') date = models.DateTimeField(auto_now_add=True) class ProductSelecte(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) products= models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='product') qnt= models.IntegerField(default=1) price = models.IntegerField() cash = models.IntegerField() i want to make table to track customers activity : for example at 4th june he bought two pen with 3 book , and for 5th july he buy 1 pen with 2 copybook , i need a result like this : 3; pen , 3;book ,2;copybook and this is my query context['clients'] = ProductSelecte.objects.filter( products__customer=self.object.name).values('product').annotate(quantity=Sum(F('qnt'))).order_by('product') till here works fine but i also need to aggregate price using this .aggregate( total_price=Sum(F('price'))) it raise this error 'dict' object has no attribute 'order_by' thanks for your helping -
How to use calendar with jquery and theme with other jquery
I have a theme that uses jQuery v3.5.1 and I want to use a calendar that also uses jqury but other form: base page: <script src="{% static 'assets/vendor/jquery/jquery.min.js' %}"></script> page that extends base: {% extends 'main/base.html' %} <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" ></script> How can I make this work ? If I remove the second page's dependency then the calendar will work but the style of the theme not obviously. I've tried this solutions but didn't work: Can I use multiple versions of jQuery on the same page? Can anyone give me a hint ? -
Login and Registration form in one view - Django
I'm stuck for good. I have a problem with having two forms (login in and registration one) in one view and html page. I've tried everything that i found but nothing seems to work for me. How do I write a statement that checks what is what and then proceeds to add user to database or log him in. Thanks in advance -
how to extract year in date field of date of birth and calculate age of person in django views.py?
I am trying to do this in views.py ExtractYear(date_of_birth) - today.year But it gives error to use int, and i tried like: int (ExtractYear(date_of_birth) )- int(today.year) and it gives error of int() argument must be a string, a bytes-like object or a number, not 'ExtractYear' and also if i try to do this: name 'date_of_birth_year' is not defined also i did: import datetime I just wanted to find age of person in integer and i don't know how to extract year, hours etc things in datefield or datetime field kindly help. -
Wagtail Django admin model multiple images from orderable
I have a Location Model: class Location(models.Model): name = models.CharField(max_length=30, null=True, blank=False) image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=False, on_delete=models.SET_NULL, related_name="+", ) address = models.CharField(max_length=60, null=True, blank=False) city = models.CharField(max_length=25) state = models.CharField( max_length=2, choices=misc_options.STATES, null=True, blank=False) zipcode = models.CharField(max_length=5, null=True, blank=False) lat = models.CharField(max_length=50, null=True, blank=False) lon = models.CharField(max_length=50, null=True, blank=False) phone = models.CharField(max_length=10, null=True, blank=False) email = models.CharField(max_length=40, null=True, blank=False) places_id = models.CharField(max_length=100, null=True, blank=True) facebook_url = models.CharField(max_length=100, null=True, blank=True) google_url = models.CharField(max_length=100, null=True, blank=True) entity = models.CharField(max_length=10, null=True, blank=True) truck_url = models.CharField(max_length=100, null=True, blank=True) trailer_url = models.CharField(max_length=100, null=True, blank=True) supplies_url = models.CharField(max_length=100, null=True, blank=True) features = models.ManyToManyField(Feature) panels = [ MultiFieldPanel([ FieldPanel("name"), InlinePanel('location_images'), ], heading="Store Info"), MultiFieldPanel([ FieldPanel('city'), FieldPanel('state'), FieldPanel('zipcode'), FieldPanel('lat'), FieldPanel('lon'), ], heading="Location Info"), MultiFieldPanel([ FieldPanel('phone'), FieldPanel('email'), FieldPanel('facebook_url'), FieldPanel('google_url'), ], heading="Contact Info"), MultiFieldPanel([ FieldPanel('entity'), FieldPanel('truck_url'), FieldPanel('trailer_url'), FieldPanel('supplies_url'), ], heading="Web Self Storage Info"), MultiFieldPanel([ FieldPanel('places_id'), ], heading="Google Places Info"), MultiFieldPanel([ FieldPanel('features'), ], heading="Features Info"), ] class Meta: # noqa ordering = ['name'] verbose_name = "Location Detail" verbose_name_plural = "Location Details" def __str__(self): return self.name that is an Admin Model. I need to attach multiple images to each object in this model. I do this using a foreign key field with "Feature", but this makes all of the features … -
How to name model instances based on a value chosen in ModelChoiceField in Django?
I have problem with Django. I have class Typy and I want to name instances of this class based on username and field match_to_bet which is ModelChoiceField and is generated from base. class Typy(models.Model): users = (('user_1', 'user_1'), ('user_2', 'user_2')) user = models.CharField(max_length=10, blank=True, choices=users) mecz = models.ForeignKey('Mecz', on_delete=models.CASCADE, default=0) choice = Mecz.objects.values() match_to_bet = ModelChoiceField(queryset=choice, empty_label=None) bet_home = models.BigIntegerField() bet_away = models.BigIntegerField() def __str__(self): return str(self.user) + '_' + str(self.match_to_bet.__str__()) So far I get name with object's adress and have no idea how to change code to get names 'user'_'option chosen in match_to_bet' current instances names -
Why accessing Django QuerySet became very slow?
I have a model query in Django: Query = Details.objects.filter(name__iexact=nameSelected) I filter it later: Query2 = Query .filter(title__iexact=title0) Then I access it using: ...Query2[0][0]... A few days ago it worked very fast. But now it became at least 20 times slower. I test it on other PC, it works very fast. What can make it so slow on my first PC? -
How to store array of objects in mongodb from django
I am using mongodb as database for my project and I want to store a list of dictionary as array of objects in an object in mongodb from django. For Eg. {"id":1,"products":[{...},{...},{...},{...}..]} how do I define my model and how to query this. please help -
How to start id filed always start from 1 or just remove it?
I am facing problems with importing csv file into my db in django. I don't want to add id field when I import the csv file. app.admin/ from django.contrib import admin from .models import Products, Forimg from import_export.admin import ImportExportModelAdmin @admin.register(Products, Forimg) class ViewAdmin(ImportExportModelAdmin): pass app.models/ class Products(models.Model): Code = models.CharField(max_length=10) Product_description = models.CharField(max_length=200,primary_key = True) Val_tech = models.CharField(max_length=5) Quantity = models.IntegerField(default=0) UOM = models.CharField(max_length=5) Rate = models.FloatField(default=0) Value = models.FloatField(default=0) def __str__(self): return self.Product_description class Forimg(models.Model): products = models.OneToOneField(Products, on_delete=models.CASCADE, primary_key = True) image = models.ImageField(upload_to = 'img/', width_field= 30, height_field = 40) def __str__(self): return self.products.Product_description -
from libs.strings import * ModuleNotFoundError: No module named 'libs.strings'
This is the error I am facing right, I google it a lot but solutions did not work, I am using python 3.7 in my django application. -
How to fix TemplateDoesNotExist at /
I get this error TemplateDoesNotExist at / home.html when I try to render a page, it worked fine before until I split my settings file into development and production settings. here is my project structure. Here is my base settings that contains the template dir settings. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'project_management.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
how to return ManyToMany field while using aggregate
i want to return a ManyToMany fields data , and also i've used aggregate to some calculation , now i need to return products as well this is my models.py class CustomerInvoice(models.Model): customer = models.CharField(max_length=50) items = models.ManyToManyField(Product,through='ProductSelecte') date = models.DateTimeField(auto_now_add=True) class ProductSelecte(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) products= models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='product') qnt= models.IntegerField(default=1) price = models.IntegerField() cash = models.IntegerField() and this is my query context['clients'] = CustomerInvoice.objects.filter( customer=self.object.name).aggregate( total_order=Sum(F('product__qnt')), total_price=Sum(F('product__price'))) i want to make table to track customers activity : for example at 4th june he bought two pen with 3 book , and for 5th july he buy 1 pen with 2 copybook , i need a result like this : 3; pen , 3;book ,2;copybook i know i should use distinct and i dont know why dont have any output {{clients.items.all|join:','}} ? thanks for your helping -
Pagination on queryset on only a segment of the page and not the whole page
I have a page with projects for a specific category that begins with the top-x most earned projects, followed by the top-x most viewed and the third segment contains all (other) projects for this category. This third segment is long as it contains all projects for this specific category. Therefore, I would like to paginate them. But with standard pagination going to the next page will refresh the page, ending on the top of the page, needing to scroll down again to the third section (every single time you select the next page), which isn't very user friendly. I saw a site (kickstarter) where they were able to paginate only one segment of the page, leaving the other parts of the site untouched, which is exactly what I want. But I am a novice and I have no idea how to do this. Thanks for any ideas and help! My HTML code: {% for project in projects|dictsortreversed:"created_date"%} {% if project.num_days > 0 %} <div class="row no-gutters"> <div class="offset-1 col-4 mb-5 "> {% if project.image %} <a href="{% url 'project_detail' project.id %}" target="_blank"> <img class="img-fluid mt-5" src="{{MEDIA_URL}}{{ project.image }}"> </a> {% else %} <a href="{% url 'project_detail' project.id %}" target="_blank"> <img … -
Django app do not render html templates (no requirements.txt)
I am working with this app, I have tried running the app using the command provided in the doc then I had to install both Django and requests but now the template view do not render at all, it seems it's interpreted as text What do I have to install? Or this app is not working properly? I am not sure why there's no requirements.txt -
How to insert filtered list in table and add additional row of naming for each columns
I have a list of filtered value from SQL : in views.py name_list=list(AB.objects.filter(name__in=xyz).values_list('name', 'surname', 'sector','industry', 'country','city')) in template.html: <ul><li>{% for name, surname,sector,industry,country,city in name_list %} {{ name }} </li></ul> <ul><li>{% for name, surname,sector,industry,country,city in name_list %} {{surname}} </li></ul> <ul><li>{% for name, surname,sector,industry,country,city in name_list %} {{sector}} </li></ul> <ul><li>{% for name, surname,sector,industry,country,city in name_list %} {{industry}} </li></ul> <ul><li>{% for name, surname,sector,industry,country,city in name_list %} {{country}} </li></ul> <ul><li>{% for name, surname,sector,industry,country,city in name_list %} {{city}} </li></ul> Output of it is : Alex Klein Machinery Aerospace USA Kansas Lia Michelle Healthcare Drugs Ireland Dublin I want to add names to each columns such as Name, Surname, Sector, Industry, Country, City and insert them in table. I made ul and li as I di not know how to insert them in table Desired output is table the following way : Name Surname Sector Industry Country City Alex Klein Machinery Aerospace USA Kansas Lia Michelle Healthcare Drugs Ireland Dublin Would appreciate your help. -
i deploy django project in cpanel(namecheap) without base url others urls are not working
i deploy django project in cpanel(namecheap) without base url others urls are not working Not Found The requested URL was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. -
Page not found (404 error) on Django HttpResponseRedirect
I see that there are numerous posts related to HttpResponseRedirect errors(Django form redirect using HttpResponseRedirect, Django: HttpResponseRedirect not working, How can I redirect to a Thank you for contacting us page after user submits a form with Django?), and the explanations all make sense. Unfortunately, they have not helped me address my problem -- which I think/hope is more about looking at this too long and I can no longer see the forest for the trees. I am working off of this example (https://techwithtim.net/tutorials/django/simple-forms/). I have a couple of models that have been incorporated into forms.py, views.py, and urls.py but the redirect is not functioning as expected. The short of it is that I have two forms, when the first form is correctly submitted, it should got to the next form (url). Once that is correctly submitted, it should go to a thank you page. The first form is displayed at http://localhost:8000/packages/new_developer/ and should go to http://localhost:8000/packages/add_package/', but is going to http://localhost:8000/add_package/' instead. Although the information is being captured and placed in the db, I have been unsuccessful at getting a redirect. I have tried changing/removing slashes as well as moving files to different locations -- all to no avail. … -
How to post in a group only if user belongs to that group?
I am creating a social networking website using django I want the user to only able post in the specific group if he/she is the member of that group.