Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which method is the most efficient and fast for Tag functionality, using content types or using manytomany field for diff apps in a django project?
Hello guys I have a doubt regarding having to implement Tag functionality. I have 3 apps, I need to add tags to the models in all those apps. Are there performance issues in using content types when the database gets populated ? or is it better to use manytomanyfield for every model in terms of performance and speed? Thanks -
How do I create dynamic detail pagea for my products in my Django e-commerce website?
I am in the process of creating an e-commerce website. My goal is to have individual detail pages for all the products listed on my website. Ideally, I want to do this dynamically using a slug field, which I have already migrated. I am relatively new to Django and would really appreciate it if someone could assist me. -
Bitbucket cloning into Linux server
I have read: BitBucket: Host key verification failed and Jenkins Host key verification failed and several other links provided. I seem to find myself in an odd situation. I want to clone my django repo into a digital ocean droplet. I am following the steps of this document. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 . Everything seems to have gone well, until the step where I need to create the django project. I already have a django project and thus don't want to create a new project on the server. I only need to clone it onto the server. I ran : root@ubuntu-s-1vcpu-2gb-xxx:~#rsync --archive --chown=llewellyn:llewellyn ~/.ssh /home/llewellyn My bitbucket has the id_rsa SSH key uploaded and it all worked in the past, no new SSH has been generated. And the repo is set to public. When running: (myprojectenv) llewellyn@ubuntu-s-1vcpu-2gb-xxx:~/myprojectdir$ git clone git@bitbucket.org:LlewellynHattinghLH/repo.git Cloning into 'repo'... Warning: Permanently added the RSA host key for IP address '18.205.xx.x' to the list of known hosts. git@bitbucket.org: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. I have tried several articles, but most only tell me how to create a new SSH. Any help would … -
Django Adding User details to a UserPost List View
I have a UserPost List View which is a view for a specific user's posts. I am looping the posts of this specific user but I want to add this user's profile details like profile image and other details like email. So, I am not sure on how to add the user details of the user's post names as designer not the logged-in user. I can add the user/designer details in every looped post but I don't want it to be repeated with every post I just want it to appear once just like {{ view.kwargs.username }} as this page is realted only to this user/designer Here is the models.py class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post") title = models.CharField(max_length=100, unique=True) here is the profile model related to every user class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email'] here is the views for the userpostlist which is filtered by a specific user/designer not the logged in user class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 6 def get_queryset(self): … -
Why does Django template block/include include external <table> tag?
Consider the below code: <table id='table1'> {% if model_name == 'TransactionsTable' %} {% block transactions_create %} {% include "snippets/transactions_create_and_update.html" with form=form %} {% endblock transactions_create %} {% endif %} </table> I have another <table>, 'table2', within transactions_create_and_update.html. Table2 was appearing outside of it's parent element. So after some testing I tried closing table1 early (first line): <table id='table1'></table> {% if model_name == 'TransactionsTable' %} {% block transactions_create %} {% include "snippets/transactions_create_and_update.html" with form=form %} {% endblock transactions_create %} {% endif %} Then table2 behaves as expected. So table1 is kind of included in the include/block inheritance - but the template doesn't seem to know that I close it after. From the docs - think this is part of the answer but I don't know what to do with it: The include tag should be considered as an implementation of “render this subtemplate and include the HTML”, not as “parse this subtemplate and include its contents as if it were part of the parent”. This means that there is no shared state between included templates – each include is a completely independent rendering process. Blocks are evaluated before they are included. This means that a template that includes blocks from another … -
How to get the values of a div by pressing a button in django
good afternoon, I come to ask a question. I have an online ordering website, I have all my products displayed on the web next to a button to add product (to the basket) The point is, I don't know how to get the data after clicking the button. Models.py (Cart): from django.db import models # Create your models here. class Cart(models.Model): titulo = models.CharField(max_length=100) precio = models.FloatField(default=0) unidades = models.IntegerField(default=0) imagen = models.ImageField(default="null", blank=True) slug_cart = models.CharField(verbose_name="Vinculo", max_length=100) usuario = models.CharField(max_length=99) creado_el = models.DateField(auto_now_add=True) actualizado_el = models.DateField(auto_now=True) class Meta: verbose_name = "Cesta" verbose_name_plural = "Cestas" def __str__(self): return self.titulo Models.py(Food): from django.db import models from ckeditor.fields import RichTextField # Create your models here. class Food(models.Model): titulo = models.CharField(max_length=100) descripcion = RichTextField() precio = models.FloatField(default=0) unidades = models.IntegerField(default=0, blank=True) publico = models.BooleanField(verbose_name="¿Publico?") imagen = models.ImageField(default="null", upload_to="foods") slug_food = models.CharField(verbose_name="Vinculo", max_length=100) creado_el = models.DateField(auto_now_add=True) actualizado_el = models.DateField(auto_now=True) class Meta: verbose_name = "Comida" verbose_name_plural = "Comidas" def __str__(self): return self.titulo views.py (Cart-app): def anadir_cesta(request): username=None if request.user.is_authenticated: username = request.user.username cesta = Cart( titulo = titulo, precio = precio, unidades = unidades, imagen = imagen ) cesta.save() HTML pages with Food: {% extends 'layouts/layout.html' %} {% block titulo %} {{page.titulo}} {% endblock titulo … -
Django compute score of matches (workaround to annotate a query after a union)
I need to compute the ranking of athletes during boxing tournaments. In my models, I track the result of each match and the points to be attributed for each outcome to each athlete. class Member(models.Model): surname = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class Tournament(models.Model): name = models.CharField(max_length=200) class TrophyRule(models.Model): win = models.IntegerField() loose = models.IntegerField() draw = models.IntegerField() class Ring(models.Model): code = models.CharFieldmax_length=1) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) class Match(models.Model): ring = models.ForeignKey(Ring, null=True, on_delete=models.SET_NULL) winner = models.CharField(max_length=20, null=True, blank=True) trophy_rule = models.ForeignKey(TrophyRule, on_delete=models.SET_NULL, null=True) red_member = models.ForeignKey(Member, related_name='reds', on_delete=models.SET_NULL, null=True) red_count_ranking = models.BooleanField(default=True) blue_member = models.ForeignKey(Member, related_name='blues', on_delete=models.SET_NULL, null=True) blue_count_ranking = models.BooleanField(default=True) Based on this model, I need to sum the points acquired when the athlete was in the red corner with the points acquired when the athlete was in the blue corner. The result should be a queryset with all members and their total number of points. In order to achieve this, I started with the computation of the points acquired by the athletes in the red corner: from apps.members.models import Member from django.db.models import Case, Sum, When, Q red = Member.objects.filter(reds__ring__tournament_id=11402).annotate( points=Case( When(Q(reds__winner='red') & Q(reds__red_count_ranking=True), then='reds__trophy_rule__win'), When(Q(reds__winner='draw') & Q(reds__red_count_ranking=True), then='reds__trophy_rule__draw'), When(Q(reds__winner='blue') & Q(reds__red_count_ranking=True), then='reds__trophy_rule__loose'), ), ) I also did … -
Django - Retrieve a field for split operation from sorted chain list
How can I access or retrieve a field for a split operation from a sorted chain in Django? Assuming the following example where each of the mentioned models has a field called "tag"? def post_list(request): list_posts = sorted( chain( Model1.objects.all(), Model2.objects.all(), Model3.objects.all(), ), key=attrgetter('published_date'), reverse=True ) tags = list_posts.tag.split(", ") [-> Cannot retrieve .tag here] .... args = {'posts': posts, 'tags': tags } return render(request, 'post_list.html', args) Each tag field is basically just a CharField / Single String where words are separated using ", " and now its required to split this up to show tags at my template, any idea? Kind regards -
how to serialize time with timezone in django-rest-framework's serializer?
I have a Django model: class Clinic(models.Model): NAME_MAX_LENGTH = 150 name = models.CharField(max_length=NAME_MAX_LENGTH,blank=False,null=False) start_at = models.DateTimeField(blank=False,default=timezone.now) the client sends the start_at field as a time field with timezone like { start_at : "12:40:10+04:30" } I want to convert this time field into the DateTimeField with the current date as the date and then save it into the database as a timezone-aware DateTimeField. I want to serialize this field and extract timezone info from the input and then create my DateTimeField object. How can I do this in rest_framework serializer? -
Add function when getting queryset django
In my view I get the popular articles by this variable: popular_article_list = Article.objects.order_by('-votes')[:5] Now in my model I have a was_published_recently function that looks like this: def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now So how do I combine the two to get the most popular articles in the last 24 hours? -
Accessing Twilio Usage API response in Django and Python
I am trying to access the Twilio usage records API (https://www.twilio.com/docs/usage/api/usage-record) using the below: account_sid = "" auth_token = "" client = Client(account_sid, auth_token) # A list of record objects with the properties described above records = client.usage.records.daily.list( category="sms", start_date="2020-08-22", end_date="2020-08-22" ) I can't seem to me able to reference the data. If I return the above to a Django template I get the following: [<Twilio.Api.V2010.DailyInstance>] How would I actually access the data in the response e.g. "price" -
if statmen not working well in django please help me
I'm trying to print specific output if the data equal to 1 but it's not working! it's printing the picture in the other if -
Django, Jinja -- Dynamically Reference Static Images from using an object attribute (slug)
Forgive my asking of what might be the wrong question, it's my second day of Django. I've got a model in the database, and the model has the following attributes: 'title': 'Entity title for Entity A', 'slug': 'entity-a', '...': '...' In my .html Jinja template, I want to load multiple entities using a loop. Which works. However, I want to reference some static loaded logo using the entity.slug. Like so... {% for entity in entities %} {{ entity.slug }} <img src="{% static 'logos/{{entity.slug}}_50x50.png' %}" alt="" class="mr-2 img-thumbnail" width="50"> {% endfor %} See inside IMG tags. Where I have {{entity.slug}}. How can I put it in so the static images will load dynamically? Atm, it's rendering the {{}} see here -
Relationship between models in models.py?
I want to make a Django ecommerce website, in models.py. I have 6 models: Order,OrderItem,Item,ShippingAddress,Payment and Coupon but i don't know which relationship to use between these models. -
How to pass a user variable saved in forms to a button link in Django
I'm trying to get a user to enter the IP address, and then return the user this IP address with port attached as a button that can be clicked by this user and take him to given website ( a part of bigger project ). I have the IP address saved, but when I'm trying to pass it, I'm getting errors. views.py: @login_required def home(request): if request.method == 'POST': form = ConnectionForm(request.POST) if form.is_valid(): form.save() home.ip = form.cleaned_data['ip'] home.username = form.cleaned_data['username'] home.password = form.cleaned_data['password'] return redirect('deploy_honeypot') else: form = ConnectionForm() return render(request, 'home.html', {'form': form}) and in template: <td><a href="{{ url 'home.ip' }}">Your Website</a></td> -
Hi, I m learning the djano, py -Pands - The below code is working fine in python, how to pass parameter values from html
import pandas as pd import pandas_profiling read the file df = pd.read_csv('Dataprofile.csv') run the profile report profile = df.profile_report(title='Pandas Profiling Report') save the report as html file profile.to_file(output_file="pandas_profiling1.html") save the report as json file profile.to_file(output_file="pandas_profiling2.json") -
Django UUIDField docs say can be serialised but migrations mark it `serialize-False`
What causes Django's UUIDField type to be marked serialize=False? How can I specify that it should be True? The documentation for database migrations, under “Serializing values”, explicitly states that uuid.UUID instances can be serialised: Django can serialize the following: […] uuid.UUID instances That sounds good to me. So I define a model with a UUIDField primary key: import uuid from django.db import models class Lorem(models.Model): id = models.UUIDField( verbose_name='ID', default=uuid.uuid4, editable=False, serialize=True, primary_key=True) dolor = models.CharField([…]) Despite specifying serialize=True explicitly, the makemigrations management command produces this field, where all the arguments are the same except it has changed to serialize=False: […] migrations.CreateModel( name='Lorem', fields=[ ('id', models.UUIDField([…], primary_key=True, serialize=False, verbose_name='ID')), ('dolor', models.CharField([…])), ], ) […] What is causing the makemigrations command to insist that the UUIDField should not be serialized? How can I get it to work the way the documentation for “Seralizing values” describes, and serialize=True? -
Django filter liked Posts by User
Post model class Post(models.Model): likes = models.ManyToManyField(User, related_name="liked_by", blank=True) I am trying to query all posts that are liked by a particular user but I couldn't find the right __ query for it. This is the query I'm trying to make. Post.objects.filter(likes__liked_by=User.objects.get(pk=1)) How can I achieve that? -
What is the correct format for adding extra parameters in action decorator?
I'm trying to pass an extra parameter to my custom ModelViewSet method: urls.py: router.register(r'mail_template', MailTemplateViewSet) view: @action(detail=False, methods=['GET'], url_path='get_template/(?P<slug>[\w-]+)') def get_template(self, request, slug=None): I also tried: @action(detail=False, methods=['GET'], url_path='mail_template/get_template/(?P<slug>[\w-]+)') @action(detail=False, methods=['GET'], url_path='dashboard/mail_template/get_template/(?P<slug>[\w-]+)') test call: self.client.get('/dashboard/mail_template/get_template/test-template') However, the path to get_template is not being found. If I remove the 'url_path', I can reach the method. Am I formatting the url_path correctly? -
I have an issue with the changeStock method of a Product class in views.py in Django
I am doing a Product class in Django for fun and I have ran into a problem regarding changing the Product's (the model name) regarding its variable qtyOnHand, which is used to check to see how much of that product is in stock. The goal is to change the product's qtyOnHand by a specified amount using the changeStock method and redirect to the home page where the updated qtyOnHand will be stored. The amount can be negative if taking out stock, and +ve if receiving stock. The error I got when typing in the URL http://127.0.0.1:8000/products/1/changeStock/2 is unsupported operand types for +: int and str, which was Here's my code for the changeStock method in the views.py. The comments there are to guide my approach to the problem. Change the stock of a specific product by the specified amount. A -ve number means that you are taking out product, while a +ve one means you are receiving that product. def changeStock(request, pk, amount): # We need the id of a specific product, plus we have to check if it's not found. product = get_object_or_404(Product, pk=pk) # Then we have to update its qtyOnHand. product.qtyOnHand = product.qtyOnHand + amount -> error … -
Trying to deploy Django on SiteGround
I am trying to deploy a Django app on Siteground through SSH. I have transferred all the files through Filezilla. Every thing is setup. I have developed several apps on AWS using ubuntu. But in siteground Fedora OS is provided in SSH, I am not familiar with that much. I can't have superuser privileges. Running my Django server on port 8000: python manage.py runserver 0.0.0.0:8000 Host name is already added in ALLOWED_HOST of setting.py: ALLOWED_HOSTS = ["himeshp7.sg-host.com","*"] Server is running in SSH, but I am unable to open my web app on browser. In AWS we get option to enable ports in Security Groups, but I couldn't find anything like that on Siteground, I also talked with customer care but they are telling to upgrade, I still doubt that if it will work or not after that as I couldn't find anything proper for deploying Django on Siteground. -
How to deploy Django REST framework on Windows server
What's a good/easy way to deploy a Django REST project on Windows server (2019)? I've been searching for a guide but can't seem to find anything on REST, just regular Django. Nginx and Waitress seems like the way to go for Django but there's no project.wsgi in a DRF project so I get stuck there. Could anyone steer me in the right direction? -
How to save equations and formulas in Django Database?
Working on a Project I need to save different articles which contains formulas and equations, Django core models support TextField which does not seems to save equations, they are all stored as plain text. I also tried adding CKEDITOR to my project but no chances on that too. so the question is : How can I save texts containing formulas and equations in my SQLite DB? -
Getting error while reloading webapp in pythonanywhere
I am trying to write my first django app on pythonanywhere with the help of django documentation(Part 1). All the things are successful until I try to add a new file named urls.py as mentioned in Documentation, I can't reload my webapp after that..I am getting following error: "Your webapp took a long time to reload. It probably reloaded, but we were unable to check it". There is no error in my code as I have checked through this command "python3 manage.py check". As a beginner, Any help would be appreciated. I am also following the tutorial "Django for everybody" on coursera and followed the instructor step by step, But I can't get rid of this error -
Django: can't optimize N+1 with image.url field
I'm trying to optimize a Django app. I iterate over and join some related info in a json I'll send to the template. I already know about select_related or prefetch_related, but when you try to get the url of an image field it seems to query again because url is not actually a value in the model but a property. This makes my view too slow because I need many images. How can I avoid this pseudo N+1 problem? Example model Obvioulsy this is not all my real code, but I just want to illustrate the process. class example_model(models.Model): name = models.CharField(max_length=200, help_text="", blank=True, null=True) logo = models.ImageField(upload_to='', default="", blank=True, null=True) def __str__(self): return str(self.name) View result_list = [] for x in example_model: result_list.append({'name': x.name, 'image': x.logo.url})