Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to extend data in one column using xlsxwritter python
How to extend data in one column seperated by commas in xlsxwriter. for x in y: worksheet.merge_range("G"+str(row)+":"+"L"+str(row),x.multiple_values, centercell) row+=1 my data is dynamic for every loop i want to write values seperated by commas in particular column. for example column A | column B data | 654654,649824,63928,624684 -
Django redirect after save form in context_processor
I will if form saved, redirect my users. But it does'nt worked. Error: dictionary update sequence element #0 has length 0; 2 is required context_processor from .models import StaticPages from .forms import ContactForm from django.shortcuts import redirect from django.urls import reverse def main(request): pages = StaticPages.objects.all() if request.method == 'POST': # If the form has been submitted... contactform = ContactForm(request.POST) # A form bound to the POST data if contactform.is_valid(): # All validation rules pass contactform.save() return redirect(reverse('index')) else: contactform = ContactForm() # An unbound form context ={ 'pages':pages, 'contactform':contactform } return(context) my main urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), ... ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my core.urls: from django.urls import path from .views import MainDashBoard urlpatterns = [ path('', MainDashBoard, name='index'), ] -
Why do Django projects have so many files?
When I started my Django project, I encountered a lot of files in my folder What is the reason for the existence of many files in Django projects? And what is the difference between manage.py file and other files? I tried coding and using libraries in the __init__.py file but it didn't work. -
ValueError: Cannot assign "<User: salman>": "DoctorProfile.user" must be a "Doctor" instance
I'm trying to register two types of users the Doctor and the Patient but when I tried I got the following error which made me feel like I'm lost because I really don't know what's happning thi is the error Traceback (most recent call last): File "C:\Users\rachi\AppData\Local\Programs\Python\Python310-32\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request)..... .. raise ValueError( ValueError: Cannot assign "<User: salman>": "DoctorProfile.user" must be a "Doctor" instance. This is my code my models.py class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Doctor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) number_phone = models.CharField( _('االهاتف :'), max_length=50, blank=True, null=True) last_login = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % (self.user.username) class DoctorProfile (models.Model): } user = models.OneToOneField(Doctor, on_delete=models.CASCADE, primary_key=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(DoctorProfile, self).save(*args, **kwargs) def __str__(self): return '%s' % (self.name) # def get_absolute_url(self): # return reverse("doctor_detail", kwargs={"slug": self.slug}) def create_profile(sender, **kwargs): if kwargs['created']: DoctorProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) class Patient(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=50, verbose_name="الاسم ") last_login = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % (self.user.username) please tell me where is the probleme -
How to solve django.core.paginator.EmptyPage error?
I'm trying to filter and paginate objects in a template. I created a views and I have 3 objects. I want to list 1 object in a page. When I do it it shows the page numbers (should be 3 pages) when I click next it gives me the error: raise EmptyPage(_('That page contains no results')) django.core.paginator.EmptyPage: That page contains no results How can I solve that? views class EntitySelect(FormView): template_name = 'sgm/entity_select.html' form_class = EntitySelectForm def get_context_data(self): self.context = super().get_context_data(**self.kwargs) process_type = ProcessType.objects.get(id=self.kwargs['process_type']) entity = process_type.consolidate_on rows = getattr(entities, entity).objects.all() paginator = Paginator(rows, 10) page_number = self.request.GET.get('page') if page_number == None: page_number = 1 page_obj = paginator.page(int(page_number)) rows = getattr(entities, entity).objects.all() if entity == 'Merchant': tableFilter = MerchantFilter(self.request.GET, queryset=rows) else: tableFilter = CustomerFilter(self.request.GET, queryset=rows) rows_2 = tableFilter.qs paginator = Paginator(rows_2, 2) page_number = self.request.GET.get('page') if page_number == None: page_number = 1 page_obj = paginator.page(int(page_number)) self.context['entity_type'] = entity self.context['columns'] = [field.name for field in getattr(entities, entity)._meta.local_fields if field.name != 'entity_ptr'] self.context['tableFilter'] = tableFilter self.context['columns'] = [field.name for field in getattr(entities, entity)._meta.local_fields if field.name != 'entity_ptr'] self.context['rows'] = page_obj self.context['process_type'] = process_type template <table class="table table-striped table-condensed table-hover"> <thead> <th> Select </th> {% for column in columns %} <th> {{ column|title|pretty_title … -
403 Forbidden error response coming back in flutter http
<!DOCTYPE html> I/flutter ( 4559): <html style="height:100%"> I/flutter ( 4559): <head> I/flutter ( 4559): <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> I/flutter ( 4559): <title> 403 Forbidden I/flutter ( 4559): </title></head> I/flutter ( 4559): <body style="color: #444; margin:0;font: normal 14px/20px Arial, Helvetica, sans-serif; height:100%; background-color: #fff;"> I/flutter ( 4559): <div style="height:auto; min-height:100%; "> <div style="text-align: center; width:800px; margin-left: -400px; position:absolute; top: 30%; left:50%;"> I/flutter ( 4559): <h1 style="margin:0; font-size:150px; line-height:150px; font-weight:bold;">403</h1> I/flutter ( 4559): <h2 style="margin-top:20px;font-size: 30px;">Forbidden I/flutter ( 4559): </h2> I/flutter ( 4559): <p>Access to this resource on the server is denied!</p> I/flutter ( 4559): </div></div><div style="color:#f0f0f0; font-size:12px;margin:auto;padding:0px 30px 0px 30px;position:relative;clear:both;height:100px;margin-top:-101px;background-color:#474747;border-top: 1px solid rgba(0,0,0,0.15);box-shadow: 0 1px 0 rgba(255, 255, 255, 0.3) inset;"> I/flutter ( 4559): <br>Proudly powered by <a style="color:#fff;" href="http://www.litespeedtech.com This type of response is comming back please anyone help me asap Acctually I am sending requewst on my url but in response i am getting back the 403 forbidden error in response -
Django signals calling asynchronous task without celery
I'm doing in signal: @receiver(post_save, sender=User) def send_something(sender, instance, created, **kwargs): if created: loop = asyncio.get_event_loop() async_function = sync_to_async(send_id, thread_sensitive=True) loop.create_task(async_function(instance.id)) my another function is: def send_id(user_id): print(user_id) But function is not calling -
regex for telephone number in validation form
in a django template with the html pattern tag and boostrap for form validation with this regex it validates a sequence of numbers that can be separated by a dash "^[+-]?\d(?:-?\d)+$" example: 12-65-25-75-84 or 12-255-0214 the javascript : (() => { 'use strict' const forms = document.querySelectorAll('.needs-validation') Array.from(forms).forEach(form => { form.addEventListener('submit', event => { if (!form.checkValidity()) { event.preventDefault() event.stopPropagation() } form.classList.add('was-validated') }, false) }) })() and the html <input type="text" class="form-control" id="exampleFormControlInput1" name="tel" id="tel" placeholder="Tel" pattern="^[+-]?\d(?:-?\d)+$" required> </div> I would like to know how to modify it to have the possibility of putting spaces between the numbers (in addition to the dashes) example: 12 57 125-98-457 and limit the total number of digits to 15 (excluding spaces and dashes) for example a string like this: 12-28-35-74-12 or 12 28 35 74 12 or 123-478 25 12 124-15 thank you -
Django MigrationSchemaMissing exception on Azure SQL using service principal auth
I'm actually working on a client's project we are connecting Azure SQL DB via service principal authentication. Our client has given us access to Azure SQL and they have given us the credential for it. so to connect to Azure SQL we're using Microsoft's mssql-django package. so this is what the DB configurations look like. DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': <db_name>, 'USER': <db_user>, 'PASSWORD': <db_password>, 'HOST': "<url>.database.windows.net", 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'connection_timeout':60, 'connection_retries':3, "extra_params": "Authentication=ActiveDirectoryServicePrincipal", }, } so when I'm trying to run the migrate command I'm getting the below error raise MigrationSchemaMissing( django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The specified schema name "<db_user>@<azure_tenant_id>" either does not exist or you do not have permission to use it. (2760) (SQLExecDirectW)')) by looking at the error we can definitely say that either the schema is not created or the DB user that they have given us does not have permission to create the tables in the DB. can anyone please suggest what could be going wrong, this is definitely not an issue from the Django or from the django-mssql package but an issue … -
How to organize multithreading
I have code, comes up WARNING: QApplication was not created in the main() thread, but the code runs, but 1 time, when it starts to run 2 times the site dies, how can I arrange multi-threading that it would not crash? from .forms import UserForm from bs4 import BeautifulSoup from django import forms from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEnginePage import sys import time import re import requests regex = r"price_85d2b9c\s+\w+\D+(?P<price>\d+\s+\d+)" class Client(QWebEnginePage): def __init__(self,url): global app self.app = QApplication(sys.argv) QWebEnginePage.__init__(self) self.html = "" self.loadFinished.connect(self.on_load_finished) self.load(QUrl(url)) self.app.exec_() def on_load_finished(self): self.html = self.toHtml(self.Callable) print("Load Finished") def Callable(self,data): self.html = data self.app.quit() def index(request): submitbutton= request.POST.get("submit") From='' To='' url='' prices = [] form= UserForm(request.POST or None) if form.is_valid(): From = (form.cleaned_data.get("From")).partition(", ")[2] To = (form.cleaned_data.get("To")).partition(", ")[2] context= ({'form': form, 'From': From, 'To': To, 'submitbutton': submitbutton,'prices': prices}) return render(request, "index3.html", context) I tried using the QThreadPool Class, but it didn't work correctly. What can I do to make the code handle links and not crash. -
Django mysql connection errors
Try to connect my django project with MySQL using wamp server i am facing error "Django.db.utils.NotsupportedError" I am tried older version of django To solve this error, but it seems also Same error. -
How to pass a dictionary to an url in POST request in Python
I have to get information about product stocks from marketplace's API via POST request. API requires to send products IDs (sku) in url Example: https://api.market.com/campaigns/{campaignId}/warehouse/{warehouseId}/stocks/actual.json?sku=sku1&sku=sku2&sku=sku3 So I guess, I have to pass a dict like {'sku': '1', 'sku': '2', 'sku': '3'} But of course, It's impossible to create a dict with same keys. I don't know how to solve this task. I made a function, using urllib (urlencode) that works. But it create an url with only last element in params. params = {"sku": "ps-22-1", "sku2": "ps-22-7-2", "sku3": "ps-22-7-3"} def get_stocks(self, campaign_id, warehouse_id, sku): """ Method for parse stocks Parameters: campaign_id (int): client_id in Store warehouse_id (int): warehouse_id in Warehouse sku (str): product sku in Product Returns: data (json): JSON with stocks data """ url = f"{self.url}campaigns/{campaign_id}/warehouses/{warehouse_id}/stocks/actual.json?" req = requests.get(url + urllib.parse.urlencode(sku), headers=self.headers) if req.status_code == 200: return True, '200', req.json() return False, req.json()["error"]["message"] I keep products IDs in my DB in such model: class Product(models.Model): name = models.CharField(max_length=150) sku = models.CharField(max_length=10) -
Django: Exception Value: The 'image' attribute has no file associated with it
Hi everyone I'm trying to create an auction system with Django. But when I go to the item profile, Django sends me an error: Exception Value: The 'image' attribute has no file associated with it. auction.html {% extends "base.html" %} {% block content %} {% load static %} <div class="page-header"> <h1>OPEN AUCTIONS</h1> </div> <div class="container"> <div class="row"> {% for item in auction %} <div class="col-sm-4"> <div class="card border-secondary" style="width: 25rem;"> <div class="card-header"> Auction {{item.id}} </div> <img src="{{ item.image.url }}" class="card-img-top" width="250" height="180"> <div class="card-body"> <h3 class="card-title" style="text-align:center" >{{ item.object }}</h3> <p class="card-text">{{item.description}}<br> Price: ${{ item.open_price}}<br> End: {{ item.close_date }}</p> <form method="POST"> {% csrf_token %} <input type="number" name='auct_id' value={{item.id}} readonly> <button type="submit" class="btn btn-primary btn-sm">Go</button> </form> </div> </div> </div> {% endfor %} </div> </div> {% endblock %} If I remove item from <img src="{{ item.image.url }}" class="card-img-top" width="250" height="180"> the page work correctly but the image doesn't display. Like this: view.py @login_required(login_url="login") def auction(request): if request.user.is_superuser: messages.error( request, "super user can access to admin/ and new_auction page only" ) return redirect("new_auction") auction = Auction.objects.filter(active=True) for data in auction: check = check_data(data.close_date) if check is False: data.active = False data.save() check_winner( request, data.id ) check_prof = check_profile( request ) if check_prof is … -
How to deploy django application with celery and celery beat in digitalocean droplet?
Hello developers i nedd to deploy django application with celery and celery beat in digitalocean droplet. where celery worker and celery beat will execute simulteneoulsy. for celery worker: celery -A <project_name>.celery worker --pool=solo -l INFO for celery beat: celery -A <project_name> beatb -l INFO afterward it will run. -
Django ImageField not updating database if i click submit button, but does it if i click enter key
The problem is The problem is that after filling a form without an image and clicking on the submit button, django does nothing and the default image does not get displayed, but if i click the Enter key on my keyboard it works, it shows the default image Can someone please tell me why this is happening, and what is the solution for it I tried changing the url for the button, expecting it to work just as it would if I clicked enter. But that did not work. I have been stressing about this for the past week. And Thanks in advance for everyone who helped. -
Django - Only update FileField column without overriding other columns
In Django, I have a model: class List(models.Model): item = models.CharField(max_length=200) document = models.FileField(upload_to='documents/', null=True, blank=True) Also, I have a page which is to ONLY upload a file to List.document for an existing List: In views.py, I have def upload(request, item_id): if request.method == 'POST': item = List.objects.get(pk=item_id) form = ListForm(request.POST, request.FILES, instance=item) if form.is_valid(): form.save() messages.success(request, 'File saved successfully.') else: messages.error(request, f'File not saved properly: {form.errors.as_data()}') return redirect('home') . However, since the form doesn't include List.item, while clicking Upload, an error occurs File not saved properly: {'item': [ValidationError(['This field is required.'])]}. The easiest way may be add List.item as a hidden element in the html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-md-10"> <input type="file" class="form-control" name="document" /> </div> <div class="col-md-2"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Upload</button> </div> </div> </form> Nevertheless, is there a better way to get over this? Maybe any options to skip overwriting existing columns? Thanks! -
Trigger React Event from Django Frontend
I want to open a Dialog-window in React whenever the User clicks on the corresponding button in Navbar. The Problem is that the Navbar is part of a Django Frontend. I have tried updating a value in localstorage but I wasn't successful. I have tried using the window.addEventlistener() , but it wouldn't update if changes where made from the Django Navbar. useEffect(() => { window.addEventListener('storage', console.log("CHANGED")) return () => { window.removeEventListener('storage', console.log("CHANGED")) } }, []) Django Template <div class="navbar-nav mr-auto" id="ftco-nav"> <button id="experimentbtn" onClick="open_experiment()" class="btn nav-link">Experiment</button> </div> <script> function open_experiment() { localStorage.setItem('experiment', 'true'); } </script> <div id="root"></div> #This is where the React part is rendered The suggested solution doesn't have to be related to this, i just want to know if there is any other way to make Django communicate with React to trigger such an event switch? -
How to prune inactive / bad APNs tokens in Django-push-notifications
I'm using django-push-notifications (DPN) to send notification to an iOS app. When I send a notification, DPN gives me the response from APNs as a dict with the device tokens and their status. r = devices.send_message(message="Fancy pansy message.", sound="default") Where the response looks something like: r = [ { '<devicetoken1>': 'Success', '<devicetoken2>': 'BadDeviceToken', '<devicetoken3>': 'Success', } ] I have a view in Django which takes POST requests. I use this endpoint to post the message I send to APNs with send_message() as well as save the message to my DB. So my plan was to add the following simple logic to the same view to prune the DB each time I get feedback on expired / bad device tokens from APNs (or something like it, I may of course need to add more statuses than "BadDeviceToken"). for token_str, token_status in r[0].items(): if token_status == 'BadDeviceToken': APNSDevice.objects.filter(registration_id=token_str).delete() My question is if there is a better way of doing this? Should pruning be done with some periodic task instead? Are there any issues with doing this kind of logic in the views in Django? Or am I missing any existing solutions to this problem (pruning tokens) in either Django or DPN? Cheers! -
How can I get a Django template message displayed when I select a value from a dropdown list that matches a condition in the parent table?
I have a form whose constituent fields are foreign keys to respective parent models as shown below: class vehicle(models.Model): STATUS = [ (OPERATIONAL, ('Operational')), (GROUNDED, ('Grounded')), (NA, ('Not Applicable')), ] reg no = models.CharField(max_length=100, null=True) operationalstatus = models.CharField (max_length=100, choices=STATUS, null=True) #####child model### class managecar(models.Model): reg_no = models.ForeignKey(vehicle, on_delete=models.CASCADE, null = True) location = models.CharField(max_length=100, null=True) ####forms.py#### class manageForm(forms.ModelForm): class Meta: model = managecar fields = '__all__' I created a view as shown below and linked a url to it to be called by ajax on the frontend to trigger a message if vehicle selected in the form is 'grounded' but it returns 404 in the console while am expecting it returns a message of vehicle is grounded if I select a vehicle that is listed grounded in the parent model. views.py def validate_operation_status(request): grounded = request.GET.get('grounded', None) data = { 'is_grounded': vehicle.objects.filter(operational_status__iexact='grounded').exists() } return JsonResponse(data) ajax method $("#id_registration_no").change(function () { console.log( $(this).val() ); $.ajax({ url: 'ajax/validate-status/', data: { 'grounded': id_registration_no }, dataType: 'json', success: function (data) { if (data.is_grounded) { alert("This vehicle is grounded."); } } }); }); I'd appreciate to be guided in the right direction or someone to point out where I am failing. Thank you in … -
Django - Add help text to field inherited from abstract base class
I just discovered the "help_text" attribute at Django model fields which automatically adds help textes to fields e.g. in the admin panel. Again, what a nice Django feature! Now I have the problem that I want to add the help_text to a field which is inherited from a parent abstract base class... how could I achieve this? class AbstractBioSequence(models.Model): """ General sequence (DNA or AA) """ name_id = models.CharField(max_length=100, null=True) description = models.CharField(max_length=1000, null=True, blank=True) sequence = models.TextField() class Meta: abstract = True class DnaSequence(AbstractBioSequence): some_dna_field = models.TextField() # -------- I want to add a DnaSequence specific helper text to the "sequence" field here -
How to get Google Calendar API working in production to create an event
Problem I'm trying to solve: Using Google Calendar API to create a calendar event. It works on locahost but not in production following the Google Documentation. I'm looking for a solution to get it working in production. What I've tried: I've spent a long time looking at solutions on here including this popular one: Google Calendar API authorization working on localhost but not on Heroku but for me I'm not using pickle. I also attempted all the relevant changes in the answer in relation to my code but I still could not get it to work. I have also made sure that my API console includes the relevant permissions. What's happening: Terminal logs are showing that my code attempts to open a browser on the server machine "Please visit this URL to authorize this application" instead of popping up a browser window for the user. This is most likely because my first try block is failing - which I think is where the problem lies. Please also note I have replaced my redirect URL in the code below for privacy reasons to myurl.com/calendar/. The redirect is simply set to the same page where I am running the code from. Google … -
Unique constraint in my model in my django project?
I would like to configure my Teacher model so that I can have several teachers with the same name, the same age but different departments How to do ? class Teacher(models.Model): name=models.CharField(max_length=70) age=models.IntegerField() service=models.CharField(max_length=100) Exemple output on my database : Name Age Service Arnaud 29 Science Carmen 37 Medecine Arnaud 29 Geologie -
Django: Get multiple id's from checkbox
I'm having problems getting multiple IDs from checkbox. It shows an empty list, and if I inspect my page, it doesn't even show it's value. Unlike the other, obj.stage for example, if I highlight this it shows it's value. So it's not possible to get each id on checkbox? Or I'm just doing it wrong? Hope you can help me, thank you! index.html <a class="btn btn-primary btn-xs" href="/save/">Save</a> {% for obj in queryset %} <tr> <td><input type="checkbox" name="sid" value="{{obj.id}}"></td> <td>{{ obj.stage }}</td> <td>{{ obj.time }}</td> <td>{{ obj.sample_number }}</td> </tr> {% endfor %} views.py sid = request.POST.getlist("sid") samples = SampleHandle.objects.filter(id__in=sid)[0:11] -
Django - givingan unique ID to a blog post/element so it could be used with http referer
I am currently creating my first project and I am using an HTML template that I found online. It is a social media application where you should be able to upload a photo, like the photo, leave a comment, etc. The issue is that I implemented all those functions, but liking, commenting, copying the URL (share buttong) refreshes the whole page and you end up at the very beginning of the page, because I am not sure how to refer the user to the post they liked/commented. I am using return redirect(f'{request.META["HTTP_REFERER"]}#{photo_id}') , but since my posts don't have an unique identifier, it does nothing. Any tips would be greatly appreciated. Thanks in advance! -
Render options of ModelChoiceField
I want to render the options for a ModelChoiceField: {% for value, label in form.fields.event_type.choices %} <option value="{{ value }}" {% if form.fields.event_type.value|add:"" == value %}selected="selected"{% endif %}> {{ label }} -- {{ form.event_type.value }} .. {{ value }} </option> {% endfor %} But this does not work: selected="selected" is not set. The output: <option value=""> --------- -- 2 .. </option> <option value="1"> OptionOne -- 2 .. 1 </option> <option value="2"> OptionTwo -- 2 .. 2 </option> This is strange, since the output "2 .. 2" did not trigger the "if" to include selected. How to solve this?