Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to copy data from model to another model in Django after filtering?
here is the models: class Rooms(models.Model): name=models.CharField(max_length=100) image=models.URLField() max_person=models.CharField(max_length=100) office=models.CharField(max_length=200) status=models.CharField(max_length=200) cost=models.CharField(null=True,max_length=250) roomId=models.CharField(max_length=100,null=True) Address= models.CharField(max_length=100,null=True) def __str__(self): return str(self.name) class Available_Rooms(models.Model): users=models.ForeignKey(Rooms,on_delete=models.CASCADE) name=models.CharField(max_length=100) image=models.URLField() max_person=models.CharField(max_length=100) office=models.CharField(max_length=200) status=models.CharField(max_length=200) cost=models.CharField(null=True,max_length=250) roomId=models.CharField(max_length=100,null=True) Address= models.CharField(max_length=100,null=True) def __str__(self): return str(self.name) at model "rooms" there is 100 objects (rooms) and what I want filter it and list rooms that have maxperson = 4 availablity= Rooms.objects.filter(maxperson="4").all() and want to to copy the rooms details to the other model "Available_Rooms" any idea how that can be done? many thanks in advance -
How to iteratively render the first X fields in a Django form
I'm rendering a form in a Django html template by using a for loop and iterating over the fields. I want to add some sections & headers inside my form, so is there a way to 'slice' the form fields or otherwise iteratively display only a subsection of fields? Something like {% for field in form.slice(0, 5) %} <!-- render first 5 fields --> <h2>Section 2</h2> <p>Some text about next section</p> {% for field in form.slice(5, 10) %} <!-- render the next 5, etc. --> I know the worst case answer is to render each field manually, but it's a VERY long form. Here's my existing form code. {% for field in form %} <div class="field"> <label class="label" for="{{field.id_for_label}}"> {{field.label}} </label> <div class="control">{{field}}</div> {% if field.help_text %} <p class="help">{{field.help_text}}</p> {% endif %} <ul class="errorlist"> {% for error in field.errors %} <li class="is-danger help">{{error}}</li> {% endfor %} </ul> </div> {% endfor %} -
Django version downgraded when I install third party Django package
When we upgrade Django version this two packages prompted incompatible Installing collected packages: django Attempting uninstall: django Found existing installation: Django 3.1.6 Uninstalling Django-3.1.6: Successfully uninstalled Django-3.1.6 ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the foll owing dependency conflicts. django-helpdesk 0.3.4 requires Django<4,>=2.2, but you have django 4.0.4 which is incompatible. django-celery-beat 2.2.1 requires Django<4.0,>=2.2, but you have django 4.0.4 which is incompatible. Successfully installed django-4.0.4 When we try to upgrade packages(django-helpdesk) django core version was downgraded. Is this not a bug? pip install django-helpdesk --upgrade -------- -------- -------- Installing collected packages: Django Attempting uninstall: Django Found existing installation: Django 4.0.4 Uninstalling Django-4.0.4: Successfully uninstalled Django-4.0.4 Successfully installed Django-3.2.13 Please help me -
Python Django login logout logic
In this question I won't add any code. Just wanted to know whether I should redirect the user to home page if user is already authenticated in the system but tries to visit login page. What is the best solution? -
Trouble with Django and Google Charts
I'm trying to make my page update in real time but for some reason the code get's stuck on "var = new_data ..." function refresh() { $.ajax({ type:"GET", url: "{% url 'get_data' %}", data:{ poll_id: {{ poll.id }} }, success: function(data) { // the code stops running here var new_data = google.visualization.arrayToDataTable(data); var options = { title: "Results", legend: 'none' }; var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(new_data, options); }, }); setTimeout(function () { refresh() }, 1000); }; } -
sql query not work in django but dose in sql shell
i have a project in django 3 and try to create a filter for finding conflicted item via datetime in postgresql 13. when i use below script via postgesql shell, it worked!. SELECT a.*, b.* FROM users_task AS a JOIN users_task AS b ON daterange(a."startDatetime"::date, a."endDatetime"::date) && daterange(b."startDatetime"::date, b."endDatetime"::date) WHERE (a."startDatetime"::date, a."endDatetime"::date) <= (b."startDatetime"::date, b."endDatetime"::date) but when i use it in my code, not work and return empty. return tsk.objects.raw(''' SELECT a.*, b.* FROM users_task AS a JOIN users_task AS b ON daterange(a."startDatetime"::date, a."endDatetime"::date) && daterange(b."startDatetime"::date, b."endDatetime"::date) WHERE (a."startDatetime"::date, a."endDatetime"::date) <= (b."startDatetime"::date, b."endDatetime"::date) ''') i found &&(contains) not work when inserted in my code. please help me. -
django get module path in shell
I am on a really big project that jump among many modules, here's a difficulty, sometimes I add a print in certain line of particular file, for testing purposes. after building, I run the file from shell, and there is a line output comes from nowhere pops up in my command line (well, not exactly nowhere, I forgot where I added the print), I need a stronger print like: print('test') # test flags/urls.py 348 therefore, I am building a put function, from inspect import currentframe def put(value): frameinfo = currentframe() location = 'path to this module' print(f'{value} {location} {frameinfo.f_back.f_lineno}') put({'name': 'jason'}) # {'name': 'jason'} path to this module 9 when I tried to work out the path, something unexpected happened. flags/test.py print(__file__) # /Applications/MAMP/htdocs/canvas/src/zzd/env/lib/python3.7/site-packages/django/core/management/commands/shell.py shell (env) 🌹 python manage.py shell < '/Applications/MAMP/htdocs/canvas/src/zzd/zzd/flags/tests.py' /Applications/MAMP/htdocs/canvas/src/zzd/env/lib/python3.7/site-packages/django/core/management/commands/shell.py it turns out to always return the path of shell.py, instead of my module file path. I wonder why this happens, would be very gratefully for your help. -
Run different python files on Django startup
After running my Django project, I want my different python files to run concurrently until I terminate the project. When I run "python manage.py runserver" I want different python files to run at the same time. Is there a way to do this in django? I searched but couldn't find the exact result I wanted. -
Django FIlter: Filtering object hidden in multi layered model structure
I have a following django model relationship: model Project(): model Vehicle(): ForeignKey(Project) model Concept(): ManyToManyField(Vehicle) model Analysis(): ForeignKey(Concept) I want to sort out all Analyses objects which are connected to a Project with a known id. Concept can be for more than one vehicle but all the vehicles within a concept will be limited to only one Project. Or should i justadd to all following models a foreignkey with a project field? Thanks -
How can I add Datepicker in DjangoCreateView
#view.py class JobCreateView(CreateView): model = Job template_name = 'Job_create.html' fields = ['Company' ,'Job_title','Department','Start_date','end_date','Consent'] def form_valid(self, form): form.instance.Alumni_id = self.request.user.alumni return super().form_valid(form) def get_form(self): '''add date picker in forms''' form = super(JobCreateView, self).get_form() form.fields['end_date'].widget = forms.SelectDateWidget() return form from get_form function I got this kind of date Input but I want a date picker that's look like a calender -
django add method to standard Model class
from articles.models import Article label = f'{Article._meta.app_label}.{Article._meta.object_name}' I need to use label for almost all inherited classes from from django.db import models.Model, I want to add this method to the standard Model class without changing library file. if there is built-in way to mix-in a bunch functions to model class without adding inheritance classes and changing initial file, please let me know, I more than grateful. class Model(metaclass=ModelBase): def label(cls): return f'{cls._meta.app_label}.{cls._meta.object_name}' -
How to deal with django migration postgres deadlock?
So, I was deploying the django app to production and then the infamous postgres deadlock situation happened. This happens during the migration. Django version: 3.2 Postgres 13 Google cloud sql postgres. OperationalError deadlock detected DETAIL: Process 112506 waits for AccessExclusiveLock on relation 29425 of database 27145; blocked by process 112926. Process 112926 waits for RowShareLock on relation 29381 of database 27145; blocked by process 112506. HINT: See server log for query details. I ran this query to get the process info: SELECT 29425::regclass,29381::regclass from pg_locks; and result: regclass | regclass "custom_requestlog" "auth_user" "custom_requestlog" "auth_user" I am not sure how to proceed ahead, as the pgaudit has been enabled but it doesnt show anything and also the query insights is not that helpful. Attached is image of query insights. Any help would be helpful please! -
Error won't showing up, Form validation with Django
I just started learning Django for my new Forum project, I'm trying to find it out myself but this problem has been bothering me since 2 days. I am trying to make a registration validation for my form, I am using messages.error(request, "Text") to make an error appear on screen, but it doesn't work, and just shows nothing. Here is a part of my HTML code: <div class="limiter"> <div class="container-login100" style="background:black;"> <div class="wrap-login100"> <form class="login100-form validate-form" method='POST' action="{% url 'users:register' %}" > {% csrf_token %} <span class="login100-form-logo"> <i class="zmdi zmdi-landscape"></i> </span> <span class="login100-form-title p-b-34 p-t-27"> Register </span> <div class="wrap-input100 validate-input" data-validate = "Enter username"> <input class="input100" type="text" name="username" placeholder="Username" required> <span class="focus-input100" data-placeholder="&#xf207;"></span> </div> <div class="wrap-input100 validate-input" data-validate="Enter password"> <input class="input100" type="password" name="pass" placeholder="Password" required> <span class="focus-input100" data-placeholder="&#xf191;"></span> </div> <div class="wrap-input100 validate-input" data-validate="Confirm password"> <input class="input100" type="password" name="pass-confirm" placeholder="Confirm Password" required> <span class="focus-input100" data-placeholder="&#xf191;"></span> </div> <div class="wrap-input100 validate-input" data-validate="Enter Email"> <input class="input100" type="email" name="mail" placeholder="E-Mail" required> <span class="focus-input100" data-placeholder="&#xf191;"></span> </div> <div class="container-login100-form-btn"> <button class="login100-form-btn"> Register </button> </div> <div class="text-center p-t-90"> <a class="txt1" href="login"> Already registered? </a> </div> </form> </div> </div> </div> Here is my views.py register function: def register(request): if request.method == "POST": username = request.POST["username"] password = request.POST["pass"] password_confirm … -
Django filter can work in generate PDF using pdfkit
Am trying to generate pdfkit using these way view.py def view_PDF(request, id): sub = get_object_or_404(Student, id=id) sub_fil = Subject.objects.filter(student_name = request.user) context = { "sub": sub.id, "sub_no": sub.sub_no, "book": sub.book, 'sub_fil':sub_fil, } return render(request, 'school/pdf_template.html', context) def generate_PDF(request, id): # Use False instead of output path to save pdf to a variable pdf = pdfkit.from_url(request.build_absolute_uri(reverse('student-detail', args=[id])), False) response = HttpResponse(pdf,content_type='application/pdf') response['Content-Disposition'] = 'filename="student.pdf"' return response When am trying to omit this line sub_fil = Subject.objects.filter(student_name = request.user)working good without information from subject but that line is very important to display some informations. when run server with that line i got this problem OSError at /student-download/2 wkhtmltopdf reported an error: Loading pages (1/6) [> ] 0% [======> ] 10% [==============================> ] 50% Error: Failed to load http://127.0.0.1:8000/student-detail/2, with network status code 299 and http status code 500 - Error downloading http://127.0.0.1:8000/student-detail/2 - server replied: Internal Server Error [============================================================] 100% Counting pages (2/6) [============================================================] Object 1 of 1 Resolving links (4/6) [============================================================] Object 1 of 1 Loading headers and footers (5/6) Printing pages (6/6) [> ] Preparing [============> ] Page 1 of 5 [========================> ] Page 2 of 5 [====================================> ] Page 3 of 5 [================================================> ] Page 4 of 5 [============================================================] … -
Out of range float values are not JSON compliant: nan, Django Rest Framework with Json Serialization Exception
I work with rest_framework to implement a django API. The table Order from my database has nan fields, and Nan generates the error Out of range float values are not JSON compliant: nan. How to ensure that serializing Nan to JSON works. #serializers.py from rest_framework import serializers from api.models import Order class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ('id', 'status', 'description') The serialization here is a black box, i don't find where to fix this -
how to get item from certain database variable?
models.py: class VideoLibrary(models.Model): shop_id = models.AutoField(primary_key=True, unique=True) shop_name = models.CharField(max_length=264) adress = models.TextField(max_length=264, default='') i have here shop_name and adress. The thing i need is to click a button wich gets shop_name from text area and match it with adress. Is there any way to do it? as i mentioned i need to get the name of shop from text area and then show its andress -
Braintree Paypal integration through API
How can i integrate PayPal payment gateway through braintree-sandbox whose client side is on Android studio and server-side on Django framework with the help of API. -
Can someone help me to implement fecth api?
I have created a like and dislike system in Django but now I want to do it with fetch api in Javascript. I don't know how to implement it, I don't understand very well how to do it. I have created the url: urlpatterns = [ path("like/<int:id>", views.like_post, name='like_post') ] Then, in views.py: @login_required def like_post(request, id): if request.method == "POST": postId = Post.objects.get(id = id) if not postId.likes.filter(id = request.user.id).exists(): postId.likes.add(request.user) postId.save() return HttpResponseRedirect (reverse("index")) else: postId.likes.remove(request.user) postId.save() return HttpResponseRedirect (reverse("index")) return HttpResponseRedirect (reverse("index")) post.html <form method="post" action="{ url 'like_post' post.id }"> {%csrf_token%} {% if request.user in post.likes.all %} <button type="submit" style="background: none; outline: none; border: none; color: inherit; font: inherit; line-height: normal; overflow: visible; padding: 0;"> <svg xmlns="http://www.w3.org/2000/svg " width="16 " height="16 " fill="currentColor " class="bi bi-heart-fill " viewBox="0 0 16 16 "> <path fill-rule="evenodd " d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z "/> </svg> </button> {% else %} <button type="submit" style="background: none; outline: none; border: none; color: inherit; font: inherit; line-height: normal; overflow: visible; padding: 0;"> <svg xmlns="http://www.w3.org/2000/svg " width="16 " height="16 " fill="currentColor " class="bi bi-heart " viewBox="0 0 16 16 "> <path d="m8 2.748-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 … -
How to set the access token in Insomnia to access DRF API
My Django settings are as follows REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"], "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), } SIMPLE_JWT = { "AUTH_HEADER_TYPES": ("JWT",), "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), } In Insomonia, I do a post a http://127.0.0.1:8000/api/v1/jwt/create/ and I get back the refresh and access token. When I go to the "POST", I choose "BEARER, and pass in the "TOKEN", but I get { "detail": "Authentication credentials were not provided." } I am not sure how to correctly pass the JWT? -
Django model location from a view
In my models.py few models related to the different entities class GuardSecurity(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) etype = models.CharField(max_length=64, default='GuardSecurity', editable=False) class SecuredFaciliy(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) etype = models.CharField(max_length=64, default='SecuredFaciliy', editable=False) facility_name=models.CharField(max_length=64) adress=models.CharField(max_length=64) class License(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) etype = models.CharField(max_length=64, default='License', editable=False) license_name=models.CharField(max_length=64) license_description=models.CharField(max_length=200) class Equipment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) etype = models.CharField(max_length=64, default='Equipment', editable=False) equipment_name=models.CharField(max_length=64) class AllEntity(models.Model): id = models.UUIDField(primary_key=True) etype = models.CharField(max_length=64) class Meta: managed=False db_table="entity_full_list" They all in common have UUID as the primary key. I implement an SQL view on those models create view entity_full_list as select id, etype from entity_equipment union select id, etype from entity_guardsecurity union select id, etype from entity_license union select id, etype from entity_securedfaciliy To solve the problem of finding a relevant model from a view table I added an etype column that points to the model (string that after can be translated to a command ) Is there another way to point to the exact model from my view? -
How to perform 2 operations in parallel?
I have a problem and I can't figure it out. I have the following code that must save the data that is sent to him by an http request, first on the aws bucket and then by a request on the db. Except that 1 of the 2 operations does not work. Is there a way to do the 2 operations in parallel? @staticmethod def ingest_data(video, metadata, video_dst_path, metadata_dst_path, detected): """ Method that insert a video and a json metadata file into AWS-S3 :param video: video file forwarded by the ingestion endpoint :param video_dst_path: path to save the video on AWS-S3 :param metadata: json file forwarded by the ingestion endpoint :param metadata_dst_path: path to save the json on AWS-S3 :return: response :type {"message": ""}, code status """ try: # This part is for EAV exit plan files = {'video': video, 'metadata': metadata, 'detected': detected} # threading.Thread(target=forward, args=(files,)).start() ########################################################### # resp = requests.post('http://192.168.1.175:8000/forward', files=files) print(files, flush=True) print(metadata,flush=True) print(resp) sleep(15) print ('DENTRO IF RESPONSE 200 ') s3 = boto3.resource( service_name='s3', aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"), aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY") ) object = s3.Object(os.getenv("BUCKET_NAME"), video_dst_path) object.put(Bucket=os.getenv("BUCKET_NAME"), Key=video_dst_path, Body=video) print('Dumping and creating object {} in S3 {} bucket'.format(video_dst_path, os.getenv("BUCKET_NAME")),flush=True) object = s3.Object(os.getenv("BUCKET_NAME"), metadata_dst_path) object.put(Bucket=os.getenv("BUCKET_NAME"), Key=metadata_dst_path, Body=metadata) print('Dumping and creating object {} … -
Can't find the error in my django project
I am creating a booking website for hotels using Django, I used the booking api to get the hotels with its images and location highlights... I sent to the django template a list of dictionaries from the backend, each dict represents a hotel, now there is two apis request that I am using 1- To get all the hotels 2-To get the images and location highlights of the hotel based on its id that 1 will give me alongside other info like the name and address... (when a button is pressed) I implemented a loop in the template that will fetch all the hotels from the list on the page and I used the id of the hotel to pass it to a url namespace in the template (Template.html) where I want to call a function (book_now) and pass the arguments below: id of the hotel, name of the hotel, address of the hotel. Now what's happening is that when I choose certain destination like Berlin or Istanbul or Paris I get this error: NoReverseMatch at /homepage/ Reverse for 'book_now' with keyword arguments '{'id_hotel': **'6140138'**, 'name': 'Vital Hotel Fulya Istanbul Sisli', 'add': 'FULYA MAH. MEHMETÇİK CAD. NO: 61 İÇ KAPI … -
When saving ModelFormSet it reads the whole underlying table?
I don't know how to explain the problem in my title, so if someone knows how to better phrase the problem I'm going to describe, I hope there is a way to update the tile. I have to say I already tried to search with google, for a solution, but I'm not able to find something useful I tried to follow there video tutorial (after reading the official Django documentation of course) Video 01 Video 02 I'm using an old version of Django, because I have to connect to MS SQL Database, and this mix of python+django+mssql-backend is the only combination found functioning (I tried with the latest version of Django and Python, but I had to mess around with the mssql-backend because there were a lot of error about deprecated function, for example ugettext_lazy instead of gettext_lazy and many more...) I'm trying to create a small interface to an already existing MS SQL Database (so I can't change the structure of the database). I'm still learning Django, so I'm pretty sure the problem is mine, I have misunderstood something :( Currenty I created a page to search the interesting rows in database table and a page to edit all … -
how to edit urls.py?
i need to create url with this path graphs/<direction>. The direction should be a string because it's the name of some department. i've tried to do this kind of formating, but it didn't work. It tells me that: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/graphs/PS/ urls.py from django.urls import path from . import views urlpatterns = [ path('<str:direction>', views.ViewDashboard.as_view()), ] views.py class ViewDashboard(View): def get(self, request, direction: str): string_query = request.get_full_path().split(f"{direction}/")[1] entry = Department.objects.get(department__exact=direction) data = { "title": f"Графики для направления: {direction}", "level_navigation": { "level": 2, "name_level_1": "vm", "url_level_1": "", }, "offset": eval(entry.info_grafana), "grafana_ip": grafana['ip_grafana_server'], "https": grafana['https'] if grafana.get('https') else 'http', "from": "now-30d", } if string_query: string_query = string_query[1:].split("&") for query in string_query: if query.startswith('from='): data['from'] = query.split('from=')[1] return render( request, template_name='graphs/graphs.html', context=data ) and my graphs.html {% extends "vm_mon/wrapper.html" %} {% block content %} <div class="container"> <iframe src="{{ https }}://{{ grafana_ip }}:3000/d/{{ offset.uid }}/{{ offset.slug }}?orgId=1&from=now-30d&to=now&refresh=1d" width="100%" height="1600" frameborder="0"></iframe> </div> {% endblock %} -
About shipping structure in django ecommerce
I wanted to ask what kind of structure should I use for my shipping fee. I wanted to fix my shipping fee to a certain number may be 30$, but then when I want to change the number I can do that in the admin panel, and also for a certain threshold I want to give my customers free shipping. So what do you suggest friends? Should I have a separate class for shipping? or can I finish it in my Order class by adding one field?