Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I use the same conda environment for different Django projects?
I know that environments are used for backward-compatibility and to create a box where we can download packages without affecting the rest of the computer. I am working on a couple of django projects and I was wondering if I need to create a new conda environment for each new project or can I use the same one? What might go wrong if I use the same environment for similar web-development project? -
Can't Save Data to Database with Django?
Here is my model class Software(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) tbdy = models.DateField(verbose_name='TBDY',blank=True,default=timezone.now()) lab_deneyleri = models.DateField(verbose_name='Labratuvar Deneyleri',blank=True,default=timezone.now()) saha_deneyleri = models.DateField(verbose_name='Saha Deneyleri',blank=True,default=timezone.now()) deprem_analizi = models.DateField(verbose_name='Deprem Analizi',blank=True,default=timezone.now()) soil_improvement = models.DateField(verbose_name='Zemin İyileştirme',blank=True,default=timezone.now()) retaining_structures = models.DateField(verbose_name='İstinat Yapıları',blank=True,default=timezone.now()) class Meta: verbose_name_plural = 'Yazılımlar' and here is my view if payment_status == "success": if len(Software.objects.filter(user=user)) == 0: f = Software(user=user,tbdy = datetime.now()) f.save() purchased_list = Software.objects.get(user=user) package_objects = {"tbdy": purchased_list.tbdy, "lab-deneyleri": purchased_list.lab_deneyleri, "saha_deneyleri": purchased_list.saha_deneyleri, "deprem_analizi": purchased_list.deprem_analizi, "soil_improvement": purchased_list.soil_improvement, "retaining_structures": purchased_list.retaining_structures} for item in item_list: finish_date = datetime.now() + timedelta(days=365) package_objects[item.url_name] = finish_date package_list.save() return render(request,"user/payment.html",payment_request) I'm trying to add some datas to my database, eventhough it doesn't give any error messages when I look at the database I don't see any result. And eventhough there is some data in my database, Software.objects.filter(user=user) gives empty queryset every time I run these codes. What am I doing wrong ? -
I have an error which sayin no encoding declared ;do you understand?
In line 10 of models.py Class master(models.Model): ... -
Howto serialize a property as relationship with json api
I have a model where a property is calculated from a lecacy api. The property is a foreign key to a model which can be retrieved via a legacy api. Now I want to serialize this property as "relationsihp" with django rest json api. The Model looks like: class Tag(models.Model): -
Query to GET x within certain date range in django
I need to get count of users whose deadline are within a certain date range. My Model: class Task_Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) def __str__(self): return self.name class Task(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) deadline = models.DateTimeField() cat_id = models.ForeignKey(Task_Category, on_delete=models.CASCADE) when I hit this url I need to get response in this manner where total is the number of people whose deadline lies between start_date and end_date. Url: /api/task?start_date=2020-03-25&end_date=2020-03-26 Method: GET, Output: - Response Code: 200 - { "total": "123" "results": [{ "user_id": 1 "id": 1, "name": "Science Task 1", "deadline": "2020-03-25T08:12:05" }] } -
Check django Cursor Programming Error and Handle accordingly
I have a code to create a materialized view using Django Cursor. If the view already exists, it gives Programming Error: Relation already exists. I want to handle this case, and check if this error comes, it instead run another query Refresh materialized view But I am unable to check for error message using cursor.statusmessage it gives empty string. Any other way to do this ? -
Optimizing Django Serializer
I have a model that looks something like: class Song(models.Model): composer = models.ForeignKey('Person') performer = models.ForeignKey('Person') backup = models.ForeignKey('Person') class Person(models.Model): name = models.CharField(max_length=1000) ... My problem starts when I try to serialize the Song model like: class SongSerializer(serializers.ModelSerializer): composer = PersonSerializer() performer = PersonSerializer() backup = PersonSerializer() class Meta: fields = ('id', 'composer', 'performer', 'backup') This causes the serializer to run 3 queries, one per foreign key. I want to optimize this into 1 query, but I don't want to change the model structure (combine composer, performer, and backup into a ManyToMany with custom ordering defined by myself). Is there a way to manually combine the queryset in the serializer? -
How can create and save files in Django
I have this Django application that does the following: 1. User login to the application. 2. Have users enter information via forms. 3. My application will then process the information entered and the create a file and save the processed information to the file. The create file should be unique and only related to the user. Is there a to do this where the name of the files are unique? Also, should I store the files in the media folder or create another folder? -
Connect my database to heroku with django
I followed the instruction from https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment and it deployed successfully. However the database is empty. I thought using dj-database-url and psycopy2-binary is suppose to fix this problem. import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) This is just part of the code. (See the whole thing: https://github.com/jchen0114/pokemon_site). I checked and others used python-dotenv but is does not seem to work as well. Is there a thing that I am missing? -
Hello I am new to JavaScript .how should I format my JSON data to standard highcharts format without using php
New to JavaScript how should I format my JSON data to highcharts. -
Django model field is showing in django admin
In my django admin model(Profile), I am not able to see my StudentID field declared in django model. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) StudentID = models.AutoField(primary_key=True, verbose_name='SID') Branch = models.CharField(max_length=255, choices=Departments, default="CSE") YearOfStudy = models.IntegerField(default=1) ContactNumber = PhoneField(help_text='Contact phone number') image = models.ImageField(default='default.jpeg', upload_to='profile_pics', blank=True) parentsContactNumber = PhoneField(help_text="Parent's phone number", blank=True) def __str__(self): return f'{self.user.username} Profile' -
Pycharm says endfor tag has typo when I cant find one
Not too sure why this wouldn't be working I don't see any typo's and everything else is setup correctly. <h1>Med</h1> <ul> {% for med in medicine %} <li> {{ med.name }} </li> {% endfor %} </ul> -
How to get the device width usign Django built-in template tags?
I've been googling about this, there are some tools like Django responsive and Django responsive2 but these package are out of date. Links: Django responsive 2 https://pypi.org/project/django-responsive2/ Django resposnive https://django-responsive.readthedocs.io/en/v0.2.0/Is there any way I'm asking for a built-in template tag, not about how to take the device with and send it to the server. -
In python with django framework upload whole front end for specific portfolio
Example I’m trying to build a website which help people to make their own profile page for example mostly Facebook and Twitter has their own template what if someone comes to my website and upload the whole front end of it and they have their own profile page from top to bottom we can also consider it as portfolio page for be developer? Just want to know is it possible I’m open how or links available thank you!! -
Send async emails in django 3.0
I've seen that django has recently added asynchronous support in version 3.0. However, the docs are not completely clear for me and they do not provide a working example. Is it possible to send an email asynchronously using django.core.mail.send_mail and asgiref.sync.sync_to_async? If so, how would this be accomplished? Thanks beforehand -
django admin panel image field produces wrong path to image
I have an image field that uploads to the media/ directory. In the django admin panel, it links to admin/api/character/2/change/media/image.jpg, instead of media/image.jpg. How do I correct this? -
Pagination with JsonResponse and change some object attributes in View
I'm new in views Django and I'm trying to get JSON data with pagination, also I want to change some of the attributes of my data like created_at give me result like this '2020-03-24T22:49:45.956Z ' and I want the format like that 'Mars 26, 2020' (I know that I can change the format in the template but in my case, I need to change it in view) also I need to change something in content, I'm trying to make a function do that, I know that there is a rest framework who will make the work easier, but I don't think that if I installed a whole framework just for one function is a good idea, that's why I'm trying to make one by myself. My shote: def get_posts(request): # get all posts posts = Post.objects.all() # get current page and how max page of our posts page = request.GET.get('page', 1) pagesCount = math.ceil(posts.count() / 3) # check the param page if is a number if page.isdigit(): currentPage = int(page) else: currentPage = 1 # check if is between 1 ans max page if currentPage > pagesCount: currentPage = pagesCount elif currentPage < 1: currentPage = 1 # get posts … -
Django admin annotation - Sum fields of related models
I've got a django-admin dashboard/listing which attempts to track and summarize "jobs" with an annotated queryset which I think is not working properly. As part of the table, I have displayed calculated fields for data volumes from related objects (as provided by the annotated queryset). Effectively it's a list of jobs which track work against computer devices and their respective storage devices, so a Job can have multiples Devices which can have multiple Storage devices. Both Devices and Storage can contain data volume (in the same way a phone can have internal memory and a removable memory card.) With some jobs a Device might be naked hard drive or a PC tower with 5 HDD, so I am trying to accommodate these scenarios... models.py: class Job(models.Model): ... job_number = models.CharField(max_length=50) job_name = models.CharField(max_length=100) ... class Device(models.Model): ... device_number = models.CharField(max_length=50) job = models.ForeignKey(Job, null=True, on_delete=models.CASCADE) capacity = models.FloatField(null=True) ... class Storage(models.Model): ... storage_number = models.CharField(max_length=50) device = models.ForeignKey(Device, null=True, on_delete=models.CASCADE) capacity = models.FloatField(null=True) ... For the admin model for Job, i've tried the following approach, which seems to work, however when I filter (based on a text search against a job name for example) the totals for the data volume … -
Change image in models - Django
I wonder what is the best way to process images in Django. Personally, I usually use django-resized but I came across some restrictions. I have a Masonry layout in the app. Is there a way to limit the size of my photo, for example, to 600 pixels wide (without cutting the photo on the length, just reduction)? img = ResizedImageField(size=[800, 1200], crop=['middle', 'center']) I mostly use the above code. But then my Masonry system will lose sense (each photo becomes of the same height and length). I found an application like sorl-thumbnail but I did not find such a function to use in my model. If I do it in the template. My user can upload a huge photo that will be charged to the server. I don't see the point in storing extremely large photos. My question is how to resize the image to 700 pixels(example) in my models.py file (without cropping it)? I apologize for my poor English, if will bean something incomprehensible I specifies this. Thank you in advance for each answer. -
Django doesn't load css file
I tried to search many posts about this problem and any one those couldn't solve my problem sadly and I couldn't understand on some points.This is the post. Django cannot find static files. Need a second pair of eyes, I'm going crazy I guess this is the most similar case with me and someone gave very nice answer for it, but it couldn't solve my problem :/ This is my file set beerlog beerlog settings.py ... posting urls.py templates posting base.html index.html post.html posting.html static posting style.css ... static registration ... settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') /posting/templates/posting/base.html <!DOCTYPE html> {% load static %} <html class="no-js"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Beerlog</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="/posting/sytle.css"> {% block extra_head %}{% endblock %} </head> <body> <h2 class='headline'>Welcome to beerlog!</h2> <ul class="sidenav"> {% if user.is_authenticated %} <li>Welcome back {{ user.get_username }}!</li> <li><a href="{% url 'logout' %}?next={{request.path}}">Logout</a></li> {% else %} <li><a href="{% url 'login' %}?next={{request.path}}">Login</a></li> {% endif %} </ul> {% block content %} {% endblock %} /posting/urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views app_name = 'posting' urlpatterns … -
getting database detail value and list of related values
i want to display detail post of related posts. i am using get_object_or_404 to try to get a single value and a list of associated with the categories_pk. The code below does not work? models.py class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Article(models.Model): title = models.CharField(max_length=100) categories = models.ManyToManyField('Category', related_name='article') def __str__(self): return self.title views.py def NewsDetail(request, pk): #single post detail obj = get_object_or_404(Article, pk=pk) # related post list related = Article.objects.filter(categories__pk=obj) context = { 'object': obj, 'related': related } return render(request, 'news/detail.html', context) post_detail.html {{ object.title }} #sigle detail post is working {% for article in related %} #related posts list is not working {{ object.title }} {% endfor %} -
Python Django for loop error in Blog Categories
views.py class PostDetail(DetailView): template_name = "posts/single.html" model = Post context_object_name = "single" def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) context['allCategories'] = Category.objects.all() return context models.py class PostDetail(DetailView): template_name = "posts/single.html" model = Post context_object_name = "single" def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) context['allCategories'] = Category.objects.all() return context single.html <ul> {% for category in allCategories %} <li> <a href="#">{{ category.title }} <span>{{ category.postCount }}</span></a> </li> {% endfor %} </ul> </div> its have to work, but i can't see categories in my blog. And i dont take any warning. Please help.. -
Remove An Unique Item From Shopping-Cart In Django
I am trying to delete an item from the cart and I have some issues to do it. Here is the function: def cart_contents(request): """ Ensures that the cart contents are available when rendering every page """ cart = request.session.get('cart', {}) cart_items = [] total = 0 destination_count = 0 for id, quantity in cart.items(): destination = get_object_or_404(Destinations, pk=id) #remove = request.session.pop('cart', {id}) <<<<<< price = destination.price total += quantity * destination.price destination_count += quantity cart_items.append({'id': id, 'quantity': quantity, 'destination': destination, 'price':price, 'remove':remove}) #cart_item will loop into the cart. return {'cart_items': cart_items, 'total': total, 'destination_count': destination_count} Template.html {% for item in cart_items %} {{ item.remove.id }} {% endfor %} I've added a remove variable remove = request.session.pop('cart', {id}) but if I use it in the code it will first not allow me to add more than one item and when I click the trash-can-button to remove the item it deletes all the cart in the session. The following image has two items in the card based by its id and the quantity as {'id', quantity} = {'2': 1, '3': 2}. -
Django filter on OneToOne field appending "_id" and failing
In my Django application I have the following model: class Provider(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return str(self.user) Note user is a OneToOneField to my CustomUser table and also the primary key of this table. In Views.py, I attempt to query this table with Provider.objects.filter(user=request.user) and get django.db.utils.OperationalError: (1054, "Unknown column 'webatds_provider.user_id' in 'field list'"). Checking my MySql database, I see the columns are (user, company_id). So why is Django adding "_id" to user when I try to filter? -
Setting up ACME challnge for a django app?
I was trying to create SSL certificate using getssl and I ran all the commands successfully untill the command ./getssl mydomain which the output was copying challenge token to /home/ubuntu/myproject/.well-known/acme-challenge/xEMXeTwfM1ukaKVBjugBgBq_Xn98smHdg7BQN5GQMTM getssl: for some reason could not reach mydomain.com/.well-known/acme-challenge/xEMXeTwfM1ukaKVBjugBgBq_Xn98smHdg7BQN5GQMTM - please check it manually and copying challenge token to ssh:myhostname:/home/ubuntu/mtproject/.well-known/acme-challenge/xEMXeTwfM1ukaKVBjugBgBq_Xn98smHdg7BQN5GQMTM getssl: problem copying file to the server using scp. scp /home/ubuntu/.getssl/mydomain.com/tmp/xEMXeTwfM1ukaKVBjugBgBq_Xn98smHdg7BQN5GQMTM ip-172-26-7-149:/home/ubuntu/mtproject/.well-known/acme-challenge/xEMXeTwfM1ukaKVBjugBgBq_Xn98smHdg7BQN5GQMTM how should I set this up when I saw the docs it said # Acme Challenge Location. The first line for the domain, the following ones for each additional domain. # If these start with ssh: then the next variable is assumed to be the hostname and the rest the location. # An ssh key will be needed to provide you with access to the remote server. # Optionally, you can specify a different userid for ssh/scp to use on the remote server before the @ sign. # If left blank, the username on the local server will be used to authenticate against the remote server. # If these start with ftp: then the next variables are ftpuserid:ftppassword:servername:ACL_location # These should be of the form "/path/to/your/website/folder/.well-known/acme-challenge" # where "/path/to/your/website/folder/" is the path, on your web server, to the web …