Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Want to self.request.filter for seperate event calender view for different users who add events to the calnedar
I want to see seperate calendar for my different users how to add filter for the user in calendar for this purpose.I have tried adding request.user in class view but it was not working. Please help me if u can. Advanced thanks to you for trying to solve my query my utils.py which is providing me calendar class view .---- from datetime import datetime, timedelta from calendar import HTMLCalendar from .models import Event class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(date__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td> <span class='date'> {day} </span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Event.objects.filter(date__year=self.year, date__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): … -
How does Watch2geather & Netflix Party work
So i want to make a application like Watch2geather its a web app that lets people watch a video together online from anywhere in the world. but i don't know how exactly does it work. what exactly happens in backend and what are the skills that i need to learn before i can execute something like this. please recommend if there are any courses. i have tried googling but i think the keywords i used were wrong so i got nothing { } Best Regards, Atomik -
How to send the dynamically added values to another url in Django
I have a HTML page with two dropdowns and a button.The values in second dropdown are populated based on the value selected in first dropdown. When I click on the button, it navigates to a different url with the same form and some additional information.How can I populate the dropdown values there too? -
Django - Find position of a record in a filtered list
I have a Django app in which I have a DetailView Page. I also have a ListView which is paginated and also has a created by filter (only author can see the records added by herself). I want to pull a position in ListView of the record being displayed in DetailView. I tried following position = BankAcType.objects.filter(author=self.request.user).order_by('-created_date').count() But it gives total number of records and not the position of the particular record in the ListView. -
Pass variable using class view in django
Directly how can I pass the context in the same time inside the class to my html pages? the class is an updateView but I need the context in the page too: class GL_PRUP(UserPassesTestMixin, LoginRequiredMixin, UpdateView): model = Gas_liftM template_name = 'Home/WELLINFO/W_lift/GL_liftUPARMTS.html' form_class = Gas_liftFORM def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): WeelN = self.get_object() GLParameters = Wcomlption.objects.filter(WellID__exact=WeelN)[0] print(GLParameters) context={'GLParameters': GLParameters,} # need to pass this variable to my html page? if self.request.user== WeelN.author: return (True, context) else: return False Every thing works fine in the update html page but only can't get the GLParameters?? {% if GLParameters %} {{ GLParameters.WellID }} it works Tyaeb {{ GLParameters.Mndrn2 }} {% else %} nothing passes and happens {% endif %} Thank you in advance -
How should i auto fill a field and make it readonly in django?
I`m new to django and i was doing a test for my knowledge. Found a lot of duplicates in here and web but nothing useful I'm trying to make a ForeignKey field which gets filled due to the other fields that user fills, and make it unchangeable for the user. I thought that I should use overriding save() method but couldn't figure that at all. How should I do that auto-fill and read-only thing? -
Navigating to corresponding ForeignKey object in Django template when model has more than one ForeignKey
I have been around this for a long time and I am not sure I'm taking the correct approach. Not sure if its a problem with model design or something else. Here is my current code: The models: from django.contrib.auth.models import User class Card(models.Model): name = models.CharField(max_length=100) # ... class Collection(models.Model): name = models.CharField(max_length=50) cards = models.ManyToManyField(Card, related_name='collections', blank=True) user = models.ForeignKey(User, related_name='collections', on_delete=models.CASCADE, null=True) # ... class UserCard(models.Model): user = models.ForeignKey(User, related_name='card_settings', on_delete=models.CASCADE) card = models.ForeignKey(Card, related_name='user_settings', on_delete=models.CASCADE) amount = models.PositiveIntegerField(default=1) # ... The view: def collection(request, pk): collection = get_object_or_404(Collection, pk=pk) cards = collection.cards.all() context = { 'collection': collection, 'cards': cards, } return render(request, 'website/collection.html', context) The template: {% for card in cards %} {{ card.name }} | {{ card.something_else }} | {{ card.user_settings.amount }} {% endfor %} In the template I am looping the card objects that I get from the view and building a table. The problem is on the last item. I need to navigate to the UserCard model to get the amount. I would do it by doing card.user_settings.amount. However since many users can have UserCard objects for this card, I get a queryset. How do I get only the UserCard for the corresponding … -
cant upload multiple images from react to Django rest framework
I can successfully upload images from react to Django rest when using file[0] but after removing [0] i can receive the uploaded message in Django but image is not recieving. react.js import React, { Component } from 'react'; import axios from 'axios' import './App.css'; import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'; class Design extends Component { state = { file: null } handleFile(e) { let file = e.target.files[0] <------ this is what im talking about, if i remove index [0] then django receives success message but not image. this.setState({ file: file }) } handleUpload() { let file = this.state.file let formdata = new FormData() formdata.append('image', file) axios({ url: "http://127.0.0.1:8000/arizonaimg/", method: "POST", data: formdata, } ).then(res => console.log(res)) } render() { return ( <div class="upload"> <h1>Upload Images</h1> <br /> <br /> <Link to="/"> <button class="btn btn-warning">Back</button> </Link> <br /> <br /> <br /> <div className="d-flex p-4 z-depth-2"> <input type="file" multiple name="file" onChange={(e) => this.handleFile(e)} /> </div> <br /> <br /> <br /> <button onClick={(e) => this.handleUpload(e)} class="btn btn-red">Upload</button> </div> ); } } export default Design; models.py from django.db import models from django.contrib.auth.models import User class Task(models.Model): title = models.CharField(max_length=100, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def save(self, *args, … -
Django - How to redirect to the same index page when clicked on Logo?
I have used static for all the js/css/images path. However, click on the logo redirects me to http://127.0.0.1:8000/static/index.html without any css/js/images. The same works well all other paths in the page(eg: http://127.0.0.1:8000/static/about.html) Sharing my urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, "index.html") Please help Screenshot here -
How can I edit a Django model object on the front-end if I passed it in through my views.py file?
For some context, I am creating a videogame on the web that needs a backend to store player names and record their score. Since I am quite comfortable with Python, I used the Django framework for my backend. The problem I encounter, however, is that I do not know how to edit the instance of the player model object I am passing into my HTML file via my views.py file to store/update its score. Here is the relevant function for my views.py file: ` def homepageview(request): form = PlayerForm(request.POST or None) if form.is_valid(): player = form.cleaned_data form.save() form = PlayerForm() for object in PlayerInfo.objects.all(): if object.name == player.get('name'): player = object break # I am looping through because there may be multiple people on the webpage playing the game so the current player isn't necessarily the most recent player context = { 'player':player } return render(request,'gamescreen/game.html',context) #once the form is valid, you can now actually play the game context = { 'form':form, } return render(request,'gamescreen/homepage.html',context) ` Here is the relevant portion of my 'gamescreen/game.html' file: <script> let player = "{{ player }}";//this is the player object passed in from views.py class Engine{ constructor(gameWidth,gameHeight){ this.gameWidth = gameWidth; this.gameHeight = gameHeight; } … -
Django Post shows with HTML tags
I have created a small blog that includes django-tinymce in model.py file. After I write a text in the Admin console and publish it, the text is shown with HTML tags. Please see the example bellow: This is my model.py file: from django.conf import settings from django.db import models from django.utils import timezone from tinymce.models import HTMLField class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) text = HTMLField() def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title I can't find any reason why it is happening. I followed the documentation and should get a text without any tags. -
django join three table
Please, someone help me. i'm new to django. i have 3 table (products, product_images, product_prices) and product_images.product_id==products.id && product_prices.product_id==products.id. I want to join three tables using products.id. I've searched a lot, to solve my problem but failed. sorry my poor english. here is my code... models.py class ProductImage(models.Model): id = models.BigAutoField(primary_key=True) product_id = models.BigIntegerField(unique=True) product_image = models.CharField(max_length=250, blank=True, null=True) class Meta: managed = False db_table = 'product_images' class ProductPrice(models.Model): id = models.BigAutoField(primary_key=True) product_id = models.BigIntegerField(unique=True) market_price = models.FloatField() sale_price = models.FloatField() class Meta: managed = False db_table = 'product_prices' class Product(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=255) brand = models.CharField(max_length=100) origin = models.CharField(max_length=100) images = models.ForeignKey(ProductImage, on_delete=models.SET_NULL, to_field='product_id', null=True, blank=True) prices = models.ForeignKey(ProductPrice, on_delete=models.SET_NULL, to_field='product_id', null=True, blank=True) class Meta: managed = False db_table = 'products' views.py @api_view(('GET',)) def get_products(request): products = Product.objects.select_related().values_list('title', 'images__product_image', 'prices__market_price') return HttpResponse(products.query) unexpected output SELECT `products`.`title`, `product_images`.`product_image`, `product_prices`.`market_price` FROM `products` LEFT OUTER JOIN `product_images` ON (SELECT `products`.`title`, `product_images`.`product_image`, `product_prices`.`market_price` FROM `products` LEFT OUTER JOIN `product_images` ON (`products`.`images_id` = `product_images`.`product_id`) LEFT OUTER JOIN `product_prices` ON (`products`.`prices_id` = `product_prices`.`product_id`) = `product_images`.`product_id`) LEFT OUTER JOIN `product_prices` ON (`products`.`prices_id` = `product_prices`.`product_id`) i want to replace products.images_id to products.id and products.prices_id to products.id thanks in advance -
Django Models Foreign Key get attributes
there are two classes in Models.py. First class creates the directory for the second class which upload image to that directory. The problem is that Image.image upload_to should take Image.directory.directory. Is there any solutions? class Directory(models.Model): directory = models.CharField('Name of the folder', max_length=50) def __str__(self): return self.directory class Image(models.Model): directory = models.ForeignKey(Directory, on_delete=models.CASCADE) image = models.ImageField(upload_to='app/{}'.format(directory)) Thanks for your attention!!! -
OperationalError at /admin/weather/comment/ no such column: weather_comment.author_id
i am trying to add comments, and i have OperationalError at /admin/weather/comment/ no such column: weather_comment.author_id My models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField(max_length=250) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('post_details', kwargs={'pk': self.pk}) def __str__(self): return f'{self.author} {self.title}' class Comment(models.Model): text = models.TextField(max_length=200) date_commented = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.PROTECT) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.text -
Is Django completely written in python or do you need to know other programming languages?
Does Django require more than just knowledge of Python? Is it a mix between several programming languages. Thanks -
Filter- model's query set based on the match from another model's ManyToMany fields
I have this problem, where I want to list Projects that the Applicant is only capable of; I have models as this>> class Project(models.Model): project_title= models.CharField(max_length=100) categories = models.ManyToManyField('ProjectCategory') class Applicant(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) full_name = models.CharField(max_length=50, null=True, blank=True) categories = models.ManyToManyField('ProjectCategory') class ProjectCategory(models.Model): category = models.CharField(max_length=50) The Applicants have categories field to specify what he/she is capable of; let's say one chooses "python" and "Django. Also two projects are created where>> 1st Project: (project_title: Need a Django Developer)[on categories field: requires "python" & 'Django'] 2nd Project: project_title:Need Developer [on categories field: requires "python" & 'Django' & 'Django-Rest'] How can I make Queryset where I can display only 1st Project which the applicant is only capable of or interested in? -
Slider using dynamic data
I am trying to have an slider using dynamic data on django which is supposed to slide throw users like in tinder. I am very new to javascript so I dont really know how would the js code end up being, How can I make this work? Please this is very important html <div class="mates-grid-1-1-content"> <div class="mates-grid-2-content"> prev </div> <div class="mates-grid-1-content"> <div class="mates-item-content"> <img class="mate-pic" src="{{ user.profile.profile_pic.url }}" > </div> <div class="mates-item-content"> <a href="{% url 'profile' username=content.user.username %}" style="float: left">{{ content.user }}</a> </div> <div class="mates-item-content"> <div class="responses"> <div class="response-item-img"> <img class="mates-image" src="{{ content.req_image.url }}" width="400px"> </div> <div class="response-item-bio"> <p>{{ content.req_bio }}</p> </div> <div class="response-item-button"> <button type="submit">Submit</button> </div> </div> </div> </div> <div class="mates-grid-3-content"> next </div> </div> -
NoReverseMatch at /admin/ when add custom url
I'm using django3 when I add URL to admin URL get an error by added slash before addition URL get_urls inside the model admin def get_urls(self): urls = super().get_urls() custom_urls = [ path('<int:course>/chapters/', self.admin_site.admin_view(self.CourseChapters)) ] return custom_urls + urls in settings.py APPEND_SLASH=True error says Reverse for '/admin/app_name/model_name//export' not found. '/admin/dern_app/activity//export' is not a valid view function or pattern name. -
Instantiating and/or prefilling django model forms
I am building my first Django application, a 'simple' web-based withdrawal and deposit system. A user's items are stored in an "Items" class: (models.py) class Item(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) stock = models.IntegerField() def __str__(self): return self.title Each "Cart" item is stored as an "OrderItem": (models.py) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) def __str__(self): return self.item.title To add items to their cart, users will go to a page that displays all of their items in forms, which they can fill and click the "Add to cart button" to create that OrderItem. (forms.py) class OrderItemForm(ModelForm): class Meta: model = OrderItem fields = ["quantity", "item"] The problem that I am having with this approach is that I need many OrderItem forms, with their "item" variable prefilled OR somehow instantiating said value. In other words, I don't want the approach Django provides by default with a dropdown, i need each of those dropdown items rendered as separate forms. (storage.html) <div class="row"> <div class="col-md-9"> <div class="row"> {% for i in items %} <div class="card"> <img src="static 'demo/logo.png" class="card-img-top"> <h5 class="card-title ml-2">{{i}}</h5> <form class="form-inline" method="POST"> {% csrf_token %} <div class="form-group ml-2 mb-2"> {{form.quantity}} <input type="submit" class="btn" value="Add to Cart"> … -
Error in Django celery beat with docker compose
I have dockerized django and using celery beat for periodic functions but i am getting following error when i try to run the celery service. I removed celerybeat-schedule file too. celery-beat_1 | [2020-06-30 16:18:43,213: WARNING/MainProcess] return mod.open(file, flag, mode) celery-beat_1 | [2020-06-30 16:18:43,214: WARNING/MainProcess] _gdbm celery-beat_1 | [2020-06-30 16:18:43,215: WARNING/MainProcess] . celery-beat_1 | [2020-06-30 16:18:43,216: WARNING/MainProcess] error celery-beat_1 | [2020-06-30 16:18:43,217: WARNING/MainProcess] : celery-beat_1 | [2020-06-30 16:18:43,218: WARNING/MainProcess] [Errno 22] Invalid argument: 'celerybeat-schedule' Following is my docker-compose.yml file. I am using multiple container, separate for web, celery and celery beat. I am using rabbitmq. version: '3' services: web: build: . entrypoint: ./entrypoint.sh volumes: - .:/code ports: - "8000:8000" networks: - backend depends_on: - db environment: wait_hosts: db:5434 POSTGRES_DB: ${POSTGRES_DATABASE} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_USER: ${POSTGRES_USER} DJANGO_SECRET_KEY: ${DJANGO_SECRET_KEY} db: image: postgres environment: POSTGRES_DB: ${POSTGRES_DATABASE} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_USER: ${POSTGRES_USER} networks: - backend volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "5434:5432" celery: build: . command: celery -A basehrs worker -l info restart: on-failure environment: wait_hosts: db:5432 volumes: - .:/code depends_on: - db - rabbit - web celery-beat: build: . command: celery -A basehrs beat -l info restart: on-failure environment: wait_hosts: db:5432 volumes: - .:/code depends_on: - db - rabbit - web rabbit: image: "rabbitmq:3-management" hostname: "rabbit1" restart: … -
Determining best location for Exception Handling
This is more of an architecture question. I am moving some of my repeated code into a SendNotificationsMixin which can be reused across different views. Obviously this Mixin will handle sending different types of notifications. Since it will be used in several different types of views, they will not all have the exact same processes (but mostly similar). To give an example of what I mean I will first show my SendNotificationsMixin: class SendNotificationsMixin: ... # other methods here ... def send_notifications(self, form, reason_for_notification): groups = form.cleaned_data['receiver'] for group in groups: for receiver in list(Employee.objects.filter(role=group)): if receiver.is_active: try: form.instance.unviewed.add(receiver) except AttributeError: pass if form.cleaned_data['send_notifications']: url = str(self.request.tenant.get_primary_domain().domain) + str( form.instance.get_absolute_url()) self.send_sms(receiver, url, reason_for_notification) self.send_email(receiver, url, reason_for_notification) In the send_notifications method I have this bit of code which keeps track of who has visited the page, but this isn't done in every view therefore I had to add exception handling: if receiver.is_active: try: form.instance.unviewed.add(receiver) except AttributeError: pass First, from a design standpoint, and without being to objective, is this the correct place for the exception handling? If I add a few more of these then it would end up being quite a few try except statements which doesn't seem correct to … -
Model constraint limit
A unique constraint is able to constraint two columns to be unique on a table. Is it possible to allow upto N equal entries on a table instead of just one? Example 1 (Allows only one post per day) class Meta: constraints = [ UniqueConstraint(fields=['post', 'date'], name='posts_unique_date'), ] Example 2 (Allows upto 5 posts per day) NOT A REAL SOLUTION class Meta: constraints = [ UniqueConstraint(fields=['post', 'date'], name='posts_limit_date', limit=5), ] -
if statement return false and django redirect me
i have views.py like this: def delete(request,slug): if request.user.is_authenticated: if request.user == Project.objects.filter(owner=request.user): return render(request,'site/delete.html') else: return redirect('project:home') else: return redirect('project:home') myquestion is when i open this url (/delete/<slug:slug>) django redirects me. Is my if true? if request.user == Project.objects.filter(owner=request.user): return render(request,'site/delete.html') else: return redirect('project:home') Note: owner must be number => owner=request.user => in my example owner was 1 | request.user means 1, why is myif not true?what should i do to fix it? -
How can I combine two fields in a django form for displaying in forms.py
I'm trying to use a ModelChoiceField to populate my dropdown list with choices from a model. In the model I am referencing, I have a last_name field, and a first_name field. I would like to combine them as a meta 'full_name' field to display in the select dropdown box. I added the following property to my model: @property def full_name(self): return '{0} {1}'.format(self.first_name, self.last_name) This works with django-tables2 and allows me to reference as though I had a full_name field. I was also able to get this somewhat working with Django forms when using a Form as opposed to a ModelForm, however I ran into problems with the save method. Every answer I could find said to just use a ModelForm, so I am back to trying to find a solution using ModelForm. When I try to reference 'full_name' as a field in my forms.py, it says that it does not exist. Is there a way I can reference full_name or alternatively combine the first_name and last_name fields for displaying in the ModelChoiceField? -
Foreign key not being returned in sqlite3 db Django
I created a model form that saves a 'note' using a few different fields like title, and creation date. The owner of the form is the user who is currently logged in. At the moment when I am logged in and enter the data into the form, the data is being saved, which I checked in sqlite3 using select * from notes_note; This returns each form entry, and returns the primary key for each, but the foreign key (for the different users) is not being displayed. I tried running PRAGMA foreign_keys = ON; and PRAGMA foreign_keys = 1; but this didn't work. Where can I next look? Not sure what code to post here as I don't know where to start looking for the problem.