Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i remove html tags in tinymce
How do I remove HTML tags which show in my browser as a result of being entered in the django administration using timymce -
google-analytics with proxy server on apache2 and django
i have googled a lot for last few days. but i couldn't find a appropriate solution. my website uses google analysis as commonly used. but ad-blockers seems to blocking it. my code <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-4RPCXXXXX"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-4RPCXXXXX'); </script> while researching i found many articles about CNAME cloacking and server proxy with node.js. can someone guide me with apache proxying or maybe a way around with django for google-analytics. or am i missing something? -
In Django I cant retrieve the fields of values of Upload cv, gender, status but the other fields are working fine which is full name
This is my edit.html code and during retrieving the values from database it shows only the text fields like value={{ i.full_name}} but when I am writing value={{ i.cv}}, value={{ i.status}}, value={{ i.gender}} it does not shows the value which needs to bed edited I have two choice fields and one file field. this is my edit.html <section class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-12 mb-5"> <h2 class="mb-4 text-center">Update Candidate Details</h2> <form method="POST" action="/update/ {{i.id}}/" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" > {% csrf_token %} {% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="full_name">Full Name :</label> <input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="recruiter_name">Recruiter Name :</label> <input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter Recruiter Name"> </div> </div> {% comment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="id_last_name">Last Name :</label> <input type="text" class="form-control" name="last_name" id="id_last_name" placeholder="Enter Last Name"> </div> </div> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="email">Email :</label> <input type="email" class="form-control" value ={{i.email }} name="email" id="id_email" placeholder="Enter Email"> </div> </div> <div class="row form-group"> <div class="col-md-12 … -
DockerHub: Incorrect copying of files
I am trying to upload a Django app to Docker Hub. On local machine (Ubuntu 18.04) everything works fine, but on Docker Hub there is an issue that the requirements.txt file cannot be found. Local machine: sudo docker-compose build --no-cache Result (it's okay): Step 5/7 : COPY . . ---> 5542d55caeae Step 6/7 : RUN file="$(ls -1 )" && echo $file ---> Running in b85a55aa2640 Dockerfile db.sqlite3 hello_django manage.py requirements.txt venv Removing intermediate container b85a55aa2640 ---> 532e91546d41 Step 7/7 : RUN pip install -r requirements.txt ---> Running in e940ebf96023 Collecting Django==3.2.2.... But, Docker Hub: Step 5/7 : COPY . . ---> 852fa937cb0a Step 6/7 : RUN file="$(ls -1 )" && echo $file ---> Running in 281d9580d608 README.md app config docker-compose.yml Removing intermediate container 281d9580d608 ---> 99eaafb1a55d Step 7/7 : RUN pip install -r requirements.txt ---> Running in d0e180d83772 [91mERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' Removing intermediate container d0e180d83772 The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 app/Dockerfile FROM python:3.8.3-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY . . RUN file="$(ls -1 )" && echo $file RUN pip install -r requirements.txt docker-composer.yml version: '3' services: web: … -
Error while trying to communicate between django and postgresql inside a docker
I've deployed Django+Vue application on server and changed psql ports from "5432:5432" to "5433:5433" because I'm running other applications on this server and this port is already in use, now I have a problem when making api requests, the error is: Is the server running on host "db" (ip) and accepting backend | TCP/IP connections on port 5433? When I'm doing docker-compose up db service is saying: db | 2021-05-08 11:52:02.547 UTC [1] LOG: starting PostgreSQL 13.2 (Debian 13.2-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit db | 2021-05-08 11:52:02.547 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db | 2021-05-08 11:52:02.547 UTC [1] LOG: listening on IPv6 address "::", port 5432 db | 2021-05-08 11:52:02.551 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db | 2021-05-08 11:52:02.555 UTC [27] LOG: database system was shut down at 2021-05-08 11:51:10 UTC db | 2021-05-08 11:52:02.560 UTC [1] LOG: database system is ready to accept connections It says that it listening on port 5432, while my docker-compose.yaml is: version: "3.8" services: backend: container_name: backend build: context: ./mkstat_backend dockerfile: Dockerfile volumes: - static:/app/static - media:/app/media env_file: - ./mkstat_backend/.env.prod depends_on: - db networks: - backdb db: container_name: db build: context: … -
Django, how to create accounts just by importing a user list
I'm currently working on an LMS. I have a list of student in an excel file, but I want to create an account for students at the time I have uploaded the file to the system, and then the students should be forced to edit the username and password Is it possible to do that with Django? -
What does PYTHONUNBUFFERED in Dockerfile do?
I'm just getting started with docker, and I've been seeing a PYTHONUNBUFFERED environment variable in every Dockerfile for python. Can anyone kindly explain what it actually is? -
Cannot parse FormData into django backend
hope you all are doing well I have been working on a custom form that I want to send to django backend via ajax request, the only problem that I am encountering is I am wrapping the form into FormData it works well on the frontend site but on the backend it shows a querydict with some strane data in it and making it much harder to parse the data, if there can be a way to easily get the data out. Any leads or any response is much appreciated Following is my code of the javascript function that sends the data to the backend Javascript function Edit_Content(e){ var form_data=new FormData(document.querySelector("#edit-form")) let csrftoken=getCookie("csrftoken") $.ajax({ url:"{% url 'EditPost' %}", method:"post", datatype:"json", processData:false, "headers":{ "X-CSRFToken":csrftoken }, data:form_data, success:function (data){ console.log("Post or idea edited") } }) } views.py def Edit(request): print(request.POST,request.FILES) data=dict(request.POST) print(data) if data["type"] == "post": post=Post.objects.get(pk=data['id']) content=data.get("post-content",None) media=data.get("media",None) post.edit(content,media) else: idea=Idea.objects.get(pk=data["id"]) title=data.get("title",None) privacy=data.get("privacy",None) requirements=data.get("requirements",None) category=data.get("category",None) content=data.get("idea-content",None) media=data.get("media",None) idea.edit(requirements,title,privacy,category,content,media) return HttpResponse(status=200) After converting request.POST into dictionary object it it gives {'------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name': ['"type"\r\n\r\nidea\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="id"\r\n\r\n1\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="title"\r\n\r\nProgramming is great\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="privacy"\r\n\r\n public\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="requirements"\r\n\r\nnothing\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="category"\r\n\r\nFisica\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="idea-content"\r\n\r\nProgramming is not for kids\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf\r\nContent-Disposition: form-data; name="media"; filename=""\r\nContent-Type: application/octet-stream\r\n\r\n\r\n------WebKitFormBoundaryW30RtYeVz4cXnUNf--\r\n']} Which is hard to parse … -
Replacing static site with Django/Serving static files with mod_wsgi
I have an existing static website that is served via apache. I wanted to add dynamic features to that site so I created a Django app that lives in a subfolder (ie. /django-site/). I have this configured like this: WSGIDaemonProcess django_site processes=5 threads=5 user=user group=group python-home=path/to/virtualenv WSGIScriptAlias /django-site /var/www/django_site/wsgi.py <Location /django-site> WSGIProcessGroup group </Location> But now I would like to replace certain pages that were originally static pages in the root directory. But I don't want to replace all of the static pages. I know that Django recommends putting your static files in a subdirectory like /media or /static and Django configured to be the root directory but since I have a long legacy of these static pages being in the root directory and external links to these pages I don't want to change that. Is there a recommended way to replace these static pages with a dynamic ones? Here are a few ideas that I have thought of: Use ProxyPass to replace pages one at a time Redirect static pages to dynamic versions, change internal links to new dynamic version Move dynamic site to root, and use something like whitenoise to serve those files -
Can you figure this out, i have no idea why there's error
sqlite> CREATE TABLE flights( id int NOT NULL, origin_id, destination_id, duration, PRIMARY KEY (id), FOREIGN KEY (id), REFERENCES (flight) ); Error: near ",": syntax error -
how to make work adsense on django web app
i'm trying to config google adsense on my django app but i can't activate my account because of my website has no content. my app is a repository to find videos or music creators which aren't famous. i have 80 creators in my database and i show them on 8 pages of my website. so that's surprised me when i've seen no content website... did somebody can tell to me if my website is maybe too empty for google adsense ? yufinder.com (my site is in french for the moment) does google has an approach to install adsense on django app ? because i don't find anything. maybe did i need to config something in my django app ? for the moment i've only had de script tag that google gave to me in my main html file but i've seen on other forums that maybe i need to install "django-ads" or something called sekizai but i haven't found a lot of informations about. if you need any informations i'll give you. thank you for helping me -
Get all files of a model in Django Shell
Is it possible to output names of all fields of a specific model in Django Shell? For example, how to get fields from User model": >>> from django.contrib.auth.models import User -
Unable to Update my Profile data in Django Forms
i extend the User Model to create profile dashboard,First I create a model named 'Profile to update some personal details. Now I want to extend User model to add educational details in profile dashboard. for this I extends User Model and then Try all ways to add and Update the data.My issue is all my code is working but when i click on update data is not going into my admin panel. Here is all my code` < Models.py from django.db import models from django.contrib.auth.models import User from PIL import Image from datetime import date GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) Martial_Status = ( ('M', 'Marriad'), ('U', 'Unmarriad'), ) Uni_CHOICES = ( ('IUB', 'The Islamia University Of Bahawalpur'), ) F_CHOICES = ( ('E', 'Faculity Of Engineeeing'), ) D_CHOICES = ( ('D', 'Department Of Information and Commmunication Engineering'), ) class Educationaldetails(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) University_Name =models.CharField( choices=Uni_CHOICES,max_length=50) Faculity = models.CharField( choices=F_CHOICES,max_length=50) Department_Name = models.CharField( choices=D_CHOICES,max_length=50) Degree_Title = models.CharField( max_length=50) Student_Id = models.CharField( max_length=50,unique=True) Registration_Number = models.CharField( max_length=50,unique=True) Transript_No = models.CharField( max_length=50,unique=True) C_GPA = models.CharField( max_length=50,default='0/4.00') Final_Year_Project = models.TextField() Supervisor_Name = models.CharField( max_length=50) Views.py def Educational_details(request): if request.method == 'POST': u_form = UserUpdateForm(instance=request.user, data=request.POST) E_form = EducationalUpdateForm(instance=request.user.profile, data=request.POST) if … -
How to create "related_name" relation with parent models of "through" model (about related_name inheritance)
I have 4 models including one M2M "through" model enabling to had an index: class TargetShape(models.Model): pass class Page(models.Model): target_shapes = models.ManyToManyField(TargetShape, through='PageElement', related_name='pages') class PageElement(models.Model): target_shape = models.ForeignKey(TargetShape, related_name='page_elements') page = models.ForeignKey(Page, related_name='page_elements') index = models.PositiveIntegerField(verbose_name='Order') class WorkingSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='working_sessions') I defined another model Resolution that enables me to link all of them together in order to create the following related_name relations: working_session.resolutions user.resolutions target_shape.resolutions page.resolutions page_element.resolutions To have it working, I had to declare: class Resolution(models.Model): # relations that would be needed from a DRY perspective: page_element = models.ForeignKey(PageElement, related_name='resolutions') working_session = models.ForeignKey(WorkingSession, related_name='resolutions') # relations I want to exist to use user.resolutions, target_shape.resolutions, page.resolutions: user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='resolutions') target_shape = models.ForeignKey(TargetShape, related_name='resolutions') page = models.ForeignKey(Page, related_name='resolutions') However, that's not very DRY. From a DRY perspective, I should be able to declare Resolution as linking to only PageElement and WorkingSession, and deduce / inherit the relation with the parent models: class Resolution(models.Model): page_element = models.ForeignKey(PageElement, related_name='resolutions') working_session = models.ForeignKey(WorkingSession, related_name='resolutions') But in that case, how can I create the following relations: user.resolutions target_shape.resolutions page.resolutions without going through: user.working_sessions.resolutions target_shape.page_elements.resolutions page.page_elements.resolutions -
ModelForm not saving data for user profile
I am having a bit of trouble with my Django forms. When I save my profile form, it's not updating the profile. When the user saves the form, I get the success message. I've tried a couple of solutions already offered here on stack overflow, but I couldn't get any of them to work. I'm sure it's something simple, but I can't figure it out. Any help is appreciated. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) subjectOfInterest = models.CharField(max_length=100) age = models.IntegerField() goal = models.TextField(max_length=500) forms.py class UpdateProfileForm(forms.ModelForm): class Meta: model = Profile labels = { "subjectOfInterest": "What subject interests you most?", "goal": "Whats the goal you want to achieve with Study Wise?", "age": "What is your age?", } fields = [ "subjectOfInterest", "goal", "age", ] views.py def profile(request): form_class = UpdateUserForm p_form_class = UpdateProfileForm if request.method == "POST": p_form = p_form_class(request.POST, instance=request.user) user_form = form_class(request.POST, instance=request.user) if user_form.is_valid() and p_form.is_valid(): user_form.save() p_form.save() messages.success(request, "Your profile has been updated") return redirect("profile") else: user_form = UpdateUserForm() p_form = UpdateProfileForm() profile_data = Profile.objects.all().filter(user=request.user) return render( request, "user/profile.html", {"user_form": user_form, "p_form": p_form, "profile_data": profile_data}, ) profile.html {%for profile in profile_data%} <h4>Interests: {{profile.subjectOfInterest}} </h4> <h4>Goal: {{profile.goal}}</h4> <h4>Age: {{profile.age}}</h4> {%empty%} empty {%endfor%} -
Custom button not performing action in Django admin
Am trying to add another custom button, and at the same time I want it to trigger certain processes in Django-admin with templates, below is how I have implemented the template : {% extends 'admin/custominlines/change_form.html' %} {% load i18n %} {% block submit_buttons_bottom %} {{ block.super }} {% if request.GET.edit %} <div class="submit-row"> <input type="submit" value="Custom button" name="_transition-states"> </div> {% endif %} {% endblock %} The button does appear however, when I click it , it doesn't show the print I have inserted in the response_change() function in the admin.py, what am I missing here : def response_change(self, request, obj): if '_transition-states' in request.POST: print("am working") return super().response_change(request, obj) When I click the button it just routes back to the previous page. -
SyntaxError : Invalid syntax jedi
There is a problem showing in my vs-code editor SyntaxError: Invalid syntax jedi I don't know why this problem showing it's bothering me so much and there are some weird symbols on my editor ←[0m ←[m you can see this image can anyone tell how to remove both of this from vs-code editor these will be really helpful. -
Load multiple comments for different events in Django view
In my recent project, I was trying to do a website to make people hold events, while others could comment the events. I want to show all the events hosted by the user in his/her profile page, I created EventsBoard model to store event details and Comment model to store all the comments. class Comment(models.Model): text = models.CharField(max_length=40) for_event = models.ForeignKey( EventsBoard, on_delete=models.CASCADE, related_name='comments' ) author = models.ForeignKey( "user_extend.UserExtend", on_delete = models.CASCADE, related_name='comment_author' ) rate = IntegerRangeField(min_value=1, max_value=10) date = models.DateTimeField(default=timezone.now) def __str__(self): return self.text and I have the view.py as follow. def profile_view(requests, id, *args, **kwargs): obj = UserExtend.objects.get(id=id) activities = EventsBoard.objects.filter(host=obj).filter(event_type='activity') projects = EventsBoard.objects.filter(host=obj).filter(event_type='project') personal_projs = EventsBoard.objects.filter(host=obj).filter(event_type='personal') context = { 'user': obj, 'activities': activities, 'projects': projects, 'personal_projs': personal_projs } return render(requests, 'profile.pug', context) But since one can host lots of events, I am wondering how could I load the comment model to the view.py to bind the event object with comment objects. -
Object of type LineString is not JSON serializable
How can I figure out this error when using folium.GeoJSON. gdf is a geodataframe. layer=folium.GeoJson( gdf, tooltip=folium.GeoJsonTooltip(fields=['oneway','lanes', 'length','speed','name'],localize=True), style_function=lambda x: { 'color': line_color }).add_to(m) m.fit_bounds(layer.get_bounds()) I also tried gdf.to_json() but it does not work -
In one project i seen serialize method outside model in models.py file
what is use of def serialize? Why outside of model method serialize present?. why on user once again serialize is used class Doctor(models.Model): """ This model stores the doctor profile. """ user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) create_on = models.DateTimeField(default=timezone.now) active = models.BooleanField(default=True) # Whether this doctor is accessible to users. qualification = models.TextField(null=True) specialization = models.ManyToManyField(DoctorSpecialization) def serialize(self): return { "id": self.id, "user": self.user.serialize(), "created_on": generate_readable_date_time(self.create_on), "active": self.active, "qualification": self.qualification, "specializations": [s.serialize() for s in self.specialization.all()] } -
how to save django foreignkey with get_or_create
i'm trying to add the vendor profile when user hit add_to_cart url everything works file without saving vendor profile, it was single vendor model, i wanted to make it multiple vendor model so the way can track the vendor data. thank you so much, appreciate your help model.py class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True) vendor = models.ForeignKey(Vendor, related_name='items', on_delete=models.CASCADE) **save this vendor profile when user hit add_to_cart** # vendor_paid = models.BooleanField(default=False) quantity = models.IntegerField(default=1) # price = models.DecimalField(max_digits=8, decimal_places=2) wishlist = models.ManyToManyField(Wishlist, blank=True) views.py @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) vendor = Vendor.object. # this where the problem is order_item, created = OrderItem.objects.get_or_create( item=item, vendor=vendor, # how to save the vendor profile user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("product:product_detail_view", slug=item.slug) else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("product:product_detail_view", slug=item.slug) else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("product:product_detail_view", slug=item.slug) -
Django models how to fix circular import error?
I read about solution for the error (write import instead of from ...) but it doesn't work I think because I have a complex folder structure. The folder structure quiz/models.py import apps.courses.models as courses_models class Quiz(models.Model): lesson = models.ForeignKey(courses_models.Lesson, on_delete=models.DO_NOTHING) # COURSE APP MODEL IMPORTED courses/models.py import apps.quiz.models as quiz_models class Lesson(models.Model): ... class UserCompletedMaterial(models.Model): ... lesson = models.ForeignKey(lesson) quiz = models.ForeignKey(quiz) # QUIZ APP MODEL IMPORTED How you can see I just can't keep it together or something else.. Because I think the UserCompletedMaterial model is a part of courses app -
How can I upload multiple files in to a Django model?
I'm trying to make an LMS system with Django and now I need to upload multiple pdf files to the curriculum of the class. I can upload one file with the OnetoOne field in the Django model but not more. When I try to add another material for the same class it says Upload materials with this Uploaded class already exists. This is my model code. class UploadMaterials(models.Model): name = models.CharField(max_length=255) uploaded_class = models.OneToOneField(Class, on_delete=models.CASCADE, related_name='upload_materials') upload_material = models.FileField(upload_to=rename, null=True) class Meta: verbose_name_plural = "Materials" I need to upload the materials and be able to view them in the template. like...... {% for material in class.materials %} <h1>{{ material.name }}</h1> {% endfor %} I tried the Django ForeignKey instead of OnetoOne and was able to create multiple materials for the same class but could not figure out how to access them from the template. What I want to know is how to upload multiple files to the same class and how to access them in the template. Thank you! -
Why am I getting "page not found" error in Django?
I am new in Django Framework having no previous experience with any other framework. After writing these code and hitting the url http://127.0.0.1:8000/MyApp/f2/400 I get the error "Page not found " This is the code of my Project's main urls.py file : from django.contrib import admin from django.urls import path from django.conf.urls import include,url urlpatterns = [ path('admin/', admin.site.urls), path('MyApp', include('MyApp.urls')), ] This is the code of my MyApp.urls file : from django.urls import path from django.conf.urls import include,url from MyApp import views urlpatterns = [ url('test', views.Index, name='Index'), url('f2/<int:guess>', views.F.as_view()), ] I have attached the image of erroneous page. -
Problem with timezone in Django ORM, datetime value differs from the value stored in the table
I have stored some data into PostgreSQL database. Here is the corresponding Django model: from django.contrib.gis.db import models class PrecipitationContourDjango10d(models.Model): value = models.FloatField(blank=True, null=True) geometry = models.PolygonField(blank=True, null=True) date = models.DateTimeField(blank=True, null=True) window_no = models.CharField(max_length=10, blank=True, null=True) color = models.CharField(max_length=20, blank=True, null=True) def __lt__(self, other): if self.date < other.date: return True return False class Meta: db_table = 'precipitation_contour_web_service10d' Here is some rows that are stored in the table: As you can see the datetime value for the row with id=5921 is 2021-05-07 21:00:00-07. However when I retrieve that row using the Django ORM, its datetime field will change: from data.models import PrecipitationContourDjango10d row = PrecipitationContourDjango10d.objects.get(id=5921) How can I solve this issue? Thanks.