Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Realtions and render multiple inlineformset_factory in the same page
I'm writing a Django application and I'm stuck at the point where I can't figure out how to structure the model and use the inlineformset_factory to get on a single page the ability to dynamically add for each customer a variable set of activities for each week day (0-6). For Example: Monday Tennis Yoga Tuesday Tennis Running Judo [ ... ] Sunday Walking Swimming Suppose that I have this model: DOW = ( (1, "Lunedì"), (2, "Martedì"), (3, "Mercoledì"), (4, "Giovedì"), (5, "Venerdì"), (6, "Sabato"), (7, "Domenica"), ) class Customer(models.Model): firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) def __str__(self): return self.firstname + " " + self.lastname class Week(models.Model): cliente = models.ForeignKey( Customer, on_delete=models.CASCADE, null=True, blank=True, default=None ) week_number = models.IntegerField() week_day = models.IntegerField( choices=DOW, null=False ) def __str__(self): return "Week number: " + self.week_number class Activity(models.Model): name = models.CharField(max_length=20) week_day = models.ForeignKey(?) def __str__(self): return "Activity: " + self.name What is the relation to put in place between Activity <-> Week to obtain the ability to have into a single page multiple forms that belong to a specific 'week_number' for each 'week_day' ? I have to create a specific "Activity" model one for each day and then use them into inlineformset_factory(Week,Activity_Monday), … -
changing function to class python
I am using django version 1.8.6. I have created student edit profile function so I want to change that function to class here is my views.py def student_edit_profile(request): if request.method == 'POST': info_form = StudentEditProfileInfoForm(request.POST, request.FILES, instance=request.user) edit_form = StudentEditProfielForm(request.POST, instance=request.user) if edit_form.is_valid() or info_form.is_valid(): edit_form.save() info_form.save() return redirect('student_course_list') else: info_form = StudentEditProfileInfoForm(instance=request.user) edit_form = StudentEditProfielForm(instance=request.user) return render(request, 'students/student/edit_profile.html', {'edit_form':edit_form, 'info_form': info_form}) else: info_form = StudentEditProfileInfoForm(instance=request.user) edit_form = StudentEditProfielForm(instance=request.user) return render(request, 'students/student/edit_profile.html', {'edit_form':edit_form, 'info_form': info_form}) and also here is my forms.py class StudentEditProfielForm(UserCreationForm): class Meta: model = User fields = { 'first_name', 'last_name', 'username', 'email', 'password', } class StudentEditProfileInfoForm(forms.ModelForm): class Meta: model = StudentProfile fields = { 'date_of_birth', 'bio', 'gender', 'country', 'address', 'city', 'image' } Anyone can I need that student_edit_profile() function change to class, and also if I visit the link without login it will show error showing like this 'AnonymousUser' object has no attribute '_meta' Anyone I need help. -
How to get the last item Message from every user in Django?
I am making a Django Chat app and I try to create an all message window, where I need all of the last messages that I got from the users I already tried distinct() and with .values() but nothing worked(I know I miss spelled recenpen_id, that is not the problem) class MessageView(APIView): def get(self, request): message = Message.objects.order_by().filter(recepien_id=request.user.id) serializer = MessagesSerializer(message, many=True) return Response({"message_info":serializer.data}) -
When are ContentTypes and Permissions created?
I created a new model and wanted to give permissions to a certain group group in the migration file after the migrations.CreateModel cando_ct = ContentType.objects.get(app_label='main', model='cando') cc_group = Group.objects.get(name='content creators') add_p = Permission.objects.get(content_type=cando_ct, codename='add_cando') cc_group.permissions.add(change_p, delete_p, view_p) but when i run migrate, i get an error saying: ContentType matching query does not exist. but if i run this script in a separately (in a different python manage.py migrate instance), i don't get the error. So my question is when are the contenttypes and permissions created? -
range() issue in Django unittest
I have a Django testcase, and I'm creating some objects in setUp: OBJ_COUNT = 4 class ObjTest(TestCase): def setUp(self): for i in range(OBJ_COUNT): print(i) Obj.objects.create() Running this test results in 5, not 4 objects! And the print() gets this output: 0 1 2 3 5 wtf? But the same code works as expected outside of setUp(). Am I missing something? Maybe this is somehow related to recent upgrade to Django 2.2.3 (from 2.1.7)? -
Is there a new device login alert system in django?
I am looking for a package or a way to implement a system into Django project that would send alerts to the users whenever a new login to their account is detected from a new device or basically different from the device they signed up from in the first place. Please suggest something that would work in production. I expect it to work in Django2 and python3. -
How to save queryset by user in new models from our created models?
I have some models and every models have many queryset. models: class Match(models.Model): match_name = models.CharField(max_length=20) first_team = models.ForeignKey('FirstTeam', on_delete=models.SET_NULL, null=True) second_team = models.ForeignKey('SecondTeam', on_delete=models.SET_NULL, null=True) tournament_name = models.ForeignKey('TournamentName', on_delete=models.SET_NULL, null=True) match_created = models.DateTimeField(auto_now_add=True) match_stated = models.DateTimeField(default=timezone.now()) mega_league = models.ManyToManyField('MegaLeague', blank=True) I have also many models class like this. In admin section I created data for every models and then I show all queryset on different templates correctly. Now I want to make same duplicate models class(same fields also) where data is stored by user. When user select our own queryset in templates then that queryset will store in new duplicate models(same class and same fields) and every queryset will different different for different users. That means every user can store their queryset by selecting our own queryset from templates. How can i do this?? -
How to save a string variable from views in Django
I'm trying to use pytesseract for my Django application. In views.py I called pytesseract and stored all the text it found in the 'text_content' variable. I want to save this variable as the 'text' parameter for my model, but I'm not sure how to go about this. I tried to use .save(), but got this error: 'str' object has no attribute 'save' <!-- language: lang-py --> #views.py def image_view(request): if request.method == 'POST': form = partForm(request.POST, request.FILES) if form.is_valid(): form.save() data = request.POST.copy() image_file = request.FILES.get('image') text_content= pytesseract.image_to_string(Image.open(image_file)) text_content.save() return redirect('success') else: form = partForm() return render(request, 'add_image.html', {'form' : form}) # models class Component(models.Model): snum = models.CharField(max_length=20, default = '') image = models.ImageField(blank=True) text = models.TextField(default = 'no text found') #forms.py class partForm(forms.ModelForm): snum = forms.CharField(max_length=128, help_text="please enter the number.") class Meta: model = Component fields = ['snum', 'image'] -
How to check the lines that executed while processing a http request in a Django Project
I am developing a Django application, it is successfully working right now. I want to track how many lines of code is being executed while serving an HTTP request. I've gone through the coverage.py but it has to be included in the view, due to this I am not able to get the code coverage of the entire scenario i.e. from import statements to return Response. Below is the code that I've Implemented. This is models file from django.db import models class Puppy(models.Model): """ Puppy Model Defines the attributes of a puppy """ name = models.CharField(max_length=255) age = models.IntegerField() breed = models.CharField(max_length=255) color = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_breed(self): return self.name + ' belongs to ' + self.breed + ' breed.' def __repr__(self): return self.name + ' is added.' class PuppyStore(models.Model): """ Puppy store, this supply all puppy needs """ puppy = models.ForeignKey(Puppy,on_delete=models.CASCADE) food = models.CharField(max_length=25) Views file from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Puppy from .serializers import PuppySerializer from coverage import Coverage @api_view(['GET']) def list_puppies(request): try: cov = Coverage() cov.erase() cov.start() qset = Puppy.objects.all() resp = PuppySerializer(qset, many=True) cov.stop() cov.save() cov.html_report() return Response(resp.data, status=status.HTTP_200_OK) except Exception … -
How to pass login view to header django
I have some problems about passing the login view to header, I want users to login from everypage via header but I couldn't do it yet. I tried to pass the view using render(request, "header.html") but it didn't work -
Django URL converters for date/time values
I'm trying to use the URL converters built into Django to convert a date time string in the URL into a date object in my views. They work as expected if I enter the URL manually, but trying to generate a URL for it cannot find a match. My converters are simple: from django.utils.timezone import datetime from datetime import time class DateConverter: regex = '[0-9]{4}-[0-9]{2}-[0-9]{2}' def to_python(self,value): return datetime.strptime(value,"%Y-%m-%d") def to_url(self,value): return value.strftime("%Y-%m-%d") class TimeConverter: regex = '[0-9]{4}' def to_python(self,value): t = datetime.strptime(value,"%H%M") return time(t.hour,t.minute) def to_url(self,value): return value.strftime("%H%M") In my template I have some nested loops that are cycling through available time slots where I call url for each combination of time slots: <a href="{% url 'club_boats:trip_booking' trip_date slot.slot.start_time slot.slot.end_time boat.boat.pk %}">Join</a> My urls.py file is: from django.urls import path, register_converter from . import converters, views register_converter(converters.DateConverter, 'date') register_converter(converters.TimeConverter,'time') urlpatterns = [ path('<int:boat_id>',views.detail,name='detail'), path('<date:trip_date>/',views.day_view,name='day_view'), path('<date:trip_date>/<time:trip_start_time>/<time:trip_end_time>/<int:boat>/',views.trip_booking,name='trip_booking'), path('', views.day_view, name='day_view') ] I've confirmed that the data types match what it's expecting (time, datetime, etc...) but the reverse conversion doesn't seem to be happening. When I try to load the tempalte that contains the above url call I get a NoReverseMatch error: Reverse for 'trip_booking' with arguments '(datetime.datetime(2019, 7, 1, 0, 0), … -
URL sent to Django using AJAX is different when printed from Django
I have a JQuery event that, when a link is clicked, an AJAX POST request is sent to a Django function. There I print the recieved url and do other stuff with it. However, when it is printed (by Django) some characters in the url are changed. The specific url this happened with was : https://www.catholicleague.org/05press_releases/quarter%204/051110_put_on_notice.htm Which was printed as : https://www.catholicleague.org/05press_releases/quarter+4/051110_put_on_notice.htm Where %20 was changed to + Here is the AJAX and Django code: $("a").on("click", function(e){ e.preventDefault(); if(e.target.href){ let clicked_source = e.target.href; let csrf_tok = parent.document.getElementById("csrf_tok").value; $.ajax({ url: "/change_origin/", data: JSON.stringify({"clicked_source":clicked_source}), type: "POST", beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrf_tok );}, success: function(response) { console.log(response.msg) }, error:function(error) { console.log(error); } }); } }); def change_origin(request): if request.method == 'POST': received = ast.literal_eval(request.body.decode()) print(received) clicked_source_url = received['clicked_source'] return JsonResponse({'msg': "ok"}) Where decode is used as the JSON object is received in Python as a byte-like object. And ast is used to turn the string representation of the object to an actual object (or dict) for access. I need either: 1) A way to just send a string from Ajax to Django 2) A better way to deal with the received object as I believe using .decode() might be the one … -
Why did the server send me a font that is already installed on my machine?
I am new to web development and I am trying to make a simple web game using python 3.7 with django as web framework combined with the channels package for using web sockets. I am trying to use custom fonts for the game UI. I used the css local() function to make sure the fonts aren't sent if the client has them already installed on his system as it says here: It's common to use both url() and local() together, so that the user's installed copy of the font is used if available, falling back to downloading a copy of the font if it's not found on the user's device. However, it seems that the django development server sends me those fonts although I already have them installed on my machine. Here's my html templates and css: core/templates/core/base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% if title %} <title>Stratego - {{ title }}</title> {% else %} <title>Stratego</title> {% endif %} <link rel="stylesheet" href="{% static "core/css/style.css" %}"> </head> <body> {% block content %}{% endblock %} </body> </html> core/templates/core/game.html: {% extends "core/base.html" %} {% load static %} {% block content … -
"how to get already exist cart id in django"
"when user login into website ,cart_id created without user name and then user jump into cart.html user name stored in cart_id.after that user add and delete item from cart table.but when user was logout form website and again login into website, new cart_id created and the user's cart appears empty" "I want already exist cart and cart item" Models.py class CartManager(models.Manager): def new_or_get(self,request): cart_id = request.session.get("cart_id",None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj , new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated: user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User,null=True , blank=True , on_delete=models.CASCADE) product = models.ManyToManyField(Product, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) VIEWS.py def cart_home(request): cart_obj,new_obj = Cart.objects.new_or_get(request) return render(request,"cart/cart.html",{"cart":cart_obj}) i'm tring to create user cart, cart was created but after logout and again login new cart was created, i want already exist cart and cart item -
Scraped data doesn't go to the Postgres database
The scraper should scrape every blog post on each page Data from the scraper should go to the Postgresql database, where the following statistics will be counted: The 10 most common words along with their numbers under the address /stats The 10 most common words with their numbers per author available under the address / stats / / posts authors with their name available in the address / stats / / available under the address / authors / so far I have focused on the first and second task but I have two problems (one results from the other and vice versa) I do not know how to make the data go to the database and thus I do not know how to do "Counter" Here is my scraper: import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from collections import Counter import psycopg2 # from sqlalchemy.dialects.postgresql import psycopg2 url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) num_pages = int(soup.select_one('.page-number').text.split('/')[1]) for page in range(2, num_pages … -
Heroku push does not upload migrations
I have developed a Django project and want to deploy it on a Heroku server. The problem is that my migrations are not uploaded after 'heroku push' command. After I run python ./Code/manage.py makemigrations python ./Code/manage.py migrate I see my migration files and database locally. But, after that, when I push them to Heroku, they seem not to be there. My website on Heroku gives the error that some tables are not available and when I run bash on the server to see my files there aren't any migration files and the migration folders in my apps only have the init.py file. I even tried to make the migrations and migrate on the release phase. This is the Procfile: release: bash ./release_tasks.sh web: gunicorn --pythonpath Code Code.wsgi --log-file - and this is release_tasks.sh: python ./Code/manage.py makemigrations python ./Code/manage.py migrate Again, when I push to Heroku everything is ok and I see the correct migration messages, which shows that migration was successfully carried out. But still, there is no migration file on the server and my website gives the same error. -
pipenv install django without re-downloading it every time?
i have limited internet access temporarily, and every time i need to start a new django project i have to re-download django (and other dependencies) that i have already downloaded from other projects. is there an easier way to pipenv install django and other dependencies without downloading them over again every time? i read that there is a cache of these dependencies, but if thats true my issue then becomes, i dont know how to access the cache so that the dependencies install correctly into the project. or if there was one location in my 'downloads' folder where i could install directly from it, instead of from the internet. im hoping for something along the lines of: pipenv install django==2.2.0 from=c:\downloads\dependencies i expect that i will then install from previously downloaded files without the use of an internet connection. -
Why is my if statement producing a key error?
I have a view that simply checks for a key in the session store and if its present it will delete it and if its not present it should pass, it may be worth noting that the key store is holding ids of model instances. def RefreshInstances(request): if request.session['instances']: del request.session['instances'] else: pass return redirect('/') This works and achieves its goal deleting the instances, however if the key store is empty I get a key error rather than the code just being passed? Can anyone shed any light? Thanks in advance. -
How to change sender email name in Django
I need to send an email from Django with 'Team Example' as a sender and by default, no-reply@example.com is used. I have tried this as mentioned in other StackOverflow questions DEFAULT_FROM_EMAIL = 'Team Blackweb <noreply@example.com>' in settings.py but it doesn't work. -
Doing a text file items selection in Django
I have a problem of selecting multiple items on the checkbox list that I want to display on a new text file (overwriting each time). In this example, SAMPLEs, I have tried the following codes below but I still cannot find a way whereby each of the selection items in SAMPLEs (in selection_html below). Each time, when I try to select multiple items, it only gave me the latest item on the text file, named as samples.txt. Codes in views.py if request.method == 'POST' and 'btnform3' in request.POST: get_samples = request.POST.get('samples[]') f1 = open(os.path.join(settings.MEDIA_ROOT, "samples.txt"), "w+") f1.write(get_samples) Codes in selection_html (GUI where my selection items in samples will be selected by the user) <form method="post" enctype="multipart/form-data"> {% csrf_token %} <h4>SAMPLEs</h4> <input id="4" type="checkbox" name="samples[]" value="4" /> <label for="4">4</label> <br /> <input id="5" type="checkbox" name="samples[]" value="5" /> <label for="5">5</label> <br /> <input id="6" type="checkbox" name="samples[]" value="6" /> <label for="6">6</label> <br /> <p><input type = "submit" value="Submit" name="btnform3"</p> </form> Can anyone guide me and possibly provide a solution to this recurring problem of mine? Thank you. -
Celery unable to find tasks in Django app
I am pretty much following the standard project organization structure. But celery is unable to find tasks located in my apps. It can find the "debug_task" located in the celery.py but it fails to pick up tasks located in the tasks.py file of the apps. My directory structure: D:. │ manage.py │ requirements.txt │ ├───fooproject │ │ celery.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ ├───settings │ │ │ base.py │ │ │ remote.py │ │ │ __init__.py │ │ ├───bravo <- app directory │ │ admin.py │ │ apps.py │ │ models.py │ │ tasks.py <- tasks file from where it fails to pick up tasks │ │ tests.py │ │ __init__.py fooproject/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fooproject.settings') app = Celery('fooproject') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY', force=True) # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) fooproject/init.py from … -
Django - how to save form with multipule objects?
I am using Python3.7, Django 2.2. Below you can find my code, to better understand my problem. As you can see my code below, I have created table with some records. Skip polish name of the values in models.py. We have to focus only for manager_accpt. This value has 2 arguments (check file choices.py). When I create view with def manager_day_free_accpt I get multiple objects. The last column contains choice, which my user have to choose and save. Example I have put in screen below. What is my problem. I have to do it in 2 ways, beacause user will choose, which solution is more user friendly for them :) I have problem with buttons, where should i put them? Because right now, submition change whole objects, but with wrong values. When I put Buttons outside "for loop", nothing happend with objects. Can you help me, I have to find two solutions for it: 1st: Every row should contain green button with submit and reject (white button). And when user click on green button, the value only in this raw should update objects in db.. 2nd sol: User choose accept and reject in every row. After that user should push … -
Output a CSV file without downloading it
I'm doing a simple View and I want the response to be a csv file but I don't want the explorer to download it. Here I show you the response I'm giving: def csv_response(self, fields, queryset=None, filename=None): if not queryset: try: queryset = self.get_queryset() except AttributeError: raise ImproperlyConfigured('This method needs to have a queryset configured.') if not filename: filename = self.__class__ response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'inline' writer = csv.DictWriter(response, fieldnames=fields.keys(), delimiter=',') writer.writeheader() for element in queryset: writer.writerow({fieldname: getattr(element, field) for fieldname, field in fields.items()}) return response I just want it to output it in any explorer instead of downloading it, is it even possible? I think it is as I've seen some on the Internet. -
How can I rename an uploaded file on Django before sending it to amazon s3 bucket?
I have a Django App which allows a user to upload a file and save it to an s3 bucket. My question is how could I rename the file before uploading to the bucket? This is my models.py class: from converter.storage_backends import CsvStorage from django.db import models from django.utils import timezone class CSVUpload(models.Model): csv_file = models.FileField(storage=CsvStorage()) def __str__(self): return self.csv_file And this is my backend_storages.py class: from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class CsvStorage(S3Boto3Storage): location = settings.AWS_CSV_LOCATION file_overwrite = False Could anyone help me understand how to go about it? I appreciate any help you can provide -
Cannot access ListField elements from another python code
Hello I want to share a mongodb between two django apps (monitor , manager) using one application called common. I can create database instances in the manager application easily but when accessing the book authors i cannot. it return this error mongoengine.errors.FieldDoesNotExist: The fields "{'_id'}" do not exist on the document "author" models.py from mongoengine import * class author(Document): name = StringField(required = True) meta = {'abstract': True , 'allow_inheritance':True} class book(Document): name = StringField(required = True) authors = ListField(ReferenceField(author)) meta = {'abstract': True , 'allow_inheritance':True} manager.py from mongoengine import * from models import * class author(author): def rand(self): print("i am useless") class book(book): def rand2(self): print("i am also useless") if __name__ == "__main__": connect('test', host = '0.0.0.0',port = 27017) a1 = author(name = "Charef") a1.save() a2 = author(name = "hamid") a2.save() a3 = author(name = "djoudi") a3.save() a4 = author(name = "cheb khaled") a4.save() book1_authors = [a1,a2,a4] book2_authors = [a1,a3] book1 = book(name = "Hello Django", authors = book1_authors) book1.save() book2 = book(name = "Hello python", authors = book2_authors) book2.save() monitor from mongoengine import * from models import * class author(author): def say_hi(self): print("Hi, my name is {} and this is my book".format(self.name)) class book(book): def book_info(self): for author …