Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'powershell.exe' is not recognized as an internal or external command, operable program or batch file
I am using Windows 10, and Windows Powershell as command terminal. I just started to learn Django framework and being trying to setup my env as 1st time practice. This is my location: PS C:\Users\MyUsername\Desktop\cfeproj> This was successful: python -m pipenv install However, when I run : pipenv shell PS C:\Users\LENOVO\desktop\proj> pipenv shell Launching subshell in virtual environment... 'powershell.exe' is not recognized as an internal or external command, operable program or batch file. Please help me ho to configure this problem. I'm basically very new and still learning. Would be so appreciate if somebody can help me out here. =D -
Save a file from requests using django filesystem
I'm currently trying to save a file via requests, it's rather large, so I'm instead streaming it. I'm unsure how to specifically do this, as I keep getting different errors. This is what I have so far. def download_file(url, matte_upload_path, matte_servers, job_name, count): local_filename = url.split('/')[-1] url = "%s/static/downloads/%s_matte/%s/%s" % (matte_servers[0], job_name, count, local_filename) with requests.get(url, stream=True) as r: r.raise_for_status() fs = FileSystemStorage(location=matte_upload_path) print(matte_upload_path, 'matte path upload') with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) fs.save(local_filename, f) return local_filename but it returns io.UnsupportedOperation: read I'm basically trying to have requests save it to the specific location via django, any help would be appreciated. -
Why do I get "AttributeError: 'Template' object has no attribute 'add_description'" error when deploy with Zappa?
So I'm trying to deploy my Django project with zappa. I've installed, and init-ed successfully and now trying to deploy. However, after zappa deploy, I get the following error: AttributeError: 'Template' object has no attribute 'add_description'.What do you think is the problem? Full error message is: Traceback (most recent call last): File "c:\users\user\envs\synergy\lib\site-packages\zappa\cli.py", line 3422, in handle sys.exit(cli.handle()) File "c:\users\user\envs\synergy\lib\site-packages\zappa\cli.py", line 588, in handle self.dispatch_command(self.command, stage) File "c:\users\user\envs\synergy\lib\site-packages\zappa\cli.py", line 630, in dispatch_command self.deploy(self.vargs["zip"], self.vargs["docker_image_uri"]) File "c:\users\user\envs\synergy\lib\site-packages\zappa\cli.py", line 960, in deploy endpoint_configuration=self.endpoint_configuration, File "c:\users\user\envs\synergy\lib\site-packages\zappa\core.py", line 2417, in create_stack_template self.cf_template.add_description("Automatically generated with Zappa") AttributeError: 'Template' object has no attribute 'add_description' -
how to create a file dynamically with OCR result from an image model
i created two apps in django one to upload a file and process it and one to preform OCR and create a pdf file from the processed image. so i have two models one for images and another for files, when i upload an image it goes through the processing pipeline then automatically the file field in the File model is populated with the result. When i m working with the admin panel or with DRF api root it is working fine, but when i use POSTMAN or react Native front end i get internal server error and the image is uploaded but no file is created. I m still learning django and backend concepts so i don't even know where to look for the issue: here are my models class Uploads(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title=models.CharField(max_length=100,default='none') image=models.ImageField(upload_to='media',unique=True) created_at = models.DateTimeField(auto_now_add=True) super(Uploads, self).save(*args, **kwargs) if self.id : File.objects.create( file=(ContentFile(Create_Pdf(self.image),name='file.txt') )) class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) label=models.CharField(max_length=100, default='none') title=models.CharField(max_length=200,default='test') file=models.FileField(upload_to='files') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) import PIL.Image pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' def Create_Pdf(image): text=pytesseract.image_to_string(PIL.Image.open(image)) return(text) -
Docker build error Could not find a version that satisfies the requirement Django
I'm just learning Docker and working with django from last 1 year. Today I try to work with docker and getting this error. ERROR: Could not find a version that satisfies the requirement Django<3.2.2 I'm familiar with this error. But with docker i don't know how to solve this. Dockerfile Configuration: FROM python:3.9-alpine ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user USER user requirements.txt Django >=3.2.5,<3.2.2 djangorestframework>=3.12.4,<3.9.0 see the error message image here can anyone help me how to fixed this ? -
Django is not updating my database after submitting my form
I have created a model and a form, both are working correctly, and I have added data to the database using the admin module models.py class Client(models.Model): firstname = models.CharField(blank=True, max_length=30) lastname = models.CharField(blank=True, max_length=15) company = models.ForeignKey(Company, on_delete=models.CASCADE, default="company") position = models.CharField(blank=True, max_length=15) country = CountryField(blank_label='(select country)') email = models.EmailField(blank=True, max_length=100, default="this_is@n_example.com") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) phone = PhoneField(default="(XX)-XXX-XXX") def __str__(self): return f'{self.firstname}' forms.py class ClientForm(forms.ModelForm): class Meta: model = Client fields = ('firstname', 'lastname',"position",'country','email','phone') views.py @login_required def add_client(request): if request.method == "POST": client_form = ClientForm(instance=request.user, data=request.POST) if client_form.is_valid(): client_form.save() messages.success(request, 'You have successfully added a client') else: messages.success(request, "Error Updating your form") else: client_form = ClientForm(instance=request.user) return render(request, "account/add_client.html", {'client_form':client_form}) add_client.html {% extends "base.html" %} {% block title %}Client Information {% endblock %} {% block content %} <h1> Client Form</h1> <p>Please use the form below to add a new client to the database:</p> <form method="post" enctype="multipart/form-data"> {{ client_form.as_p }} {% csrf_token %} <p><input type="submit" value="Save changes"></p> </form> {% endblock %} Everything seems to be working fine, I can submit data in the website and I get a message stating that the the submission when fine, however, when I check the admin website and inspect the database, … -
Django Foreign Key Related Objects Not Saving Changes, Cannot Edit
I have two models, Movie and Review. Review has a foreign key field related to Movie. I have been trying to edit the Review objects associated with an instance of Movie. models.py class Movie(models.Model): title = models.CharField(max_length=160) class Review(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='reviews') author = models.CharField(max_length=150) active = models.BooleanField(default=True) views.py # Create and save movie object movie = Movie(title="Nightcrawler") movie.save() # Create and save two review objects review1 = Review(movie=movie, author="John", active=True) review2 = Review(movie=movie, author="Rob", active=False) review1.save() review2.save() print("Before: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.") active_reviews = movie.reviews.filter(active=True) print("There are " + str(len(active_reviews)) + " active reviews.") movie.reviews.set(active_reviews) movie.reviews.first().author = "Abby" # Try and save both objects just for good measure. # Not sure if it is necessary to do this. Does not # seem to work anyway movie.reviews.first().save() movie.save() print("After: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.") print("Author of the first review is: " + str(movie.reviews.first().author)) The output of the views.py code is as follows: Before: Nightcrawler has 2 reviews. There are 1 active reviews. After: Nightcrawler has 2 reviews. Author of the first review is: John I want and expected the changes made to movies.reviews … -
Django is not picking CSS file
Django is not picking CSS file from static folder, though its picking image file in static folder. here is my Django structure rootapp -settings.py -urls.py -wsgi.py app1 -views.py app2 -views.py template -app1home -app2home -base static -logo.png -style.css urls.py from django.views.static import serve urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^media/(?P<path>.*)$', serve, kwargs={'document_root': settings.MEDIA_ROOT}), re_path(r'^static/(?P<path>.*)$', serve, kwargs={'document_root': settings.STATIC_ROOT}) ] In base.html.I have {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> It is picking logo as follows in the base file <img src="{% static "logo.png" %}" alt="logo"></a> <h1>Disease Diagnosis via AI</h1> But not picking style.css file. CSS file looks like h1{ margin-top: 10px; color: red; } Settings file MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Also, media paths are working -
Django template: two different font sizes on same line
I'd like to be able to render two different font sizes on the same line using a Django template. Here's my code: <div> <h5>Details</h5> </div> <div> <h6>Creator By:</h6> {{ order.creator }} </div> <div> <h6>Category:</h6> {{ order.category }} </div> This is rendering as follows: Details Created By: Janice Category: Automotive ############################################# Notice that the variables are skipping to a new line. I would like to render these as follows (on the same line): Details Created By: Janice Category: Automotive Is this just a simple mistake I've made with the HTML? Or, is there some nuance I'm missing with the Django form? Thank you! -
How to get the related field of a related field in Django REST Framework serializers?
Imagine having three Django Models: class A: Susu = models.CharField() # props... class B: a = models.ForeignKey(A) Bar = models.CharField() # props... class C: b = models.ForeignKey(B) c_prop # props... I'd like to write a serializer for C objects, such that they are represented as { "c_prop": "Foo", "b" : { "Bar": "Agu" }, "a" : { "Susu", "Jaja" } } i.e. the foreign key of the B class is representated at the same level of nesting as the B object (instead of "within" B) I have these serializers: class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = ("Susu", ) class BSerializer(serializers.ModelSerializer): class Meta: model = B fields = ("a", ) class CSerializer(serializers.ModelSerializer): b = BSerializer class Meta: model = C fields = ('c_prop', 'b', 'a', ) # <-- How to get the 'a' here (not just the PK of 'a' but the nested object representation? -
Django authentication/user create functions
I'm trying to start a project in Django, where users can register on my site and subsequently login/logout when they visit it. I have found a template for a user creation view, that looks like this: from django.views.generic import CreateView from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login class CreateUserView(CreateView): template_name = 'register.html' form_class = UserCreationForm success_url = '/' def form_valid(self, form): valid = super(CreateUserView, self).form_valid(form) username, password = ( form.cleaned_data.get('username'), form.cleaned_data.get('password1') ) new_user = authenticate(username=username, password=password) login(self.request, new_user) return valid Now, I'm wondering why a call to authenticate with a non-existing username should create a new user. I'm trying to find any documentation for the imported functions authenticate and login, however, I can only find documentation for the User-model, AnonymousUser object, Permission-model, Group-model, some authentication backends and signals/validators, but I don't find any documentation for (standalone) functions authenticate and login. Can someone provide me the with a link to the relevant documentation or at least confirm that the way as they are used above is (still?) correct? -
Put the value of Not null in a field using Alterfield
In my Django project, I first added new fields to the project and set their null value to true, and then I wanted to set the Not null value for those fields via AlterField, but I was unable to do so. In this project, I manually created two migrations for these changes. 0002_edit_model: from django.db import migrations,models def excavating_information(apps, schema_editor): Person = apps.get_model('people', 'Person') #get data from fullname field full_name = [i.split(';') for i in Person.objects.values_list('fullname', flat=True)] full_name_finall = [f for i in full_name for f in i] #get data from information field information_field = [i.split(';') for i in Person.objects.values_list('information', flat=True)] information_field_final = [f for i in information_field for f in i] #Extract data from fullname first_name = [k[11:] for k in full_name_finall if k[1] == 'i'] last_name = [k[10:] for k in full_name_finall if k[1] == 'a'] #Extract data from information id_code = [k[8:] for k in information_field_final if k[1] == 'd'] born_in = [k[8:] for k in information_field_final if k[1] == 'o'] bith_year = [k[11:] for k in information_field_final if k[1] == 'i'] #final step for person,f, l, i, b, bi in zip(Person.objects.all(),first_name, last_name, id_code, born_in, bith_year): #update fields in person model person.objects.update(first_name=f, last_name=l, id_code=i, born_in=b, birth_year=bi) class … -
Optimizing Django with prefetch and filters in large table
I had a database in php/html using MySQL and am transferring this to a Django project. I have all the functionalities working, but loading a table of the data I want is immensely slow because of the relations with other tables. After searching for days I know that I probably have to use a model.Manager to use prefetch_all. However, I am not stuck on how to call this into my template. I have the following models(simplified): class OrganisationManager(models.Manager): def get_queryset_director(self): person_query = Position.objects.select_related('person').filter(position_current=True, position_type="director" ) return super().get_queryset().prefetch_related(Prefetch('position_set', queryset=person_query, to_attr="position_list")) def get_queryset_president(self): person_query = Position.objects.select_related('person').filter(position_current=True, position_type="president" ) return super().get_queryset().prefetch_related(Prefetch('position_set', queryset=person_query, to_attr="position_list")) class Person(models.Model): full_name = models.CharField(max_length=255, blank=True, null=True) country = models.ForeignKey(Country, models.CASCADE, blank=True, null=True) birth_date = models.DateField(blank=True, null=True) class Organisation(models.Model): organisation_name = models.CharField(max_length=255, blank=True, null=True) positions = models.ManyToManyField(Person, through='Position') # positions are dynamic, even though there should only be only one director and president at each given time, a onetoone model wouldn't work in this scenario objects = OrganisationManager() # The following defs are currently used to show the names and start dates of the director and president in the detailview and listview def director(self): return self.position_set.filter(position_current=True, position_type="director").last() def president(self): return self.position_set.filter(position_current=True, position_type="P").last() class Position(models.Model): POSITION_TYPES = ( ('president','President'), ('director','Director'), ) … -
Displaying javascript style alert after form submit in Django
I am creating a simple application in Django. I have a form on a page and after the form is submitted, I want to redirect the user to a new page and display a JavaScript alert like this. How would I go about doing this? My code is down bellow. This is the function that stores the form data and redirects to a new page, the new page only has simple html on it. def donate(request): if request.method == "POST": title = request.POST['donationtitle'] phonenumber = request.POST['phonenumber'] category = request.POST['category'] quantity = request.POST['quantity'] location = request.POST['location'] description = request.POST['description'] # New part. Update donor's stats. UserDetail.objects.filter(user=request.user).update(donations=F('donations') + 1) UserDetail.objects.filter(user=request.user).update(points=F('points') + (quantity * 2)) return render(request, 'dashboard.html', ) return render(request,'donate.html') I have done lot's of research but I can not find a logical solution to my problem. Past questions have asked me to use Django messages, which is something I don't want to use. Thank you to everyone who helps! -
Django App - I have a list of students which I upload within the app, how can I connect the student list with login so they only create new password
from django.shortcuts import render from .forms import csvForm from .models import csvList import csv from portal.models import Studentlist Create your views here. def upload_file_view(request): form = csvForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = csvForm() obj = csvList.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i==0: pass else: print(row) #studID = row[0] middlename = row[1] #User.objects.get(username=row[1]) gender = row[2].capitalize firstname = row[3] #User.objects.get(username=row[3]) tPeriod = row[4] unitNum = row[5] teamid = row[6] Studentlist.objects.create( id = int(row[0]), surname = middlename, title = gender, name = firstname, teachPeriod = tPeriod, unitCode = unitNum, teamId = teamid ) obj.activated = True obj.save() return render(request, 'home.html', {'form': form}) -
unexpected keyword argument
enter code here class Client(models.Model): enter code here name = models.CharField(max_length=100, verbose_name="Client name") enter code here description = models.TextField(verbose_name="Client say") enter code here image = models.TextField(upload_to="clients", default="default.png") enter code here def __str__(self): enter code here return self.name i'm getting a TypeError: init() got an unexpected keyword argument 'upload_to' -
unable to get related table field data using select_related django
using Select_related i got the query what exactly i need. but i unable to figureout how to see anyfield or all field of related tables. prod = ProblemProductBind.objects.all().select_related('prod_id') >>> print(prod.query) SELECT "repair_problemproductbind"."id", "repair_problemproductbind"."prob_id_id", "repair_problemproductbind"."prod_id_id", "repair_problemproductbind"."A_price", "repair_problemproductbind"."B_price", "repair_problemproductbind"."A_buying_price", "repair_problemproductbind"."B_buying_price", "repair_problemproductbind"."A_ISmash_price", "repair_problemproductbind"."B_ISmash_price", "repair_problemproductbind"."isLCD", "repair_problemproductbind"."askQuote", "repair_problemproductbind"."time_stamp", "products_products"."id", "products_products"."pName", "products_products"."cat_id_id", "products_products"."subCat_id_id", "products_products"."type_id_id", "products_products"."brand_id_id", "products_products"."pImage", "products_products"."weRepair", "products_products"."weRecycle", "products_products"."time_stamp" FROM "repair_problemproductbind" INNER JOIN "products_products" ON ("repair_problemproductbind"."prod_id_id" = "products_products"."id") -
How to reorder the fields when we have two forms of two models in Django?
How can I reorder the fields in the form of my Django models ? I have two models : Student inherited from the User class inherited from an AbstractBaseUser class. I want the student to register on my webpage having these fields in this order : firstname ; lastname ; address ; email ; password. But Firstname and Lastname are in the User class, address in the Student class, then email and password in the User class. How can I reorder them ? Here is my code : forms.py : class CreateUserForm(UserCreationForm): class Meta: model = CustomUser fields = ('firstname', 'lastname', 'email') class StudentForm(forms.Form): address = forms.CharField(max_length = 30) class Meta: model = Student fields = ['address'] models.py : class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email address', unique=True) firstname = models.CharField(max_length = 30, null = True) lastname = models.CharField(max_length = 30, null = True) class Student(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) address = models.CharField(max_length = 60, null = True) register.html : <div> <form method="POST" action="{% url 'register' %}"> {% csrf_token %} {{ form.as_p}} {{student_form.as_p}} <button class="btn btn-secondary"> Je m'inscris </button> </form> </div> -
How to make custom filter based on user
I have an application which is being used globally at my company. It is used to track internal hardware inventory. Each product is associated with a category (for example a product could have a category of 'cable', or 'development kit', or 'PC peripheral'). Now, each category is associated with a location (for example 'Boston', 'Budapest', and so forth). I have extended the user model in django to allow for a location to be associated with each admin user. I want to create a dropdown list filter in the admin space for each user. The user should be able to filter by product categories, but only the categories with the same location as the user. models.py ##product model class dboinv_product(models.Model): pk_product_id = models.UUIDField( default = uuid.uuid4, primary_key=True, null=False ) product_creation_time = models.DateTimeField( auto_now_add=True, null=True ) product_name = models.CharField( max_length=50, null=False ) product_description = models.CharField( max_length=500, null=True ) current_qty = models.IntegerField( null=False ) fk_location_name = models.ForeignKey( dboinv_location, verbose_name="Location name", default='Boston', on_delete=models.CASCADE, null=True, blank=True ) fk_product_category = models.ForeignKey( dboinv_product_category, verbose_name='Product category', on_delete=models.CASCADE, null=True, blank=True ) def __str__(self): return f"{self.product_name}, {self.fk_location_name}" class Meta: db_table = "dboinv_product" verbose_name = "Product" managed = True ##category model class dboinv_product_category(models.Model): pk_category_id = models.UUIDField( default = uuid.uuid4, primary_key=True, null=False … -
Session variable (Django) in one route exists, and in other is None
Currently I'm working on a project where I'm using React as frontend and Django as backend. In react i created a login page, where I through axios send files to django, and in this route index i sent all the information from the login page, and define a session variable reqeuset.session['id']=150 in it. But when i call reqeust.session['id'] in a diffrent route, it says that it is type None. This is the code: @api_view(['POST']) def index(request): data=request.data.get('data') korisnik = Korisnik.objects.filter(korisnicko_ime=data.get('user'), if korisnik.exists(): korisnik_json=serializers.serialize('json',korisnik) request.session['id']=150 print(request.session['id']) # if not request.session.session_key: # request.session.create() return HttpResponse(korisnik_json) else: return HttpResponse(status=404) @api_view(['GET']) def korisnik(request,id): print(request.session.get('id')) korisnik=Korisnik.objects.filter(pk=id) korisnik_json=serializers.serialize('json',korisnik) return HttpResponse(korisnik_json) This is the output from python console Image Also note, I'm using django restframework. Did anyone, have this problem before, any help is appreciated. -
How to display items in a row of 4 across using django, html, and python
this is my code. I want the items to be displayed horizontally. I've tried changing the col-md-3 and still no luck <title>Document</title> </head> <body> <div class="container"> <div class="row"> {% for product in product_objects %} <div class="col-md-3"> <div class="card"> <img src="{{ product.image }}" class="card-img-top"> <div class="card-body"> <div class="card-title"> {{ product.title }} </div> <div class="card-text"> {{ product.price }} </div> </div> </div> </div> {% endfor %} </div> </div> </body> </html> -
How can i pass a Django form to Html Asynchronously with intial data
I am representing data in a table and taking input for new data using a form on the same webpage. In my table at the end column, there is an update button for each row. When I will click the button, I want the existing form will populate with the data of the row. I want to update the data of a selected row asynchronously. I did it quite well with regular Django. But when I tried to do it with ajax/jquery. I have encountered a problem passing the form with populated data to HTML/script(Django view to frontend). I have added few lines of code below. Here is my Django view, def update_view(request,pk): p = People.objects.get(pk=pk) if request.method == 'POST': form = RecordUpdateForm(request.POST,instance=p) if form.is_valid(): form.save() else: form = RecordUpdateForm(instance=p) return !!! here is the url path, path('<int:pk>/update_view',views.update_view,name="update-view"), -
Cannot Debug Django using pdb
I am trying to add a breakpoint() to a particular line in a Django code which is running on an ec2 instance. I have tried ipdb, pdb tried import pdb;set_trace() it quits giving a BdbQuit error. tried simply adding breakpoint This simply gets ignored None of them stop the code. If I run the code like this python -m pdb manage.py runserver , it immediately drops into pdb and fails after executing 2 lines. How exactly should I use pdb in Django correctly? Old answers don't work. -
Filtering parent/child using NestedTabularInline in Django
Stuck in getting conceptually my head around a Django/ORM problem for a few days. Searching online (stackoverflow) didn’t address my problem. Furthermore I’m quite new to Django and Python and trying to understand the concepts of abstract models, multitable inheritance and proxy models but I don’t think that’s the solution. Outline: I’ve a general description of a activity/method/task model which describes a general assembly instruction. See my Activity/Method/Task/TaskImage model. On a actual product I want to execute a plan, in which I concretize a series of activity steps, hence my PlanActivity and PlanMethod models. Moreover for each actual plan I want to assign a bill of materials to make the product (therefore the TaskBOM). For convenience I’m heavily using NestedTabularInline for both drag/drop and inline properties. My problem is a bit twofold: Any activity step can have only one single method (Q1) and the available method’s need to be filtered (Q2) on it’s parent (activity). The tasks need to be filtered on the same way based on it’s parent (method). I think/hope my model is sane (thus no need for abstract models, multitable inheritance and proxy models) and I believe I need to use get_queryset or formfield_for_foreignkey functions in some … -
How to Remove " Password Condtions text " in django crispy form
I have added Password and using django crispy form. But can anyone help me how to remove the Password conditions text? Is there any easy way to remove """" Your password can’t be too similar to your other personal information. Your password must contain at least 8 characters. Your password can’t be a commonly used password. Your password can’t be entirely numeric. New password confirmation* "" enter image description here this text