Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django with Apache upload file to project get SuspiciousFileOperation Exception
I want to upload file to project/static/uploads get an error. SuspiciousFileOperation at /admin/myvideo/videomodel/add/ The joined path (D:\Web\pyproject\xxm_hrproject_video\src\static\uploads\2499be8ca837405aa440a4a56065bbb0.mp4) is located outside of the base path component (D:\Web\Apache24) If upload to apache path will not get any error. Django project path is D:\Web\pyproject\xxm_hrproject_video\src Apache path is D:\Web\Apache24 models.py from uuid import uuid4 from django.conf import settings class VideoModel(models.Model): def wrapper(instance, filename): # return r'D:\Web\Apache24\static\uploads\123.mp4' will not get any error return r'D:\Web\pyproject\xxm_hrproject_video\src\static\uploads\123.mp4' file = models.FileField(upload_to=wrapper) -
Django: How to calculate total hour in django model [duplicate]
I have an Overtime model. I want to calculate between start_time & end_time. and set result in total_hour field. class Overtime(models.Model): employee = models.ForeignKey(Employee,on_delete=models.CASCADE) start_time = models.DateTimeField() end_time = models.DateTimeField() total_hour = models.IntegerField(editable=False) How can I do that ? -
How to assign the specific path to store the Django Group migration file
There is currently an existing Django system, I want to add some fields to its Group, but other tables were relation Group already, so I use add_to_class that's success to add field. But I have the problem about migration file, the Group's new migration file was stored in {package path}/djano/contrib/auth/migrations, But I want to manage those files from our self, Is possibility assign the new path to store those migration files? Because we need these files for deployment. -
Django templates: block tag
listTemp.html {% extends "base_generic.html" %} {% block content %} <h1>{% block h1 %}{% endblock %}</h1> <style type="text/css"> a:link {color: black;} /* unvisited link */ a:visited {color: black;} /* visited link */ a:hover {color: black;} /* mouse over link */ a:active {color: black;} /* selected link */ </style> {% if list_list %} {% for x in list_list %} <a href="{% url '{% block modelName %}{% endblock %}-detail' {% block modelName %}{% endblock %}.pk %}" style="border:1px solid black;padding:5px;margin-left:40px;margin-bottom:20px"><strong>Name:</strong> {% block modelName %}{% endblock %}.firstName } </a> {% endfor %} {% else %} <p>{% block modelName %}{% endblock %} database is empty.</p> {% endif %} {% endblock %} client_list.html {% extends "listTemp.html" %} {% block h1 %}Clients{% endblock %} {% block modelName %}client{% endblock %} This is my first Django project and my first time working with HTML so my bad if it is obvious. I know what I have above is incorrect but how can I implement it? I have listviews and detail views for many models and they all have the exact same layout and the only difference in the files is the model name such as client.firstName and url 'client-detail' vs contractor.firstName and url 'contractor-detail' -
How can I store a complaint made by a user in my admin panel by django
what do I write in my views.py and forms.py to store the complaints by a user: This is how my site looks and this is where the users can input complaints. How can i save those complaints to later display, edit or delete them accordingly. How can I save those complaints in form of list in the admin panel. models.py: class Complaints(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.BooleanField(default=False) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title What do I write in my views.py and forms.py to do this. Please help me. The basic function is to accept complaints so that associated people can receive it and resolve the comlpaints accordingly. How do I make the views and forms so that we can accept these complaints and store them somewhere accordingly? -
How to add user roles on Signup?
my models.py ROLES = ( (1, 'student'), (2, 'creator'), (3, 'mentor') ) class User(AbstractUser): role = models.PositiveSmallIntegerField(choices=ROLES, default=1) forms.py ** class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) views.py def user_register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('login') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) I want to assign a role to every user which signs up, to make some permissions to restrict some type of users, i want t know how to add that role field in the signup so that a role can be given when a user registers and then permissions can be made accordingly, or if there is some better way to do it -
Why getting PostForm' object has no attribute 'user?
I am working on a small project containing two models User and Post.And a user can have multiple posts. I have created a custom form PostForm. When ever i am submitting the form it showing me the following error:- 'PostForm' object has no attribute 'user' views.py:- def add_post(request): print("addpost runn") if request.method == 'POST': post_form = PostForm(request.POST) print(request.POST) print("if part") if post_form.is_valid(): print(post_form) post_form.save(commit=False) post_form.user = request.user post_form.save() else: print("else part") post_form = PostForm() return render(request, "addpost.html", {"form": post_form}) forms.py:- class PostForm(forms.ModelForm): text = forms.CharField(label="Write Your Text Here", max_length=200, widget=forms.Textarea(attrs={'rows': 3})) created_at = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M:%S'], widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M:%S')) updated_at = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M:%S'], widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M:%S')) class Meta: model = Post fields = ['text'] def save(self, commit=True): print(self.cleaned_data) post = Post.objects.create_post( self.cleaned_data['text'], datetime.datetime.now(), datetime.datetime.now(), self.user, ) return post manager.py:- class PostManager(BaseUserManager): def create_post(self, text, created_at, updated_at, user, **otherfields): print(created_at) print(updated_at) print(text) post = self.model(text=text, created_at=created_at, updated_at=updated_at, user=user) post.save(using=self._db) return post -
Django elastic search consuming lot of memory
I have an EC2 instance having 32 GB RAM and I am using Django Elasticsearch DSL to use elastic search in Django for searching in Model objects. I have containerized the elastic search server. Below is the code from the docker YAML file to build the image. elasticsearch: image: elasticsearch:7.12.1 container_name: zinia-backend-elasticsearch ports: - "9300:9300" - "9200:9200" environment: discovery.type: "single-node" restart: unless-stopped networks: - backend But currently, I am facing the issue of high memory consumption by elastic search it is taking up to 16.5 GB of memory, and when other containers need more ram the system runs out of memory and stops responding and this becomes a critical issue for our team and project. Please, someone, guide the way to control it. Thanks in advance. -
how to get bytea images from postgresql database and display them in django?
This is how I created a table: sql_create_table = ''' CREATE TABLE IF NOT EXISTS images ( image_id text PRIMARY KEY, image bytea, name text )''' I have images and text data store in excel. I used openpyxl python library to read the excel data and insert them in the Postgres database. I looked at the database table and saw the image store as binary data. Now, How should I get bytea data and display them using HTML. Store.html <div class="w3-container w3-center"> {% load static %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <label>Image</label> <input type="file" name="image" value="{{image.0}}" class="file-upload"> <label>Name:</label> <input type="text" name="name" value="{{image_id.1}}"><br> <label>url:</label> <input type="text" name="url" value="{{name.2}}"><br> <button type="submit" value="update" name="update" class="file-upload-btn">Upload</button> </form> </div> Python libraries I used: import os from django.shortcuts import render, redirect import psycopg2 from openpyxl import load_workbook from openpyxl_image_loader import SheetImageLoader import PIL.Image as Image import base64 I connect to Postgres and get the table data from python. Look at my code, I convert binary to base64 since HTML doesn't support binary data. views.py def images_display(request): connection = connect_to_db() cursor = connection.cursor() sql = 'SELECT * FROM images;' cursor.execute(sql) results = cursor.fetchall() one_row = [] data = [] for value in results: for i … -
wanna join all tables in django
yet I'm a noob on Django. but I want to join every table in Django models. Here is some example on models.py (use inspectdb from MySQL ... cuz unable to add column(field) in Model) class Title(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(db_column='__title__', max_length=255) pages = models.IntegerField(db_column='__pages__') type = models.CharField(db_column='__type__', max_length=10) url = models.URLField(db_column='__url__', max_length=800) class Meta: managed = False db_table = 'title_' def __str__(self): return self.title class Author(models.Model): author_id = models.BigAutoField(db_column='artist_id', help_text='artist guestbook', primary_key=True) title_id = models.ForeignKey("Title", on_delete=models.CASCADE, db_column='Title_id', related_name="author_index") author = models.CharField(db_column='__author__', max_length=60) class Meta: managed = False db_table = 'author_' def __str__(self): return self.author and Series, Categories, etc.. has a foreign key to Title like Artist. I want to execute Django like SQL select t.id, t.__title__, group_concat(distinct ta.__author__ separator ', ') as __author__, (omitted) group_concat(distinct t2.category separator ', ') as __category__, from title_ t join artist_ ta on t.id = ta.Title_id (omitted) join (select title_id, concat(__prefix__, ': ', __name__) as category from category_) t2 on t.id = t2.title_id group by t.id order by t.id desc; but it's hard for Django.. plz help me. if title and artist like id title 1 python 2 java and title_id author 1 A 1 B 2 C Joined table on Django Models … -
Djangoissue with angular
I am trying to deploy my application using below tech stack. angular ( frontend ) and django ( backend ). When i am trying to access over https my app the backend is giving following error Not Found: / [05/Jul/2021 00:57:08] "GET / HTTP/1.1" 404 2356 [05/Jul/2021 02:42:50] code 400, message Bad request version ('À\x14À') [05/Jul/2021 02:42:50] You're accessing the development server over HTTPS, but it only supports HTTP. -
Dependent drop down on filter
Previously I implemented a dependent drop down on my model form (car manufacture to manufactures models) based on this blog post. Now I have a section on my site for users to view the cars with a filter for the manufacture to model. The only issue is that if you select a manufacture you have a list of every model not just the ones that are linked to that manufacture. If you could please point me in the right direction on how I would go about creating a dependent drop down on a filter. filter class carFilter(django_filters.FilterSet): class Meta: model = Post fields = 'manufacture', 'model' -
Django Foreign Key ["Incorrect type. Expected pk value, received str."]
The Company table has the basic contact information of the company, and the Address contains the address and geolocation of the company. These two tables are connected with a foreign key named "company_name," which is neither a primary key of both tables. I inserted some mock data of a company named "FF2" into the company table, it went great. However, when I attempted to insert "FF2" with its mock address into the Address table, I failed and received this: company_name: ["Incorrect type. Expected pk value, received str."] I tried every solution I found online, but none of them worked. Please help and be specific as possible, thank you so much!! model.py: class Address(models.Model): city = models.CharField(max_length=200) state = models.CharField(max_length=200) zip = models.CharField(max_length=20) address1 = models.CharField(max_length=200) address2 = models.CharField(max_length=200, blank=True, null=True) company_name = models.ForeignKey('Company', models.DO_NOTHING, db_column='company_name') lat = models.DecimalField(max_digits=50, decimal_places=6) long = models.DecimalField(max_digits=50, decimal_places=6) class Meta: managed = False db_table = 'address' class Company(models.Model): company_name = models.CharField(unique=True, max_length=200) contact_name = models.CharField(max_length=100) phone = models.CharField(max_length=100) email = models.CharField(max_length=100) website = models.TextField() class Meta: managed = False db_table = 'company' views.py: class AddressView(APIView): serializer_class = AddressSerializer def get(self, request): address = [ {"city": address.city, "state": address.state, "zip": address.zip, "address1": address.address1, "address2": address.address2, "company_name": … -
What should I library should I use for authorize.net in django
there. I've been working on my friend's dad's restaurant website which is using django 3.1. I successfully integrated PayPal to the site, and I plan to add Authorize.net as well. I started researching, but I only found django-authorizenet, which does not support django 3.1. So the question is WHAT LIBRARY SHOULD I USE FOR MY SITE. Thank you in advance. -
How to filter sentences from an list of words in array in Django
I create like books site, I want to show related book by the title of this book, by at least 2 words to be accurate in suggest books, Firstly I split the title of the current book into an array of words like ['good', 'book', 'by', 'mickle'] and filter the books using title__icontains but it shows an empty list My question is how I can filter sentences from a list of words in an array? and if there is a better way to get the related objects by title at least two similar word from the title My Book title class Book(models.Model): author = models.models.ForeignKey(Account, on_delete=models.CASCADE) title = models.CharField(max_length=90, null=True, blank=True) My function to get the related books by title. class BookRelatedObj(ListAPIView): serializer_class = BookRelatedSerializer lookup_field = 'title' def get_queryset(self): book_pk = self.kwargs['pk'] book = Video.objects.get(pk=book_pk) lst = book.title split = lst.split() print(split) return Book.objects.filter(title__icontains=[split]) -
Trying to print out result from query set.. returning a tuple
I am trying to print out the query set just to determine what is being returned from the query but it is returning the error "str returned non-string (type tuple)" File "/Users/richard/Documents/FordHack/backend/fleetCommand/views.py", line 20, in findExistProp print(OrgList) File "/Users/richard/Documents/FordHack/fordHack/lib/python3.9/site-packages/django/db/models/base.py", line 521, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) TypeError: __str__ returned non-string (type tuple) My model is below: class FleetCommandModel(models.Model): vehicleId = models.CharField(max_length=255, blank=False, editable=False) uuid = models.CharField( max_length=32, default=hex_uuid, editable=False, unique=True, primary_key=True ) req_date = models.DateTimeField(auto_now_add=True, editable=False) ok_bySuper = models.BooleanField(editable=True, default=False) ok_byCustRep = models.BooleanField(editable=True, default=False) initiated_byWho = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, on_delete=models.DO_NOTHING, related_name="initiated_byWho") Super_Ok = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, editable=False, on_delete=models.DO_NOTHING, related_name="Super_Ok") CustRep_Ok= models.ForeignKey(settings.AUTH_USER_MODEL, null=True, editable=False, on_delete=models.DO_NOTHING, related_name="CustRep_Ok") active_Req = models.BooleanField(editable=True, default=True) req = models.CharField(max_length=255, blank=False, editable=False) def __str__(self): return (f'vehicleId: {self.vehicleId}.',f'uuid: {self.uuid}.') My function to print out the query is below: def findExistProp(self, vehicleId): Org_obj = FleetCommandModel.objects.filter(active_Req=True).filter(vehicleId=vehicleId) if Org_obj: exist = True OrgList= list(Org_obj) print(OrgList) return {"exist":exist, "Org_obj":OrgList} else: return {"exist":False} -
Running Scrapy from a Django Channels -based script
I wanted to add an async behavior while scraping single items from a URL using a Scrapy spider. Having Django Channels working great for other projects, I thought I might go with it instead of a similar server like scrapyd. Although scrapy does everything expected; -generating a request, -scrape its content, -saving it to the DB, etc., it is generating an error that resulting in the Django channels socket failing before sending anything back to the client. Here is the error message I am receiving inside my terminal: Web_1 | 2021-07-05 22:24:32 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) web_1 | 2021-07-05 22:24:32 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023 web_1 | 2021-07-05 22:24:32 [aioredis] DEBUG: Cancelling waiter (<Future cancelled>, [None, None]) web_1 | 2021-07-05 22:24:32 [aioredis] DEBUG: Waiter future is already done <Future cancelled> web_1 | 2021-07-05 22:24:33 [daphne.server] ERROR: Exception inside application: Task got bad yield: <Deferred at 0x7fddc8564f10> web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in __call__ web_1 | return await self.application(scope, receive, send) web_1 | File "/usr/local/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ web_1 | return await application(scope, receive, send) web_1 | File "/usr/local/lib/python3.8/site-packages/channels/routing.py", line … -
count after difference between two columns with django
I have a table with the following data. table_1 col_a col_b 1 2 0 1 2 0 I want to add a with b. I can do this with annotate: table_1.objects.annotate(diff=F('col_a ')+F('col_b ')) what I can't do is apply a filter. Example. count where col_a + col_b is greater than 2: Desired result: 1 Can you help me? -
Value assigned to the function is not rendered
In class NewEntry, there is a variable called dis has value "d" assigned. In the function create, the value is set as "test". However, string "test" is not rendered. Why? I have tried global dis in the function but still not render "test" I have also tried it in a couple of other ways but I can't get it to change before it is sent to the client side. class NewEntry(forms.Form): dis = "d" title = forms.CharField(label="Title") title.widget = forms.TextInput(attrs={ "value": dis }) contentArea = forms.CharField(label="Content", widget=forms.Textarea()) This function should be able to set the value for the class. def text(self,text): self.dis = text class searchEntry(forms.Form): q = forms.CharField(label="", widget= forms.TextInput(attrs={'placeholder':'Search Encyclopedia'})) def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def create(request): if request.method == "POST": form = NewEntry(request.POST) form.dis = "test" if form.is_valid(): title = form.cleaned_data["title"] contentArea=form.cleaned_data["contentArea"] if (util.get_entry(title) is None): messages.success(request, f'"{title}" is created!') util.save_entry(title, contentArea) messages.success(request, f'"{title}" is created!') ##return HttpResponseRedirect(reverse('entry',kwargs = {'title':title})) return redirect('entry',args=[title]) else: messages.info(request,'Title exists') return render(request,"encyclopedia/create.html",{ "form":form }) return render(request, "encyclopedia/create.html",{ "form":NewEntry(),NewEntry.text(NewEntry(),"test"):"test" }) -
How to show different messages based on Query strings in Django?
I have a login page. It has a message that I can dynamically generate based on request method by configuring the view. I also have a logout button custom admin panel. That logout button redirects to login page. All I want is to show two different messages in the login page. One will be general message when you go to login page and another one when you come to login page by clicking on logout (redirected to login page) Both are GET method. So how will I make it possible? I got one response asking me to add query string after in the logout redirect url like 'login?logOut=True' and then use it as a parameter in view. But I don't know how to do that. Please help. -
Pass id from button in template to Django View
im on my 2nd week trying to learn Python+Django and wanted to make a litte project. But im getting stuck on some JS-bs. I don't know JS well at all and would need some help. I want to pass the ID ("Value" in the button) of the selected button as data in the Ajax function, but can't really get this to work. How do i pass the value to the Ajax function? I want to use the value in the "id" variable in views. Thank you! HTML - I want to pass an ID of selected pressed button. {% for product in products %} <button type="button" id="submit" class="btn" value="{{product}}">{{product}}</button> {% endfor %} Javascript To the Ajax POST function here. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> var data = new FormData(); $(document).on('click', '#submit', function(e) { data.append('action', 'toggle_button') data.append('csrfmiddlewaretoken', '{{ csrf_token }}') $.ajax({ type: 'POST', url: '{% url "toggle_button" %}', data: data, cache: false, processData: false, contentType: false, enctype: 'multipart/form-data', }) }) </script> Django view file from django.http import HttpResponse, request from django.shortcuts import render from django.http import JsonResponse def home_view(request): context = { "products": ["Button1", "Button2", "Button3", "Button4"], } return render(request, "home.html", context) def toggle_button_view(request): if request.POST.get('action') == 'toggle_button': token = request.POST.get('csrfmiddlewaretoken') id = … -
How can i use Django signals for price calculations for items?
Info: Hello! i am trying to make an monthly installment app using Django my models are fine but i don't understand how can i calculate items price using Django signals i want to save Property calculate price in database. I want to calculate property price with Payment amount and get remaining price and save into database. Models.py class Property(models.Model): area = models.CharField(max_length=255) price = models.IntegerField(default=0) class Customer(models.Model): name = models.CharField(max_length=255) prop_select = models.ForeignKey(Property, on_delete=models.SET_NULL, null=True) class Payment(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, blank=True, related_name='payment') amount = models.IntegerField(default=0) remaining = models.IntegerField(default=0) -
unable to implement basic login in the django framework
I am trying as hard as I can to learn to concept of authentication within the Django framework. I am reading the documentation and trying to code similar which will help me get the subject. At the moment I am trying to implement a simple login which redirects to a page. If the user is logged in he should see a message other wise he should see a different message. This is my code. I have made a simple login form class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput()) this is my login view def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/users/success/') else: return redirect('/users/success/') else: form = LoginForm() return render(request, 'testauth/login.html', {'form': form}) (I know the above code is a little bit redundant ... at the moment this is not so important) and this is the success view def success_view(request): print(request.user) if request.user.is_authenticated: return HttpResponse("logged in") else: return HttpResponse("you are not logged in") The problem is, I always get the "logged in" message even with users which do not exist. I tried restarting the server my … -
What would be a good way to create a model for bunch of check boxes in Django?
I'm trying to create a model for these check boxes below. There is also dosage text input next to each check box. I think there should be a better way to save it to database rather than creating field for each check box and dosage text field in the model. -
Logging/print statements do not work in subprocess in Python Django application
In my Django project I have a file called views.py. There are a couple of logging/print statements there, which work fine. However, views.py calls another python script using subprocess’s run method. Surprisingly, no logging/print statements work in that script. This is how run() is being called: out= run([sys.executable, /path/to/script.py, param1, param2], shell=False, stdout=PIPE) Logging is configured like this in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'my_logger': { 'handlers': ['console'], 'level': 'INFO', }, }, } Please advise what is going wrong. Thanks.