Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Through relationship using polymorphic model
I'm trying to use a through relationship between a polymorphic and a non-polymorphic table with the the RankedAthlete model: class ChoiceBlank(PolymorphicModel): pass class ChoiceAthlete(ChoiceBlank): choice = models.ForeignKey('SomeModel', on_delete=models.CASCADE) class BetMultiple(models.Model): answer = models.ManyToManyField('ChoiceBlank', blank=True, through='RankedAthlete') class RankedAthlete(models.Model): choiceAthlete = models.ForeignKey('ChoiceBlank', on_delete=models.CASCADE) bet = models.ForeignKey('BetMultiple', on_delete=models.CASCADE) rank = models.IntegerField() This doesn't work because RankedAthlete expects a ChoiceBlank and a ValueError is raised when I create one. Conversely, I can't migrate my db if I replace choice with a ChoiceAthlete. Django-polymorphic doc doesn't mention my use case, is it unsupported? Is there a way to make this work? -
Best practices for long running tasks in django
I am developing web app on django. One of the problem that I encounter, is long running tasks, that can execute during weeks or more. I am talking about Campaign entity. User creates one, launch and can wait and see intermidiate results. What is the best practise to implement such tasks in django. One of the options that I could find is celery and rabbitmq. -
Django: display many to many relationship through a model in themplate
I have this ManyToMany relationship through an intermediary model: class Group(models.Model): members = models.ManyToManyField(Student, through='NamedMembershipClub') class Membership(models.Model): year = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) I'm trying to display members with the year they joined in my template. I read on this post that I should use members_set.all {% for member in object.members_set.all %} <p>{{member.user.first_name}} {{member.year}}</p> {% endfor %} But it doesn't produce any output, the loop is just not entered because the set is empty. I also tried : {% for member in object.members.all %} <p>{{member.first_name}}</p> {% endfor %} Which gives some satisfaction because I can display the user but not the associated data in the Membership model. Is there any way to get the set directly in the template ? Thanks! I'm running Django 3.0. -
How can i filter by date min and date max with rows?
how can i get a filter by date min and date max without model, i connect to a external database and get a consultation but cant filter Add code here: views.py def BootstrapFilterView(request): cursor.execute("[Prueba].[dbo].[Pr_Ne] '10/04/2021 4:00:00', '28/05/2021 23:59:59'") qs = cursor.fetchall() prog_data_ini = request.GET.get('prog_data_ini') date_min = request.GET.get('date_min', None) date_max = request.GET.get('date_max', None) fecha = datetime.now() format_min = fecha.strftime('%Y-%m-%d') date_max = fecha + timedelta(days=1) format_max = date_max.strftime('%Y-%m-%d') if is_valid_queryparam(date_min): qs = qs.filter(prog_data_ini__gte=date_min) if is_valid_queryparam(date_max): qs = qs.filter(prog_data_ini__lt=date_max) html <div class="input-group date"> <b class="b-form">DESDE:</b><input type="date" class="form-control" id="publishDateMin" name="date_min" value="{{format_min}}"> <span class="input-group-addon"> <i class="glyphicon glyphicon-th"></i> </span> </div> <div class="input-group date"> <b class="b-form">HASTA: </b> <input type="date" class="form-control" id="publishDateMax" name="date_max" value="{{format_max}}"> <span class="input-group-addon"> <i class="glyphicon glyphicon-th"></i> </span> </div> -
Django: Show media files to authenticated users only
I'm on Django 3.2 not using django's default server and I want to restrict certain media[mostly pdf files] inside the media directory to logged in users only. Is there any way to do that? Thanks. PS:I'm aware of a question similar to this,but it is on django v1.x and Nginx -
how to send nested functions data to another function in python
I want to display the value of a variable in world function. def base(): print("Hello World") def child(): a = 10 return a def world(): num = base.child() # error ------- print(num) world()``` -
Run custom command from admin panel
Instead of connecting to the server and running the custom command from the terminal, I'd like to make it easy for someone to log into the admin panel and run it on a button click. The current idea is to extend the admin index template to include a button that links to a particular view and then have the command be triggered in the view function. However, that sounds like a hacky solution. Is there a more elegant way? -
CreateView not receiving Kwargs from urls.py
I've been using arguments provided in the path(...) in urls.py for my view, which is a TemplateView. Now, I've been trying to do the same with a similar template, but using a CreateView. After some debugging, I've realized that for some reason a CreateView doesn't seem to receive the kwargs defined in the urls.py path. For instance: urls.py path('product/<int:pk>/', views.SomeViewClass.as_view(), {"foo": "bar"}, name='detail_product', ), views.py class SomeViewClass(TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) section = kwargs["foo"] The above works. However, this doesn't: urls.py path('create/', views.OtherClassView.as_view(), {"foo": "bar"}, name='create'), views.py class OtherClassView(CreateView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) section = kwargs["foo"] Any obvious workaround? Other than fishing out this parameter through a completely different pipeline? -
How to store Unique=True in database in django
My app keeps book records for different schools I have a Klass model that enables each school to key in the classes in the school. I also have an import-export resource for importing books details in bulk. I however get an error because already there are two schools each having form 1 form 2 and form 3. It return MultipleObjectsReturned error get() returned more than one Klass -- it returned 2! How can I help my situation??? class ImportStudentsResource(resources.ModelResource): school = fields.Field(attribute = 'school',column_name='school', widget=ForeignKeyWidget(School, 'name')) klass = fields.Field(attribute = 'klass',column_name='class', widget=ForeignKeyWidget(Klass, 'name')) stream = fields.Field(attribute = 'stream',column_name='stream', widget=ForeignKeyWidget(Stream, 'name')) class Meta: model = Student fields = ('school','student_id','name','year','klass','stream') import_id_fields = ('student_id',) import_order = ('school','student_id','name','year','klass','stream') class uploadStudents(LoginRequiredMixin,View): context = {} def get(self,request): form = UploadStudentsForm() self.context['form'] = form return render(request,'libman/upload_student.html',self.context) def post(self, request): form = UploadStudentsForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() resource = ImportStudentsResource() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) if result.has_validation_errors() or result.has_errors(): messages.success(request,f'Errors experienced during import.') print("error", result.invalid_rows) self.context['result'] = result return redirect('upload_students') else: result = resource.import_data(data_set, dry_run=False, raise_errors=False) self.context['result'] = None messages.success(request,f'Students uploaded successfully.') else: self.context['form'] = … -
I have created my piechart for my database(postgresql) value in python using django ..But i couldn't display on my server
Main url urlpatterns = [ path('',include('health.urls')), path('admin/', admin.site.urls), path('users/',include('users.urls')), path('Dashboard/',include('Dashboard.urls')) ] Dashboard.urls from django.urls import path from . import views urlpatterns = [ path("pe", views.piechart, name="piechart"), path("data", views.piechartdata, name="piechartdata") ] dashboard view.py..Here I have two functions but am able to return only one ..How to add both at my main html page from django.http import JsonResponse from django.shortcuts import render from Dashboard.models import userdashboard from django.core import serializers def piechart(request): return render(request, "piechart.html", {}) def piechartdata(request): dataset = userdashboard.objects.all() data = serializers.serialize('json', dataset) return JsonResponse(data, safe=False) In my html page i could return only one function,but I need both..can anyone help me?? <li><a href="Dashboard/pe">Dashboard</a></li> model: from django.db import models class userdashboard(models.Model): Month = models.CharField(max_length=30) Values = models.IntegerField() -
Django not accepting parsed csv date input even though it follows the YYYY-MM-DD format. What is the problem?
I'm trying to populate my existing Django model with values from a csv file. I've tried to use datetime.strptime() but it also has not worked. This is the code I'm trying to run from the Django python manage.py shell loadcsv.py import csv from dashboard.models import Checkin with open('foo.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: new_checkin = Checkin(date=row[0],project_id=row[1],manager_id=row[2],user_id=row[3],hours=row[4]) new_checkin.save() # # row[0] = date; # # row[1] = project # # row[2] = manager # # row[3] = user # # row[4] = hours models.py (dashboard.models) from django.db import models # Create your models here. class Checkin(models.Model): date = models.DateField(blank=False) project_id = models.IntegerField(blank=False) manager_id = models.IntegerField(blank=False) user_id = models.IntegerField(blank=False) hours = models.DecimalField(max_digits=5, decimal_places=2) foo.csv sample entry date,project_id,manager_id,user_id,hours 2019-09-11,134,1,1,3 2019-09-11,201,1,1,5 2019-12-23,14,8,2,0.46 2019-12-23,14,8,2,0.46 The error I'm getting django.core.exceptions.ValidationError: ['“date” value has an invalid date format. It must be in YYYY-MM-DD format.'] I can save to the database when I manually create a single object in the shell like so: from dashboard.models import Checkin new_checkin = Checkin(date="2012-01-01", manager_id="5", project_id="5",user_id="3", hours="0.75") new_checkin.save() -
Cookies in Django/JavaScript for a cart in webstore
I'm just starting to add cookie to my webstore and I need to use cookies in order for the cart to update the added products. Any tips? Is django good to use for storing cashe and using them in the shopping cart - or is it simpler to only use JavaScript? Don't have a lot of code to show as I've just stared doing the cookies, any tips would be helpful! :) -
I want to login with both and phone number in this DRF
I'm currently using a custom user model and can log in with my phone number. But now I want to log in with both phone and email. Please check the given code and let me know in the comments if any more details are needed. Thanks in advance. class LoginSerializer(serializers.Serializer): phone = serializers.CharField() password = serializers .CharField() def validate(self, data): email = data. get ('email') phone = data.get('phone') password = data.get('password') reg = False print(phone, ",", password) obj = CustomUser.objects.get(phone=phone) if phone and password: user = authenticate(username=obj.username, password=password) if user: data['user'] = user print(user.id) else: msg = 'login failed' raise exceptions.ValidationError(msg) else: msg = 'provide credientials' raise exceptions.ValidationError(msg) return data -
Django custom URL mapping: date pattern not matched in template
I am using Django 3.2 I have created a custom Date URL pattern matcher as follows: helpers.py from datetime import datetime class DateConverter: regex = '\d{4}\d{2}\d{2}' def to_python(self, value): return datetime.strptime(value, '%Y%m%d') def to_url(self, value): return value urls.py from django.urls import path, register_converter from . import views from myproj.helpers import DateConverter app_name = 'event' register_converter(DateConverter, 'yyyymmdd') urlpatterns = [ path('', views.index, name='index'), path('detail/<int:event_id>/<slug:event_slug>', views.detail, name='detail'), path('archive/<yyyymmdd:start_date>/<yyyymmdd:end_date>', views.archive, name='archive'), ] index.html (relevant section) <div class="row"> <a href="{% url 'event:archive' '2020101' '2020201' %}">Previous Events</a> </div> I get the following error: reverse for 'archive' with arguments '('2020101', '2020201')' not found. 1 pattern(s) tried: ['media/events/archive/(?P<start_date>\d{4}\d{2}\d{2})/(?P<end_date>\d{4}\d{2}\d{2})$'] How do I fix this? -
django superuser created through docker-compose file doesn't work
I have a simple django-mongo application. I have a dockerfile for my django application. I have a docker-compose.yml which contains django and mongo images. I am able to build and run the django-mongo application using docker-compose commands. the problem I am facing is I am unable to log into the django admin-panel using superuser credentials. Below is my dockerfile RUN mkdir /cursor_infotech WORKDIR /cursor_infotech ADD . /cursor_infotech/ RUN pip install -r requirements.txt``` docker-compose.yml ```version: "3" services: cursor-infotech: container_name: cursor image: cursor restart: always build: . #environment: # - MONGO_URI=$MONGO_URI # - PORT=$PORT # - NODE_ENV=$NODE_ENV ports: - "7000:7000" networks: - cursor-backend depends_on: - mongo command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py createsuperuser --noinput --username admin --email admin@test.com && gunicorn -b 0.0.0.0:7000 cursor_infotech.wsgi" mongo: container_name: mongo image: mongo environment: - MONGO_INITDB_DATABASE=cursor-pcbuild - MONGO_INITDB_ROOT_USERNAME=root - MONGO_INITDB_ROOT_PASSWORD=password volumes: - ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo-js:ro - ./data:/usr/share/db/data ports: - '27017:27017' networks: - cursor-backend networks: cursor-backend: driver: bridge``` I ran this command in my project folder ```docker-compose up --build``` The django & mongo images are build and deployed - working fine. When I try to log-into admin account in my django admin-panel, I get below error. [enter image description here][1] [1]: https://i.stack.imgur.com/WiMOV.png … -
image annotation tools with Django
I need to create an online 2D annotation tool using DJANGO. I would like to know how I can implement an already existing image annotation tool like for example (CVAT / VGG VIA / LabelMe ...) in django, Thank you. -
Reverse list in descending order to get the last objects in django template
I've searched a lot and couldn't find anything to reverse the list in descending order so that I can get the last two objects in the template. Here is my model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') commented_by = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=128) views.py: posts = Post.objects.all().order_by("date_posted").reverse() return render(request, "cs50gram/explore.html", {"posts": posts}) template.html: {% for post in posts %} {% for comment in post.comments.all|slice:":2" reversed %} <div style="color: gray"> <b> {{ comment.commented_by }} </b> {{ comment.comment }} </div> {% endfor %} {% endfor %} The problem here is that it slices first and then reverse.. What have I tried? How to reverse a for loop in a Django template and then slice the result Using the solution presented in the answer, it didn't work for some reason. This is exactly how I tried it in my code. {% for post in posts %} {% for comment in post.comments.all.reverse|slice:":2"%} <div style="color: gray"> <b> {{ comment.commented_by }} </b> {{ comment.comment }} </div> {% endfor %} {% endfor %} The output is that it only slice it without reversing. Any help in reversing the list in descending order and getting the last n (2) objects is appreciated. -
Is there a difference between (eg) 'ListView' and 'generic.ListView'?
Please help clarify some basic concepts. Googling leads to answers about the difference between two different views, eg, ListView vs DetailView, but not where my confusion is: The official Django docs has two import versions: from django.views import generic class IndexView(generic.ListView): And from django.views.generic.detail import DetailView class ArticleListView(ListView): Are the two interchangeable? I have had the following seemingly with no ill effect: from django.views import generic class IndexView(ListView): # insteald of `generic.ListView` -
How to manipulate CharField as a string Django
I have a charfield in which the user inputs a range of numbers which will correspond to a list of numbers. For example the user should be able to input '1, 2, 3, 4, 5' or '1-5', and I want to be able to convert that into a list of all those numbers in the range. When I grab the field's cleaned_data in the views.py, however, the value does not behave like a string. The .split() does not convert to a list, and the for loop loops through individual characters. How can I convert the field into a usable string? In the views.py: def my_view(request): if request.method == 'POST': if form.is_valid(): nums = form.cleaned_data['numbers'] nums.split(',') num_list = [] for item in nums: if '-' in item: item.split('-') for x in range(item[0], item[1]): num_list.append(x) else: num_list.append(item) If the input is '1-160', I get an error because the single character '-' can't be split into two items and be indexed. The expected num_list is a list of all the integers between 1 and 160. If the input is '1,2,3' num_list is a list of all the characters, not just the numbers. -
How can I implement a checkbox in django from my database
I need to make a project for faculty administration. I made a project that selects 3 tables from my database. I have 3 ModelChoiceField and a submit button on my page. When I click submit I need to be redirected to a new page that has a list of checkboxes that are related to my choices from the 3 choiice fields. models.py: class An(models.Model): an_studiu = models.SmallIntegerField(primary_key=True) class Meta: managed = False db_table = 'an' def __str__(self): strAni = ["0", "I", "II", "III", "IV", ] return strAni[self.an_studiu] class Disciplina(models.Model): id = models.CharField(primary_key=True, max_length=256) denumire = models.CharField(max_length=256, blank=True, null=True) an_studiu = models.ForeignKey(An, models.DO_NOTHING, db_column='an_studiu', blank=True, null=True) id_program_studii = models.ForeignKey('ProgramStudii', models.DO_NOTHING, db_column='id_program_studii', blank=True, null=True) pondere_evaluare = models.FloatField(blank=True, null=True) nr_lucrari = models.IntegerField(blank=True, null=True) nr_teme = models.IntegerField(blank=True, null=True) nr_evaluari = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'disciplina' class Incadrare(models.Model): semigrupa = models.ForeignKey('Semigrupa', models.DO_NOTHING, db_column='semigrupa', blank=True, null=True) id_disciplina = models.ForeignKey(Disciplina, models.DO_NOTHING, db_column='id_disciplina', blank=True, null=True) id_profesor = models.ForeignKey('Profesor', models.DO_NOTHING, db_column='id_profesor', blank=True, null=True) class Meta: managed = False db_table = 'incadrare' class ProgramStudii(models.Model): id = models.CharField(primary_key=True, max_length=256) abreviere = models.CharField(max_length=256, blank=True, null=True) denumire = models.CharField(max_length=256, blank=True, null=True) nr_ani_studiu = models.SmallIntegerField(blank=True, null=True) def __str__(self): return self.abreviere class Meta: managed = False db_table = 'program_studii' class … -
how do i delete a file from azure blob based on file path in Django
MODELS.PY class FilesHistory(models.Model): filename = models.CharField(max_length=100, blank=False, null=False) file = models.FileField(upload_to='upload/%y/%m/%d/',null=False,blank=False) sentGroupId = models.CharField(max_length=100,blank=False) uploaded_at = models.DateTimeField(auto_now_add=True,blank=True) def delete(self, using=None, keep_parents=False): self.file.storage.delete(self.file.path) super().delete() this delete function is working for removing files from the media folder based on the file path. -
CustomUser created through Django Admin cannot login (Django Rest Framework)
I created a register/login system through DRF by overriding dj_rest_auth If registering an user with Postman, by firing on the endpoint, that user can be used for login through endpoint However, if creating an user through Django Admin, that user cannot be used for login through endpoint, and notably, if seen through Django Admin, the password is not hashed serializers.py class CustomLoginSerializer(LoginSerializer): def validate_auth_user_status(self, user): request = self.context.get('request') if not request.data.get('role'): msg = 'Role is missing from the payload.' raise exceptions.ValidationError(msg) if not user.groups.filter(name=request.data.get('role')).exists(): msg = 'Invalid role for the user.' raise exceptions.ValidationError(msg) def create(self, validated_data): pass # Empty because the function is not needed # but Pylint demanded to implement it anyway def update(self, instance, validated_data): pass # Empty because the function is not needed # but Pylint demanded to implement it anyway class CustomRegisterSerializer(RegisterSerializer): name = serializers.CharField() def get_cleaned_data(self): super().get_cleaned_data() return { 'email': self.validated_data.get('email', ''), 'password1': self.validated_data.get('password1', ''), 'name': self.validated_data.get('name', '') } def create(self, validated_data): pass # Empty because the function is not needed # but Pylint demanded to implement it anyway def update(self, instance, validated_data): pass # Empty because the function is not needed # but Pylint demanded to implement it anyway def save(self, request): user = … -
creating objects in PostgreSQL and Django
I'm trying to create rows inside my PostgreSQL using scraped data from a website. I'm pretty sure my approach is wrong. here is tasks.py inside one of my Django apps which is supposed to do the scraping and then add the scraped data to db: from models import Movies from bs4 import BeautifulSoup import requests url = 'any url' r = requests.get(url).text soup = BeautifulSoup(r, 'lxml') title = soup.find('a', class_='movie_name') year = soup.find('span', class_='year') rating = soup.find('p', class_='rate') Movies.objects.create( title = 'the movie name', year = 2020, rating = 8.7) and this is my models.py : class Movies(models.Model): title = models.CharField(max_length=20) year = models.IntegerField(max_length=4) rating = models.FloatField(max_length=10) What's the best way to scrape data and add it automatically to the database? -
Image Render Problems [Pillow]
I'am trying to make image resize service with Pillow.The images saved in the cache folder look completely correct. But when I look at the browser, there is a small white box instead of resized image. http://127.0.0.1:8000/media/images/Test_image.jpg it look like https://prnt.sc/12sy9it Here is my code. from io import BytesIO import requests from PIL import Image from django.http import HttpResponse from django.conf import settings def image_downloader(url): filename = url.split("/")[-1] response = requests.get(url) print(response.headers) if response.status_code == 200: print('Image sucessfully Downloaded: ', filename) return response.content else: print('Image Couldn\'t be retreived') return None def image_resizer(img_content): img = Image.open(BytesIO(img_content)) img.thumbnail((960, 640), Image.ANTIALIAS) return img def image_provider(request): _url = 'https://upload.wikimedia.org/wikipedia/en/9/95/Test_image.jpg' _filename = _url.split('/')[-1] image = image_downloader(_url) resized_image = image_resizer(image) print(settings.BASE_DIR + "/cached_files/" + _filename) print(resized_image.get_format_mimetype()) resized_image.save(settings.BASE_DIR + "/cached_files/" + _filename, optimize=True, quality=60) # resized_image.seek(0) response = HttpResponse(resized_image, content_type='image/jpeg') return response -
How to login with both phone and email in this Django program?
I want to login with both email and phone . Currently Iam able to login using phone , I need to login with email also .I am using CustomUser.Please let me know in the comments if anymore details are needed,I am not sure about this method , please suggest correct method if this is wrong. class loginn(TemplateView): model = CustomUser form_class = LoginForm template_name = "../templates/Customer/loginn.html" context = {} def get(self, request, *args, **kwargs): self.context['form'] = self.form_class return render(request, self.template_name, self.context) def post(self, request, *args, **kwargs): form = LoginForm(request.POST) phone = request.POST.get('phone',False) password = request.POST.get('password',False) email = request.POST.get('email',False) try: obj = CustomUser.objects.get(phone=phone) except: obj = CustomUser.objects.get(email=email) user = authenticate(username=obj.username, password=password,backend='Customer.backends.CustomerBackend') if user is not None: login(request, user) if user.is_authenticated: obj1=CustomerProfile.objects.all() if obj1.exists(): for datas in obj1: if request.user==datas.user: return redirect('index') if request.user != datas.user: return redirect('customerprofilecreate') else: return redirect('customerprofilecreate') else: messages.error(request,"Invalid Credentials") return redirect('loginn')