Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render string literal with html tags in django?
I've wrote a custom view to parse markdown files using regex and I'm passing content as a string literal to the template context = "Django is a web framework written using <a href='https://www.python.org/'>Python</a>" return render(request, "blog/post.html", {"context": context}) And in template: <p>{{ context }}</p> But the engine renders content as a plain text. How to make links to be links and paragraphs to be paragraphs? -
Django TemplateView + From does not upload files
I created a dynamic form to upload data to a jsonfield: class ProductForm(forms.Form): def __init__(self, product, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["number"] = forms.IntegerField(required = True) self.fields["number"].widget.attrs.update({'class': 'form-control'}) for key in product.data.keys(): keyname, keytype = key.split("___") if keytype == "str": self.fields[key] = forms.CharField(required = False) elif keytype == "file": self.fields[key] = forms.FileField(required = False) self.fields[key].widget.attrs.update({"class": 'form-control'}) class Meta: model = Product fields = ["id", "number", "data"] I have a TemplateView in place that deals with the request: class ProductUpdateView(TemplateView): template_name = "appName/EditProduct.html" def post(self, request, *args, **kwargs): print(request) ... return render(request, self.template_name, context) But the request I get back looks like this: <QueryDict: {'number': ['3'], 'name___str': ['testname'], 'upload_1___file': ['[object File]']}> and thus request.FILES reads <MultiValueDict: {}> empty. How can I obtain the file? -
Django DetailView form dont save data
I have a DetailView, and need add a form to user contact. views.py class ProductView(FormView, DetailView): model = Product template_name = 'product_detail.html' form_class = NotificationForm success_url = '/products/' def post(self, request, *args, **kwargs): return FormView.post(self, request, *args, **kwargs) forms.py class NotificationForm(ModelForm): ..."""some fields""" class Meta: model = Notification fields = [ 'usernameclient', 'emailclient', 'emailclient_confirmation', 'phoneclient', 'messageclient', ] The model Notification is where is stored the data from that form models.py class Notification(models.Model): ..."""some fields""" I dont understand yet how django workflow with forms. After the submition is correct rediretc to success_url, but nothing is save in db... What is missing? -
Javascript async send query to Django query database then update the same html template
Assuming I have something need to be sent by javascript asynchronously without refreshing the page. name.html {%if names%} {%for name in names%} <h4>{{name}}</h4> {%endfor%} {%endif%} In name.html, I am going to send "Joe" to my Django backend for querying let crsf = '{{csrf_token}}' fetch('{%url "name"%}', { credentials: 'same-origin', headers: { 'X-CSRFToken': crsf, 'Content-Type': 'application/json', 'Accept': 'application/json, text/plain, */*'}, method: 'POST', body: JSON.stringify({ data: "Joe", }),}).then(res=>console.log(res)) Now "Joe" has been sent to the backend In views.py: def name(request): names = Names.objects.all() paginator = Paginator(names, 100) page = request.GET.get('page') paged_names = paginator.get_page(page) context = { 'names':paged_names, } if request.method == 'POST': data = json.loads(request.body.decode("utf-8")) joe = data.get("data") names = Names.objects.all() names = names.filter(name__iexact=joe) context = { 'names':names, } # return render(request, 'cool/names.html', context) return render(request, 'cool/names.html', context) Now I have all names named "Joe" queried out from the database. Question: How do I then render all "Joe"s in name.html and also making pagination work as intended assuming there are over 20k "Joes". -
Django: Form for icalendar to create ics
I am working on a Django application for my friends to organize some tournaments. I want to have an overview of upcoming events and for every event there should be the possibility to download an ics-file with the details. I came across this post How can I dynamically serve files and then make them downloadable in Django? but I was wondering if anyone has an idea how the get_calendar_details(name) function has to look like as I am struggling with the right format. Currently I have the following within my application: models.py class Events(models.Model): title = models.CharField(max_length=64, unique=True) description = models.TextField(default=None) start = models.DateTimeField() end = models.DateTimeField() To render the page with all the events that are upcoming: views.py def events(request): today = datetime.today() events = Events.objects.filter(date__gte=today) return render(request, "events.html", { "events": events }) and my html <table> <thead><tr> <td>start</td><td>end</td><td>title</td><td>description</td><td>link</td> </tr></thead> {% for event in events %} <tr><td>{{ event.start }}</td> <td>{{ event.end }}</td> <td>{{ event.title }}</td> <td>{{ event.description }}</td> <td><a href={% url 'serve_calendar' %}>ics</a></td></tr> {% endfor %} </table> Any input is appreciated, especially if I am on the write track with my model. Many thanks in advance! -
how to integrate XML Schema, XML gateway API in django
i am working in a web application to register a company online via API. but i know how to work with restful API's, basically my mind set is to get an http link to make POST and GET request as per API type. but in this case i have a link contains of XSD schemas, here is the link. i dont have any idea how to test and get started. please anyone know how to work with XML gateway, or any link to follow where may i get the process to integrate XML gateway with django to make a POST request. will be thankful for your answer. -
Django Add object Count and Raw SQL in Javascript
def dashboard(request): employee = Employee.objects.count() position1 = Posit.objects.raw('SELECT employee.stat, count(posit.position_id) as NO FROM employee, posit WHERE employee.id = posit.employee_id AND posit.position_id="1" GROUP BY employee.stat') context = { 'employee ': employee , 'position1': [pos for pos in position1] , } return render(request, 'dashboard/dashboard.html', context) I can use employee count inside the javascript. var x = JSON.parse("{{employee}}"). How do I add position1 into a variable in javascript. Because when I add var y = JSON.parse("{% for pos in position1 %}{{pos.NO}}{% endfor %}"). I got this error Invalid block tag on line 96: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Here is the whole error 86 87 } 88 } 89 }; 90 window.onload = function () { 91 window.myRadar = new Chart(document.getElementById("canvas"), config); 92 }; 93 var colorNames = Object.keys(window.chartColors); 94 </script> 95 96 {% endblock %} 97 {% block content %} -
hello i want to start a function when the server is starting and re execute it every 30 seconds in python
apps.py class MyappConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'myapp' def ready(self): if 'runserver' not in sys.argv: print("server down") else: from .models import Dht11 asset = Dht11.objects.select_related('asset').order_by('-id').first() print(str(asset.dt)+" / "+str(asset.id)) time.sleep(10) # you must import your modules here # to avoid AppRegistryNotReady exception # from .models import MyModel # startup code here while True: ready() This is my code in apps.py but it gives me an exception: TypeError: ready() missing 1 required positional argument: 'self' -
Django update related objects on save using signals
I am coming across an issue that I cannot figure it out. I have created a simple multi step form to help the user to create a Project. A brief explanation: Project is the main model ProjectDetails add information to the Project. There can be 'n' ProjectDetails to one Project. Every details include a Trade that is a ForeignKey of ProjectDetails. There can be only one Trade for every ProjectDetail class Trade(models.Model): ... shipped_quantity = models.IntegerField(default=0) status = models.IntegerField( choices=Status.choices, default=Status.CREATED ) class Project(models.Model): ... quantity = models.IntegerField(default=0) status = models.IntegerField( choices=Status.choices, default=Status.INIT ) class ProjectDetail(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, default='', blank=True, null=True, related_name='details') trade = models.ForeignKey(Trade, on_delete=models.SET_NULL, default='', blank=True, null=True, related_name='project') quantity = models.IntegerField() Once the user complete the last step and finalize the creation of the Project, I would like to update some related fields: a) adding up all the Trades quantity and update the Project Quantity b) update for each Trade the shipped_quantity c) update status of each Trade Here it is my view.py code: def project_create_complete(request, *args, **kwargs): # Final step to complete the project creation # update the status to SAVED and delete the session if request.POST: project = Project.objects.get(id=request.POST['project_id']) if project.status < Project.Status.SAVED: project.status … -
How To: For...Else in a Django template (if/else inside a for loop)
I apologize in advance if this has already been asked, but I couldn't find any answers that answered the problem I'm having: I need to do something similar to a For...Else loop in a Django template. I need to show a button on a template base on an if condition: If the user has already bought this product, then show button 1 If the user has not bought this product, then show button 2 For each product, I have to go through the user's purchases, and then show one button or the other depending on whether they have already bought the product or not. A simplified (and wrong) version of the code would be like: {% for product in products %} //other code here {% for purchase in purchases %} {% if purchase.service_id.id == product.id %} // show button 1 {% else %} // show button 2 {% endif %} {% endfor %} {% endfor %} However, this code doesn't work, as it shows both buttons as it goes through the for loop. I can't do a For...Empty because the user may have other purchases (so the for loop wouldn't be empty), but none of them coincide with this product. … -
Django Rest Framework Filtering does not response 'No Data Found' when no data found
I have a very simple DRF ListApiView which is using filters.SearchFilter as filter_backend. But the problem is it is returning an empty list if no data is found on the queryset. My Code: serializers.py class PhoneSerializer(serializers.ModelSerializer): brand_name = serializers.CharField(source='brand') class Meta: model = models.Phone fields = '__all__' views.py class PhoneApiView(generics.ListAPIView): filter_backends = [filters.SearchFilter] serializer_class = serializers.PhoneSerializer queryset = models.Phone.objects.all() search_fields = ['model_name', 'jan_code'] Result for a successful search [ { "id": 6, "brand_name": "Oppo", "model_name": "Oppo Reno 5", "image": "http://127.0.0.1:8000/media/phone/reno-5-black-2.jpg", "colors": "Red, Blue", "jan_code": "785621716768184", "brand": 6 } ] Expected Result if nothing found (Currently returning an empty list []) { "response": 'No Data Found' } Now, How do I do that? Thanks -
Get latest record in Django from two tables by comparing the date
I have two models - New User Request and Existing User Request which contain exactly the same fields class new_user_request(models.Model): request_id = models.AutoField(primary_key=True) emp_id = models.CharField(max_length=70) request_date = models.DateTimeField(auto_now_add=True) expiration_date = models.CharField(max_length=15, blank=True, null=True) class existing_user_request(models.Model): request_id = models.AutoField(primary_key=True) emp_id = models.CharField(max_length=70) request_date = models.DateTimeField(auto_now_add=True) expiration_date = models.CharField(max_length=15, blank=True, null=True) My task is to send notification mails to employees starting from 3 days before their access expires. I need help in getting the records of employees based on the following conditions: If record exists in existing_user_request get the records whose expiry is in the next three days. If record does not exist in existing_user_request, get the records from new_user_request where the expiry date is in the next three days. If there is a django way of doing this please let me know, if not please help me with the sql query so that I could run this as a cron job. -
name 'cache' is not defined django
class CourseListView(TemplateResponseMixin, View): model = Course template_name = 'eschool/course/list.html' def get(self, request, subject=None): subjects = cache.get('all_subjects') if not subjects: subjects = Subject.objects.annotate(total_courses=Count('courses')) cache.set('all_subjects', subjects) all_courses = Course.objects.annotate(total_modules=Count('modules')) if subject: subject = get_object_or_404(Subject, slug=subject) key = f'subject_{subject.id}_courses' courses = cache.get(key) if not courses: courses = all_courses.filter(subject=subject) cache.set(key, courses) else: courses = cache.get('all_courses') if not courses: courses = all_courses cache.set('all_courses', courses) return self.render_to_response({ 'subjects': subjects, 'subject': subject, 'courses': courses }) -
how users in a plateform made with django can voice call each others
hello in my plateform I want the users to call each others , like this scenario A : call B , B : receive a call from A. maybe this time B : call C C : receive a call from B and so on what do you suggest me, to make it work -
Django Raw Query does not Output
views.py def dashboard(request): employee = Employee.objects.count() position = Position.objects.raw('SELECT employee.stat, count(position.position_id) as NO FROM employee, position WHERE employee.id = position.employee_id AND position.position_id="1" GROUP BY employee.stat') context = { 'employee ': employee , 'position': position, } return render(request, 'dashboard/dashboard.html', context) I can output the employee count by using {{employee}} but when I use {{position}} the position output is "RawQuerySet". This is the output in MariaDb using the raw query. employee.stat NO 1 100 2 20 3 30 How can I output all the value of each employee.stat in the dashboard.html? Also can I output each employee.stat NO seperately? -
How to add image for image field for a model instance in django admin panel on heroku?
I added a few books on heroku data. Every model is displayed on heroku app site. My models have the field "image". I add these images from my PC folder and when I open this app after 2-3 hours the book images dissapear. I think it's because I turn off a PC, where I took these images. How do I have to do it correctly that these images don't dissapear? -
'NoneType' object has no attribute 'negate'
I'm getting the error when trying to get all the Urls for which the limited field is True. I've tried deleting the migrations and creating new migrations, but still getting the same error. these are the installed dependencies: asgiref==3.4.1 backports.zoneinfo==0.2.1 Django==4.0 django-cors-headers==3.10.1 django-shell-plus==1.1.7 djangorestframework==3.13.1 djongo==1.3.6 dnspython==2.1.0 gunicorn==20.1.0 pymongo==3.12.1 python-dotenv==0.19.2 pytz==2021.3 sqlparse==0.2.4 tzdata==2021.5 models.py: class Urls(models.Model): _id = models.ObjectIdField() record_id = models.IntegerField(unique=True) hash = models.CharField(unique=True, max_length=1000) long_url = models.URLField() created_at = models.DateField(auto_now_add=True) expires_in = models.DurationField(default=timedelta(days=365*3)) expires_on = models.DateField(null=True, blank=True) limited = models.BooleanField() exhausted = models.BooleanField() query: Urls.objects.filter(limited=False) error: Traceback (most recent call last): File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 933, in _select return SelectQuery(self.db, self.connection_properties, sm, self._params) File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 116, in __init__ super().__init__(*args) File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 152, in parse self.where = WhereConverter(self, statement) File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/converters.py", line 27, in __init__ self.parse() File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/converters.py", line 119, in parse self.op = WhereOp( File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 476, in __init__ self.evaluate() File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 465, in evaluate op.evaluate() File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/sql2mongo/operators.py", line 258, in evaluate self.rhs.negate() AttributeError: 'NoneType' object has no attribute 'negate' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/mnt/c/Users/pranjal/Desktop/urlhash/env/lib/python3.8/site-packages/djongo/cursor.py", line 51, … -
MultipleObjectsReturned at /course/eyime/user_library/
I am building a website where users can buy courses and the courses will display on their users library, a site similar to gumroad, but i am getting this error when i clicked on the payment option on my code. Here is the error messages i am getting MultipleObjectsReturned at /course/eyime/user_library/ get() returned more than one UserLibrary -- it returned 2! here is the Views.py codes @login_required def user_library(request, username): user = get_object_or_404(User, username=username) my_library = UserLibrary.objects.filter(user=user) if request.method == 'POST': course_id = request.POST['course_id'] course_price = request.POST['course_price'] course = UserLibrary.objects.get(courses__id=course_id) """for c in course.courses.all(): print(c.name)""" context = { 'course': course, 'course_price': course_price, 'email': request.user.email, 'phone': request.user.phone_number, } return render(request, 'courses/content/pay_for_courses.html', context) return render(request, 'courses/content/user_library.html', {'my_library': my_library}) here is the html codes for payment of the courses {% extends "jtalks/base.html" %} {% load static %} {% block title %}Payment With Paystack{% endblock %} {% block content %} <div class='container' onload="payWithPaystack()"> <div class='row justify-content-md-center'> <div class='col-md-auto'> <div id="output"> </div> <div id="success"> </div> <div id="display_info" style="display: none"> <p>Click <a href="{% url 'courses:print_course_pdf' course.id %}" target="_blank">Here</a> to print receipt of your purchase</p> <p id="home">Go Back Home <a href="{% url 'jtalks:jtalks-home' %}">Homepage</a></p> </div> </div> </div> </div> {% endblock content %} {% block js %} <script … -
Django on Heroku continues to process an old worker request on repeat?
I finally set up RQ on Django, and for some reason the worker dyno continues to run on repeat with old values I was testing. As soon as the job results return, it once again starts. I tried FLUSHALL with redis, I tried stopping my front end app engine, I tried restarting and redeploying my Django app on Heroku, but the only thing that seems to temporarily work is turning off the worker dyno until I turn it back on. My current add on list is Heroku Postgress, Heroku Redis, and Heroku Redis To Go. I don't know why it continues to restart the worker queue with the same values, and no amount of fiddling is working. -
When I try to validate 'username' field in Django form with clean_method I get a NameError
Here is my forms.py file. I got a "NameError: name 'username' is not defined" on this row: def clean_username(self): trying to submit this form, but, AFAIK, there are nothing wrong with it. from .models import Blog from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.exception import ValidationError class PostForm(forms.ModelForm): class Meta: model = Blog fields = ('title', 'description',) class SignUpForm(UserCreationForm): username = forms.CharField(max_length=30) first_name = forms.CharField(max_length=150) #, help_text='First Name') last_name = forms.CharField(max_length=150) #, help_text='Last Name') email = forms.EmailField(max_length=200, help_text='Required. Enter a valid email address') def clean_username(self): nom_de_guerre=self.cleaned_data['username'] if User.objects.filter(username=nom_de_guerre).exists(): raise forms.ValidationError('User with this name is already exists!') def clean_email(self): addresse_de_mail=self.cleaned_data['email'] if User.object.filter(email=addresse_de_mail).exists(): raise forms.ValidationError('User with this email is already exists!') class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2', ) ``` -
Is there a way to create a back button in Django that understands a tree structure?
I have a Django website that looks like this: The arrows represent hyperlinks that take you to the next page. All pages except the Main Page need a "Back" button. For Page A and Page B, the back button is pretty simple - it always takes you to the Main Page. For Page C however, there are 2 different ways to get to it (technically 3, if you count the back button on Page D), so it's no longer obvious where the back button should take you. The way it should work is this: If the user came from Page A to get to Page C, the Back button should take them back to Page A If the use came from Page B to get to Page C, the Back button should take them back to Page B If the user didn't come from either Page A or Page B to get to Page C (they could have just entered the URL of Page C into their browser), default to having the Back button take them to Page A This has been asked before, and none of the answers/suggestions make sense for anything other than the most basic scenario, where … -
TypeError: Planet() got an unexpected keyword argument 'name'
from django.db.models.fields import CharField # Create your models here. class Planet(models.Model): name: models.CharField(max_length=50) number: models.IntegerField() I used python shell to run: python manage.py shell from planet_universe.models import Planet large_jupiter = Planet(name="Jupiter1", number=1) I get the following error: TypeError: Planet() got an unexpected keyword argument 'name'. How do I correct this error? -
I'm trying to deploy django web app on heroku but i couldn't after deploy heroku shows first method not allowed then bad request
[here is project structure ][1] when I write Heroku local then enter terminal shows an error no procfile but here we can see above [1]: https://i.stack.imgur.com/d54wN.png -
How to use clickhouse in django project?
I have a Chat model that is stored in postgresql class Chat(StatusModel, MyTimeStampedModel): closed_at = MonitorField(monitor='status', when=['closed']) channel = models.ForeignKey(Channel, on_delete=models.PROTECT, null=True) I need to count the number of open and closed chats using clickhouse. How can I do this? -
How can show django auth-views URLs on swagger?
I set the Urls like belows. users>urls.py from django.urls import path from django.contrib.auth import views as auth_views from users import views .... path( "changePassword/", auth_views.PasswordResetView.as_view(), name="password_reset" ), # 비밀번호 변경 (링크 발송) path( "changePasswordDone/", auth_views.PasswordResetDoneView.as_view(), name="password_reset_done", ), # 비밀번호 변경(링크 선택 후 화면) path( "changePasswordConfirm/<uidb64>/<token>/", auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm", ), # 비밀번호 변경(사용자 전송 링크) path( "changePasswordComplete/", auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete", ), # 비밀번호 변경(사용자 새 비밀번호 입력 후) ] but the auth_views doesn't appear in the swagger like below images. I guess there is some problem in the settings.py.... but don't know the detail. config>settings.py # Rest_Framework JWT REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ( # 'rest_framework.permissions.IsAuthenticated', #401 에러 회피 "rest_framework.permissions.AllowAny", # 401 에러 회피 ), "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", # 'rest_framework.authentication.SessionAuthentication', # 'rest_framework.authentication.BasicAuthentication', ), } could you help kindly please?