Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Comments not visible in template even though they are saved in the database
I currently have 2 models in my App, one for uploaded files and another one for comments. I've figured out how to implement the forms on the same page and it seems to be working but for some reason, the submitted comments aren't being shown and I have no idea on how to accomplish that. Should I provide the comments in a return or seeing as that there is a ForeignKey in the Comment model this is not neccesary and the comments can be accessed through each file? # Model for all uploaded files class Uploaded(models.Model): objects: models.Manager() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users") time_uploaded = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=100) file = models.FileField(upload_to=MEDIA_ROOT) admintags = TaggableManager(blank=True, through=AdminTagsAll, verbose_name="Admin Tags") usertags = TaggableManager(through=UserTagsAll, verbose_name="User Tags") additional_description = models.CharField(max_length=50, blank=True) def __str__(self): return f"{self.description} {self.file}" # Model for comments class Comment(models.Model): objects: models.Manager() file = models.ForeignKey('Uploaded', on_delete=models.CASCADE, related_name='comments') text = models.TextField() def __str__(self): return self.text HTML template: {% for comment in comments %} <div style="border:1px solid silver; border-radius:15px; padding:15px; margin:10px 0px;"> <p class="mb-auto" style="font-size:15px;">{{ comment.text }}</p> </div> {% empty %} <div style="border:1px solid silver; border-radius:15px; padding:15px; margin:10px 0px;"> <p class="mb-auto" style="font-size:15px;">No Comments</p> </div> {% endfor %} Views.py def index(request): url_parameter = request.GET.get("q") user … -
Django Custom User UUID Duplicated (cached?)
I'm Using Django with a custom user model with custom UUID and custom user manager: class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=generate_id(), editable=False) # ... As you can see, I'm NOT using default=uuid4(). Instead I've made a function my on my own that uses uuid() to generate the custom id also using the timestamp: from datetime import datetime as dt from uuid import uuid1, uuid3, uuid4 def generate_id(): timestamp = str(dt.timestamp(dt.now())) return uuid3(uuid4(),timestamp) Now if I open the interactive shell: python manage.py shell and I call my function several time, this is what I get: >>> generate_id() UUID('bd8279f1-9b4b-3d7d-8932-f9e725f17045') >>> generate_id() UUID('0c2ec2ad-b062-3915-a9e9-22842c6f5ea2') >>> generate_id() UUID('2289202b-f252-3b27-bcae-cd44825bf4e0') >>> generate_id() UUID('88676ea9-4902-36ac-857d-929cb133089c') >>> generate_id() UUID('4a18b33e-12f0-3803-8ff0-0c4f0d1c849c') but when I try creating 2 users: from users.models import CustomUser >>> one = CustomUser.objects.create_user(email='hhh@jaja.com',password='JJlsaks16112') >>> two = CustomUser.objects.create_user(email='ttth@jija.com',password='JJlsaks16112') Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/usr/local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.IntegrityError: (1062, "Duplicate entry 'b448f583acfb31b7955926689b60f28a' for key 'PRIMARY'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File … -
How to set backgroundcolor and border for each array element using javascript or jquery?
I am trying to set separate background and border for each element in the array using JavaScript something like this. Until now what I have done outputis below. As I add a new element to the array, it will stretch the background. let skills = []; function displayname() { console.log(document.getElementById("namehere").value); x = document.getElementById("namehere").value; skills.push(x); console.log(skills) document.getElementById("skill-set").innerHTML = skills document.getElementById("skill-set").style.border = "1px solid blue"; document.getElementById("skill-set").style.backgroundColor = "yellow"; document.getElementById("skill-set").style.padding = "5px"; document.getElementById("skill-set").style.display = "inline-block"; document.getElementById('namehere').value = " "; } <label>Enter the skills: </label><br> <input type=t ext id="namehere" onchange="displayname()"> <div id="skill-set"></div> -
Django CORS Headers not Working as Suggested in Docs
The DOCS for Django Cors Headers, https://pypi.org/project/django-cors-headers/ , clearly states that "CORS_ALLOWED_ORIGINS: Previously this setting was called CORS_ORIGIN_WHITELIST, which still works as an alias, with the new name taking precedence." From the code if I use CORS_ORIGIN_WHITELIST my requests go through, but if I use CORS_ALLOWED_ORIGINS, while commenting out CORS_ORIGIN_WHITELIST, my requests are blocked. In my options request I am not getting any response and the subsequent POST request is blocked. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #APPS .... #ADDL FRAMEWORKS 'corsheaders', 'rest_framework', 'oauth2_provider', 'django_extensions', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:3000', 'http://localhost:3000' ] # CORS_ALLOWED_ORIGINS = [ # 'http://127.0.0.1:3000', # 'http://localhost:3000', # ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] -
How to display related attribute and values properly with ajax?
Here based on the class selected I want to display it's related attributes on the select option with ajax and jquery(it works fine) and on the side of select option there is a input field for attribute's related values(here is the problem only while displaying in the template with ajax, in the view it is printing the related values). Below is my ajax call and there is a problem while displaying attributes related values in the side of the attribute select option. After selecting class it displays related attributes correctly but the related attribute's related values are not displaying. The error is Uncaught ReferenceError: Attributes is not defined at HTMLSelectElement.onchange views.py class_id = request.POST.get('class_id') qs = VariantAttribute.objects.filter(class=class_id) attribute_data = [] attribute_data_values = [] for obj in qs: attribute_data.append(obj.attribute) attribute_data_values.append(obj.attribute.attributevalues_set.all()) data = serializers.serialize('json', attribute_data) print(data) values = serializers.serialize('json', attribute_data_values) print(values) response_data = { 'attribute': data, 'values': values } return HttpResponse(json.dumps({'data': response_data})) html <td><select class="form-control attribute-options" name="name" type="text"> {% for attribute in attributes %} <option value="{{attribute.pk}}">{{attribute.name}}</option> {% endfor %} </select></td> <td><input class="form-control attribute-input" name="value" type="text"></td> script(main problem is here) function Attributes(value){ $.ajax({ url: '{% url "get_attribute" %}', data:{ 'class_id' : value, }, dataType: 'json', success: function(response) { // console.log(response.data.attribute) var attribute = … -
len() of unsized object in Django template
Basically, I have store array [{'A': 'aa'}, {'B': 'bb'}, {'C': 'cc'}] in django model CharField(). In Templates {% for arr in my_array %} {{ arr }} {% endfor %} But, I got [ { ' A ': ' a a ' }, { ' B ': 'b b ' } , { ' C ': ' c c ' } ]. In views.py print(type(my_array)) # Output: <class 'str'> Then, I edit my code as: import numpy as array my_array = array.asarray(my_array) print(type(my_array)) # Output: <class 'numpy.ndarray'> Then, I got an error at browser: len() of unsized object so, how can I fixed this error? -
Setup Jetsi in back-end with connection monitoring with Django
I want use jitsi meet for a project. I have to task: Monitoring internet connection of clients inside a room Saving some data inside the browser cookies or opening a session for each client For the first task I need to ping the clients in some intervals to check the internet speed and also if a client gets disconnected I need to log it somewhere in the back-end server( Due to bad internet connections in my country this kind of monitoring is necessary for me). Also Might to write to browser cookies for some other purpose. I want to use Django for my web application.I know I have to use Jitsi meet api but unfortunately there is no good tutorial or answer for my work and couldn't find anything in the documentation. There are many codes describing how to implement the api in JS but that's mostyl front-end and custom UI or configs. Also I know I have to install jitsi-meet in a VM and give the domain to the web application. How ever I do not know the back-end development processes and since I need to monitor and probably save the data in a DB I really need help. … -
How to place a button in each row of table in django management form
In my Django application, I have a form with Parent/Child model objects laid out using loop. To dynamically add child form instances, I am using Django dynamic formset. Every thing works fine including saving of user inputs without hassle. So far, so good. However, now my user wants that I place one button before a particular field (spl_instructions) in each of the dynamically rendered rows (of fields). The instant field spl_instructions (of the child table) is a CharField of 255 chracters and is being rendered as Textarea in the page. The "button" is intended to be used to open the field spl_instructions if and when there is a need to enter text in the field. This route is being taken to conserve space. models.py class ProductAssy(models.Model): prod_assy_id = models.AutoField(primary_key=True, ...) prod_assy_num = models.CharField(max_length=24, ...) prod_assy_type = models.ForeignKey(MaterialType, ...) short_text = models.CharField(max_length=55, verbose_name="Description") # ... Rest of the fields class BillOfMatlItems(models.Model): bom_item_id = models.AutoField(primary_key=True, ...) prod_assy_id = models.ForeignKey(ProductAssy, ...) short_text = models.CharField(max_length=55, verbose_name="Description") spl_instructions = models.CharField(max_length=255, ...) # ... Rest of the fields forms.py class CreateProdAssyForm(forms.ModelForm): class Meta: model = ProductAssy fields = (...) class CreateAssyBomForm(forms.ModelForm): class Meta: model = BillOfMatlItems fields = (...) widgets = { 'short_text': forms.TextInput(attrs={'style': 'width:300px; text-align:right;'}), … -
Django use context variable passed from view in the url pattern
I have a view function passing in an integer as a context and renders a HTML file. def youtube(request, gateid=0): print(gateid) return render(request, "streamapp/youtube.html", {'gateid': gateid}) Inside the HTML file called youtube.html, I want to use this argument gateid inside a URL pattern which calls in another view. existing code: <a href='{% url 'video_feed' gateid=0 %}' /> So instead of hard coding the gateid=0 to zero in the above <a /> tag, I wanna make use of the context variable passed, how do I do that? -
Problems to load an image from my context in django
{% load static %} I want to load an image from my static files but the name of the image depends of my context The data come from Open Weather map API -
How to get time slot in django for doctor appointment
I have 2 models Schedule and Appointment.How can i get the duration of doctor in a diffrent time slots for 15 minutes.I am getting blank in this models. class Schedule(models.Model): doctor=models.ForeignKey(Doctor) open=models.TimeField() close=models.TimeField() class Appointment(models.Model): patient=modles.ForeignKey(Patient) doctor=models.ForeignKey(Doctor) date=models.DateField() time_slot=models.TimeField() -
What's the most pythonic way to parse multipart/form-data with array-like name structure in Django?
I have a structure like this: ------------------------------69f765a4d9fa Content-Disposition: form-data; name="data[4]" message ------------------------------69f765a4d9fa Content-Disposition: form-data; name="data[5]" message ------------------------------69f765a4d9fa Content-Disposition: form-data; name="data[6]" message How should I parse it to have an array of messages to parse it further? I use Django and I suppose I should use Django forms to do this but I've not seen anything regarding this in the docs or here on this site. -
Django ORM. How to distinguish, recognize or identify objects from each other
As title describes, I want to distinguish objects from each other. For example, I have Application objects and AdmissionBase objects. Application is an application for student to apply to university, whereas AdmissionBase is financial base to apply - paid, grant, financial support etc. How can I distinguish grant base from paid and financial support and vice versa without querying by their name attribute (the project must support i18n)?. Their name values might change some time later. My current solution is that I use code attribute which is in every reference object. There are written human-readable constants for admission bases, like PAID, GRANT or F_SUP. This might be good solution, but the project is for several universities. Which means entering on each university owned server updating code attribute to several objects (other classes use the same code attribute, it comes from abstract base class) plus such objects come from other APIs (government APIs) that do not contain code attribute. Here is the code so you can understand class AbstractReference(models.Model): uid = models.UUIDField(primary_key=True, editable=False, default=uuid4) name = models.CharField(max_length=128) # in this attribute human-readable constants are written code = models.CharField(max_length=128) class Meta: abstract = True # this is used just a reference in … -
Comment inside of the Django DetailView
I need to add comments in the Post Detailed View. I am able to submit the comment form but it is not saving the comment, instead, when I click on the submit button the page is reloaded and the comment doesn't get saved. In models.py class Comment(models.Model): post=models.ForeignKey(Post,on_delete=models.CASCADE,related_name="comments") name=models.CharField(max_length=200) comment=models.TextField() created_date=models.DateTimeField(default=timezone.now) approved_comment=models.BooleanField(default=False) def __str__(self): return self.comment In forms.py: from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model=Comment fields=['name','comment'] In views.py: from django.views.generic.edit import ModelFormMixin from .forms import CommentForm class PostDetailView(ModelFormMixin,DetailView): model=Post form_class=CommentForm def get_context_data(self,*args,**kwargs): context=super().get_context_data(**kwargs) context['form']=self.get_form() return context def post(self,request,*args,**kwargs): self.object=self.get_object() form=self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self,form): form.instance.post=self.object form.save() return super().form_valid(form) -
document direction change using javascript
I'm trying to change document layout from Arabic to English and so the body direction should be changed from rtl to ltr i have already written the JavaScript function and it works for a second only,the document changes direction to ltr and then goes back, any idea on how to fix this? function layout(){ document.body.style.direction="ltr"; } -
run tasks every day at 8 AM in django
i am working on a web app in django and i need to send some random numbers to database , EVERY DAY at 8 AM. i was trynig to use celery but it did not work (im working on windows and from a tutorial i've heard celery does not work on windows!!!).Also i tried django-extensions and django-cron but it needs some changes in cron that i've found it is for linux and as i said before,im on windows. What should i do? Any help would be appreciated. -
visual studio code-should I install python in virtual environment in the folder of my project?
I am a newbie. I have set up my virtual environment in a project folder on my desktop, I also used pip install to install django 2.2 in this project folder on my desktop. I have python installed, but it is in another folder elsewhere on my computer, do I need to install python in the same project folder on my desktop? I am getting messages in virtual studio, which say, "visual studio code, workspace contains pipfile but 'pipenv' was not found". Also when try to use pip install to install python into the project folder on my desktop I get an error message in terminal(I am using a mac) which says, pip install python3.8 ERROR: Could not find a version that satisfies the requirement python3.8 (from versions: none) ERROR: No matching distribution found for python3.8 I'm also getting error messages which say: visual studio code no python interpreter is selected & there is no pip installer available in the selected environment So overall, do I need to install python in the project folder and if so, how do I do this? Do i need to install the python interpreter as well? I have had a problem with bash wherein … -
Is there a way i could select which group i want my user to belong to using a custom template?
Lets say You want to create a user and you want to associate the user with a specific group i.e a user should either be an Admin, Seller and Customer. I dont need the user to always be a customer like in the below code. group = Group.objects.get(name='Customer') user.groups.add(group) -
How to Return MEDIA URL in Template
I Create This Function to return a Media URL of a File in Templates but it Show in HTML like http://example.com/history/('/media/exam/returns/files.png',) @property def ReturnAttachment(self): from ResultManagement.models import Result attachment = Result.objects.filter(examinee=self.examinee, exam=self.exam) attachment_url = attachment[0].attachment.url if self.hasReturnAttachment(): #print("URL", attachment) return attachment_url, How can I fix it? Thanks in Advance -
How choose the right serializer depends on specific field ? e.g. type
I'd like to serialize an input from an API to check if the format is valid ProfileSerializer(payload).is_valid() profile.py from rest_framework import serializers from .node import NodeSerializer class ProfileSerializer(serializers.Serializer): node = NodeSerializer(many=True) node.py from rest_framework import serializers from .point import PointSerializer class NodeSerializer(serializers.Serializer): id = serializers.IntegerField() points = PointSerializer(many=True) type = serializers.CharField(max_length=50) The issue is the node format, depend on the type -> SEGMENT, ARC, ... I need to select the right serializer. So I create a serialier for each type type -> SEGMENT, ARC, ... but I can't figure out how to use them inside the ProfileSerializer. How I can catch the type field and use it inside a provider parser function profile.py from rest_framework import serializers from .segment import SegmentSerializer from .thread import ThreadSerializer map_type2serializer= { "THREAD": ThreadSerializer, "SEGMENT": SegmentSerializer } def parseur_provider(type): p = map_type2serializer.get(type, None) if(p is None): raise ValueError("Type {type} is not register") return p class ProfileSerializer(serializers.Serializer): node = parseur_provider(type)(many=True) -
Cannot assign "<QuerySet []>": " must be a "" instance
I am trying to save this field from Forms.py, which seems to be causing this error: Cannot assign "<QuerySet [Vehicles: Toyota]>": "Group.vehicles" must be a "Vehicle" instance. Everything saves correctly through the admin page but not through the form. class GroupForm(forms.ModelForm): vehicles = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Vehicles.objects.all()) class Meta: model = Group Models.py: class Vehicles(models.Model): Vehicles = models.CharField(max_length=30, null=True, blank=True) MaxRange = models.DecimalField(null=True, max_digits=20, decimal_places=3, default=Decimal('0.000')) Speed = models.DecimalField(null=True, max_digits=20, decimal_places=3, default=Decimal('0.000')) def __str__(self): return self.Vehicles class Group(models.Model): group = models.CharField(max_length=30, blank=True) vehicles = models.ForeignKey(Vehicles, null=True, on_delete=models.CASCADE) def __str__(self): return self.group 'Group' consists of one type of vehicle. views.py: def home(request): group = Group.objects.all() form = GroupForm() if request.method == 'POST': form = GroupForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.vehicles = form.cleaned_data['vehicles'] obj.save() return redirect('/') context = {'group': group, 'form': form} return render(request, 'calculator/Input.html', context) Thanks you for any input -
How to understand the following Python function code?
How to understand the following code? This code is a snippet of Django source code. I am trying to understand 1. How the nested function works below? 2. The function returns itself, so is it a recursive function? 3. Why does the check_password(raw_password, self.password, setter) in return can have three parameters? def check_password(self, raw_password): """ Returns a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes. """ def setter(raw_password): self.set_password(raw_password) self.save(update_fields=["password"]) return check_password(raw_password, self.password, setter) -
VSCode Debug - Prepend command when launching for django?
I've recently started using VSCode to debug with Django and it's worked out pretty well. I use a system for managing my environment variables however that requires the use of it's keyword first (keys python manage.py runserver) Debugging works fine for firing up a standard Django install - but I can't seem to get the python debugger to run the above statement. In my launch.json I've tried a few configurations like the following: # launch.json { "name": "Python: Django", "type": "python", "request": "launch", "preLaunchTask": "keys-run", "program": "${workspaceFolder}/manage.py", "args": [ "runserver" ], "django": true } # tasks.json { "type": "shell", "label": "keys-run", "command": "keys" } I've tried this as well: { "name": "Python: Django", "type": "python", "request": "launch", "program": "keys", "args": [ "python", "manage.py", "runserver" ], "django": true } The second config give me an error that there is no such file or directory '/home/username/project_directory/keys' But from the command line (zsh) I can run the command: keys python manage.py runserver and it loads my environment variables as it should, then loads up and runs django without issue. What is the best way to get this into VSCode debugger? -
Django add urls from project to another project
I have an existing project (let's name it main) on Django and several applications in it. There is a separate project, also in django, and one application inside it (we will call this the second one). Here is a generalized file structure for project "second": my_second_project │ manage.py │ models.py │ my_models.py │ my_views.py │ ├───myapp │ │ admin.py │ │ apps.py │ │ Funcs.py │ │ models.py │ │ tests.py │ │ urls.py <-- from here urls import to project urls file │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ └───...│ ├───my_second_project │ │ asgi.py │ │ settings.py │ │ urls.py <-- HERE all urls i need │ │ wsgi.py │ │ __init__.py ├───templates │ ... │ └───__pycache__ models.cpython-37.pyc Here is a generalized file structure for project "main": main_project ├───app ... │ ├───... ├───main_project │ ├───media │ │ └───user_uploads │ ├───settings │ │ └───base.py │ └───urls.py ├───app ... │ ├───... ├───app ... │ ├───... └───static ├... I need to integrate "second" project into my existing one (main project), ideally without making any changes to the second project. I tried to do it in the same way that applications are integrated (via urls include), but it … -
How to clone on the updated files from github to the droplet in digital Ocean
I have a django website deployed in digital ocean which requires to be updated. I learn that the deployment method is using github. I do not have access to the github account but i can commit and push to the repository from the bash. Is there a way i can clone the only updates files from the git repo to my digital ocean droplet