Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I pass an image from URL to a Django template?
I have the following view: import requests def home(request): r = requests.get("https://via.placeholder.com/150") # Use the headers (r.headers) for something here ... return render(request, 'index.html', {'image': r.content}) And then in template, I want to use the image in an <img> tag, like so: <img src="{{ image }}"> Unfortunately, the image is broken in the template. When printing r.content, I get the following: >>> r.content b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x96\x00\x00\x00\x96\x04\x03\x00\x00\x00\xce/l\xd1\x00\x00\x00\x1bPLTE\xcc\xcc\xcc\x96\x96\x96\xaa\xaa\xaa\xb7\xb7\xb7\xc5\xc5\xc5\xbe\xbe\xbe\xb1\xb1\xb1\xa3\xa3\xa3\x9c\x9c\x9c\x8b*p\xc6\x00\x00\x00\tpHYs\x00\x00\x0e\xc4\x00\x00\x0e\xc4\x01\x95+\x0e\x1b\x00\x00\x01\x00IDATh\x81\xed\xd21o\x830\x18\x84\xe1\x8b1&\xa3\t\xb4s\x93!3\xde:\xc2\xd0\x9d\xaa\x1d\x18\x89\x84P\xc6D\x91\x98QR\xa9\xfd\xd9\xfd\x0ci;\x9b\xb5\xf7\x8c\x87\xf4\x06\x1c\x03DDDDDDDDDD\xb4\x82I\xd3\x16\xc7\xdb\xdfd\xa7\xc9|\x15\xa1\xad-\xd4\xd0\xd7\xd1\xe3\xa1\xfcY\x94\x9d&\xd7\xe7\x81)\x97"\x91\xdfOZ\xd5\xc2\xe4:\x03\xa2\xd4N\xd3\x80}`\xeb\xc5!y\x97/-\xa3\x11\xb8\xaa\x13\xa0\xdf\xec4\xe5x\x0el\xa1\xc2\xea\xbcAU\xc6\xd2r\xae\x96E[?\xe9\x1c\xcd\x82V\xd7\xb4\x95/ \xd9\xe0\xde\xea\x9a\xce\xca\xa3\xe0\x96\x1c\xd18\xbf\x97\xc9\xee-\x99>\x16\xbd\x17\x10\xdb\xf9\xbc\xd6\x9f\xbf\xad\xd8.:/\x07s\x92\xff\xf1\t8\xbe\x16s\xcbO\x03v\xe1\xad\xf5\xe5P\xc8\xfd\xaa\xa135\xce-?\xb9\xfe!\xbc\x15\x9f\xe5\xce\xfb{\xafF\x7f\xbf|\xcbO\x0b\xee=\x11\x11\x11\x11\x11\x11\x11\x11\x11\xfd?\xdfY\xa5%Q\x8a\xf0\x7f\xae\x00\x00\x00\x00IEND\xaeB`\x82' What do I need to do to format the content to be usable in my template? Thanks for any help! Edit I know the URL can be used in the <img> tag directly. However, I need a specific header from the URL in my Python code, so this way, I can save one extra request. -
Django there is no unique constraint matching given keys for referenced table
I have 3 models: class Event_type(models.Model): """ Event_type is like a category model for patient, datebase relationship is one to many """ name = models.CharField(max_length=40,unique=True) class Meta: verbose_name = "event_type" verbose_name_plural = verbose_name def __str__(self): return self.name class Patient(models.Model): patient_id = models.AutoField(unique=True, primary_key=True) # patient identification patient_name = models.CharField(max_length=30,unique=True,verbose_name='patient_name') class Meta: verbose_name = 'Patient' verbose_name_plural = verbose_name ordering = ['-patient_id'] def __str__(self): return self.patient_name class Event(models.Model): event_id = models.AutoField(unique=True, primary_key=True) event_type = models.ForeignKey(Event_type, on_delete=models.CASCADE, blank=True, verbose_name='event type', to_field='name' ) event_value = models.PositiveIntegerField(default=0, verbose_name='even value', blank=True) event_unit = models.CharField(max_length=100, blank=True, verbose_name='event unit') event_time = models.DateTimeField(auto_now=False,verbose_name='event time') patient = models.ForeignKey(verbose_name='patient', to='Patient', to_field='patient_id', on_delete=models.CASCADE) class Meta: verbose_name = 'Event' verbose_name_plural = verbose_name ordering = ['-event_id'] def __str__(self): return self.event_type.name Event is the primary table,Event_type and Patient are both foreign tables of it. After I add: to_field='name' into class Event error comes: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "patients_event_type" Any friend can help ? -
API returning an array inside of an object how to display contents- Django
So I am requesting spot price from cex API, it returns something like this {"data":[{"amount: "67000.0", "base": "BTC", "currency": "USD"}]} of course there is more than one returned so I want to loop over it. In my views.py I am passing it into my context 'price': price. Then inside of my .html file I have a list with a for loop for example: <ul> {% for x in price %} <li>{{ x }}</li> {% endfor %} </ul> Then when I open my .html page I get data But what I'd like to be able to do is make a table where I have three columns to show the amount, base and currency. I am unsure on how to extract this data individualy? -
Unable to install Django Version 1.11.22 with python 2.7 installed on windows 10
I have python 2.7 installed on my machine globally and the pip version is pip 20.3.4. I want to install Django version 1.11.22. When I am trying to do so with pip install Django==1.11.22, I am getting the error as mentioned in the picture. This is not just while installing Django, I am getting the same error while installing anything like pip install openpyxl. -
400 (Bad Request Vue Js, axios and Django rest framework for POST and PUT Method
My Get and Delete Request is working perfectly. But, getting 400 Bad request while POST or PUT method are calling. And for your kind information my Django rest framework is working fine in POST-MAN and in my local http://127.0.0.1:8000/doctor. And I am including my local machine picture too. This is working fine. In my Axios code: data(){ return{ doctors:[], modalTitle:"", DoctorName:"", DoctorId:0, DoctorNameFilter:"", DoctorIdFilter:"", doctorsWithoutFilter:[] } }, methods:{ refreshData(){ axios.get(variables.API_URL+"doctor/") .then((response)=>{ this.doctors=response.data; this.doctorsWithoutFilter=response.data; }); }, addClick(){ this.modalTitle="Add Doctor"; this.DoctorId=0; this.DoctorName=""; }, editClick(doc){ this.modalTitle="Edit Doctor"; this.DoctorId=doc.id; this.DoctorName=doc.name; }, createClick(){ axios.post(variables.API_URL+"doctor/",Qs.stringify({ data:this.DoctorName })) .then((response)=>{ this.refreshData(); alert(response.data); }); }, updateClick(){ axios.put(variables.API_URL+"doctor/"+this.DoctorId, Qs.stringify({ data:this.DoctorName })) .then((response)=>{ this.refreshData(); alert(response.data); }); }, deleteClick(id){ if(!confirm("Are you sure?")){ return; } axios.delete(variables.API_URL+"doctor/"+id) .then((response)=>{ this.refreshData(); alert(response.data); }); }, FilterFn(){ var DoctorIdFilter=this.DoctorIdFilter; var DoctorNameFilter=this.DoctorNameFilter; this.doctors=this.doctorsWithoutFilter.filter( function(el){ return el.DoctorId.toString().toLowerCase().includes( DoctorIdFilter.toString().trim().toLowerCase() )&& el.DoctorName.toString().toLowerCase().includes( DoctorNameFilter.toString().trim().toLowerCase() ) }); }, sortResult(prop,asc){ this.doctors=this.doctorsWithoutFilter.sort(function(a,b){ if(asc){ return (a[prop]>b[prop])?1:((a[prop]<b[prop])?-1:0); } else{ return (b[prop]>a[prop])?1:((b[prop]<a[prop])?-1:0); } }) } }, mounted:function(){ this.refreshData(); } } My Django settings.py: """ Django settings for DrAppointment project. Generated by 'django-admin startproject' using Django 3.2.8. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like … -
Django - Search field as form input from different table
I have a form which creates an object with the following two fields : These are created from my models.py as : class Propositions(models.Model): ClientName = models.CharField(max_length=50, null=False, blank=False) ClientSiret = models.CharField(max_length=14, null=False, blank=True) views.py : class PropositionsCreateView(LoginRequiredMixin, generic.CreateView): #LoginRequiredMixin template_name = 'propositions_/propositions-create.html' form_class = PropositionModelForm def form_valid(self, form): print(form.cleaned_data) form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('propositions_:propositions-list') hmtl : I've another table which stores few millions companies and their respective ids: class Companies(models.Model): CompanyName = models.CharField(null=False, blank=True) OfficialID= models.CharField(null=False, blank=True) I'd like transform the "Client" input field as a "dropdown search input field" which filters results from the "Companies" table and also populates the id "N° Siret" once the name is found. What would be the most "djangoic" way of doing this ? -
Exclusion of admin.logenty from dumpdata
I am trying to dump my data using python manage.py dumpdata --exclude=admin.logentry but it still gets included in the final json. Any hint what am I doing wrong ? -
Processing Repeated Bootstrap Modals in Django
How do people process bootstrap modals in Django that need to be shown on multiple pages? Do you have a special class to handle a second form? Do you use Crispy Forms? For example, if I have a Contact Us modal that is launched from a navigation bar on all pages in the application, how would I appropriately process that modal information? I can't imagine copying and pasting the same modal form and view code all over. That's clearly not DRY. I would imagine that there would be a way to do this, since it's a common problem. -
Using Python's deepcopy for different django models
I have two different django models with many attributes which differ in only 1 or 2 attributes. Based on some conditions, I would want to read one row from one model of a table and write to the other table. As of now, I am reading a row into an object, doing a deepcopy and then changing the class name using python's __class__ so that data of other attributes is persisted and I can add details of other attributes. The reason for doing this is because there are so many attributes and manually trying to copy every attribute should be avoided if we can. An example code goes something like this. There is a Program model and a ProgramRepository model. The ProgramRepository model has an extra attribute owner program = get_object_or_404(Program,pk=id) new_program = copy.deepcopy(program) new_program.id = None new_program.__class__ = ProgramRepository new_program.owner = creator new_program.save() Will this cause any problems? Is there a better way to do this? -
DJANGO Boolean Field form not saving
I have a simple checklist that a driver in an imaginary scenario would have to tick off before starting his day. To accomplish this i have a model that has all the tick boxes: from django.db import models from accounts.models import User from Inventory.models import trucks class CheckList(models.Model): vehicle = models.ForeignKey(trucks, primary_key=True, on_delete=models.CASCADE) driver = models.ForeignKey(User, on_delete=models.CASCADE) breaks = models.BooleanField(null=False) wipers = models.BooleanField(null=False) cargo = models.BooleanField(null=False) # If the cargo checks false its not a fatal failure but should return a warning to the previous driver saying he didn't do his task successful and warning should be issued from the office tires = models.BooleanField(null=False) oil = models.BooleanField(null=False) gas = models.BooleanField(null=False) seatbelt = models.BooleanField(null=False) date_created = models.DateTimeField(auto_created=True) def __str__(self): return self.vehicle.nickname After the model i created this form: from django import forms from .models import CheckList class driver_form(forms.ModelForm): breaks = forms.BooleanField(widget=forms.CheckboxInput, required=False) wipers = forms.BooleanField(widget=forms.CheckboxInput, required=False) cargo = forms.BooleanField(widget=forms.CheckboxInput, required=False) tires = forms.BooleanField(widget=forms.CheckboxInput, required=False) oil = forms.BooleanField(widget=forms.CheckboxInput, required=False) gas = forms.BooleanField(widget=forms.CheckboxInput, required=False) seatbelt = forms.BooleanField(widget=forms.CheckboxInput, required=False) class Meta: model = CheckList fields = "__all__" exclude = ['driver', 'date_created', 'vehicle'] And finally i added this view: def driver_checkout(request, pk): items = trucks.objects.all() truck = trucks.objects.filter(pk=pk) form = driver_form() context = { 'items': … -
how to fix (Hidden field submitted_by) This field is required error in django
I am trying to hide the submitted by field in my forms.py because I don't want user to upload the assignment on the behalf of some other user. So what I am doing is I am hiding the field but before hiding I am setting the value of logged in user to that input text using javascript but I am getting this error. (Hidden field submitted_by) This field is required. forms.py class assignmentUploadForm(ModelForm): class Meta: model = Submissions fields = ('submitted_by', 'submitted_to', 'submission_title', 'submission_file', 'submission_status') widgets = { 'submitted_by': forms.TextInput(attrs={'class': 'form-control', 'type': 'hidden', 'id': 'user', 'value': ''}), 'submitted_to': forms.Select(attrs={'class': 'form-control'}), 'submission_title': forms.Select(attrs={'class': 'form-control'}), } template <form method="post" enctype="multipart/form-data" style="margin-left: 240px;"> {% csrf_token %} {{form.as_p}} <input type="submit"> var name = "{{user.username}}" document.getElementById('user').value = name; views.py class AddAssignmentView(CreateView): model = Submissions form_class = assignmentUploadForm template_name = 'project/assignment.html' -
Problem when I try to save data in my database Django
I tried to make a pure api Django and save some data in my database for practicing. But I have some problems when I try to save data. For example I tried this code for the post method def post(self, request, *args, **kwargs): form = UpdateModelForm(self.request.POST) if form.is_valid(): obj = form.save(commit=True) obj_data = obj.serialize() return self.render_to_response(obj_data, status=201) if form.errors: data = json.dumps(form.errors) return self.render_to_response(data, status=400) data = {"message": "Not Allowed"} return self.render_to_response(data, status=400) And here is my Form validation from django import forms from .models import Update as UpdateModel class UpdateModelForm(forms.ModelForm): class Meta: model = UpdateModel fields = [ 'user', 'content', 'image' ] And the model class UpdateQuerySet(models.QuerySet): #def serialize(self): # qs = self # return serialize('json', qs, fields=('user', 'content', 'image')) def serialize(self): list_values = list(self.values("user", "content", "image", "id")) return json.dumps(list_values) class UpdateManager(models.Manager): def get_queryset(self): return UpdateQuerySet(self.model, using=self._db) # Create your models here. class Update(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) image = models.ImageField(upload_to=upload_update_image, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now_add=True) objects = UpdateManager() def __str__self(self): return self.content or "" def serialize(self): try: image = self.image.url except: image = "" data = { "id": self.id, "user": self.user, "content": self.content, "image": image } data_json = json.dumps(data) return data_json … -
How can i send updated request from 1 api to another api
I'm calling update_profile api by which return Response(self.profile(request).data) is suppose tp give updated users profile. but the thing is it is not giving output in real time. If i change name it is not reflecting in single api hit. Changes being reflect in 2nd api hit. Because of same request is being passed to profile api. So How can i update request and then send it to self.profile Heres my code: @action(detail=False, methods=['get'], authentication_classes=(JWTAuthentication, SessionAuthentication)) def profile(self, request): user = self.get_user() if not user: raise AuthenticationFailed() return Response( {"status": 200, "message": "Success", "data": UserSerializer(user, context={"request": self.request}).data}, status=status.HTTP_200_OK) @action(detail=False, methods=['post'], authentication_classes=(JWTAuthentication, SessionAuthentication)) def update_profile(self, request): profile_serialize = ProfileSerializer(data=request.data) profile_serialize.is_valid(raise_exception=True) AppUser.objects.filter(pk=self.get_user().pk).update(**profile_serialize.data) return Response(self.profile(request).data) -
Django: When will `auto_now` field not be updated?
Suppose I have a Django app backed by Postgres, and in that app I have model called Contact with a DateTimeField called last_updated. Suppose last_updated has auto_now set to True. I know there are some circumstances in which last_updated will not get updated when a Contact record is updated: Contact.objects.filter(xxx).update(yyy) will not update last_updated unless last_updated is included in yyy Contact.objects.bulk_update(contacts_qs, [zzz]) will not update last_updated unless last_updated is in zzz Are there other ways to update modify Contact objects (barring accessing the DB directly) where last_updated won't be updated? -
Caught LDAPError while authenticating
After we upgraded the Python version from 3.6 to 3.9 and the Django version from 2.2.16 to 2.2.17, we are getting the below error while logging in to the application using Kerberos-AD authentication. Caught LDAPError while authenticating ****************: SERVER_DOWN({'result': -1, 'desc': "Can't contact LDAP server", 'errno': 107, 'ctrls': [], 'info': 'Transport endpoint is not connected'}) Python-ldap version > 3.3.1 django-auth-ldap version > 3.0.0 -
How to make dynamic source path of FileFieldPath in django?
Info: I am try to use FileFieldPath in django. I want to make FileFieldPath(path=dynamic). I want to make every user have there own Directory path for file selection. Is there a way to user define his path from django Admin? class SourcePath(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) source = models.CharField(max_length=255) class Articles(models.Model): post_by = models.ForeignKey(User, on_delete=models.CASCADE) file_path = models.FilePathField(path=SourcePath.source) -
Problems while implementing SSO using Django SAML2 Auth and AzureAD
The error the application throws is: ERROR:saml2.sigver:check_sig: ERROR:saml2.response:correctly_signed_response: Failed to verify signature ERROR:saml2.entity:Signature Error: Failed to verify signature ERROR:saml2.client_base:XML parse error: Failed to verify signature And it seems to be a Windows problem. Does anyone know how should I implement this? The command used to verify the XML is: C:\Windows\xmlsec1.exe --verify --enabled-reference-uris empty,same-doc --enabled-key-data raw-x509-cert --pubkey-cert-pem C:\Users\me\AppData\Local\Temp\tmp8wssc6_f.pem --id-attr:ID urn:oasis:names:tc:SAML:2.0:assertion:Assertion --node-id _579304c7-f1c4-5918-83ee-4b33c5df1e00 --output C:\Users\me\AppData\Local\Temp\tmpw9lbnowc.xml C:\Users\me\AppData\Local\Temp\tmpcg9l7jik.xml And it returns b"". Thanks in advance. -
Django filter form field objects by existing one-to-one relation
I'm new to django and still trying to figure out basic things. I have three models: pc, pcslot and card. pcslot contains the relations to slots and to pc. One pc can have multiple slots, each card can only be in one slot. class pcslot(models.Model): card = models.OneToOneField("card on_delete=models.SET_NULL, null=True, blank=True ) computer = models.ForeignKey('pc', on_delete=models.CASCADE, related_name='slots', editable=False ) Now I would like to exclude all already assigned cards from the form dropdown. I tried to filter the objects inside the form by adding this to the model def get_related(self): if(hasattr(self, 'pcslot')): return 1 return None But django object filter cannot access these methods, so filter(get_related=1) is not working: class pcslotForm(ModelForm): class Meta: model = pcslot fields = "all" def init(self, user=None, **kwargs): super(pcslotForm, self).init(**kwargs) self.fields['card'].queryset = card.objects.filter(get_related=1) What would be the best way to do this? Do I have to loop through all objects and compare or is there a builtin method I don't know yet? Thanks -
How to create a combined stacked bar chart and table to display on a HTML website
I am trying to create something like this: It is a combined bar chart with a table below it. Notice that the table headers and chart's x-axis are the same. I also want the headers and bars to be aligned although it's not shown in the picture. What is the best way I can do this? I am using Python, Django, HTML, CSS and Javascript to build this chart. Is there any library like chart.js to create this type of graph? -
Calculate 38 days from month last date in Django
let us consider date as invoice.created_at = datetime.date(2021, 11, 17) next_month_first_date here is getting the nextmonth first date next_month_first_date = (invoice.created_at.replace(day=1) + datetime.timedelta(days=32)).replace(day=1) # datetime.date(2021, 12, 1) Now I need last day of invoice.created_at month this_month_last_day = ? how to find last date of invoice.created_at month i.e 30/11/2021 and calculate 38 days from this_month_last_day? 38 days from this_month_last_day is 7/01/2021 -
How to access to request.user in def save() in models?
I want to create a user at the creation of an object. This object is linked to the user by a foreign key. I have override the def_save() method to create the user and link it to the object. Problem: I generate a random password for this user and I would like to send it by e-mail not to the just created user but to the user. def save(self, *args, **kwargs): if self._state.adding: super(Machine, self).save(*args, **kwargs) username = f"machine_{slugify(self.site.client.name).lower()}_{self.id}" password = User.objects.make_random_password() self.user = User.objects.create( username=username, password=password ) self.save(update_fields=['user']) send_mail( f'Password of {username}', f'Password: {password}', settings.DEFAULT_FROM_EMAIL, [self.request.user.email], fail_silently=True, ) else: super(Machine, self).save(*args, **kwargs) The problem is that I don't have access to self.request in this method. How can I access to request in my def save()? Or how can I get the password value in my view? -
How to change status of the object automatically?
I am working on a project, aim of the project is that user creates announcement and I need to change is_active status to False automatically after 30 days so announcement be active 30 days but I have no idea how to do that, I am using Django Rest Framework and VueJs. -
API full path in unit tests
Is there any way to specify full path for url when i test APIs. Now i'm doing it in this way: def test_product_types_retrieve(self): self.relative_path = '/api/api_product/' response = self.client.get(self.relative_path + 'product_types/') I should add relative_path part to every single request, but i want to set it, for example in setUp function. Without self.relative_path i will get http://localhost:8000/product_types/ instead of http://localhost:8000/api/api_product/product_types/ My project structure is following, every api have its own urls.py with urlpatterns settings. Project structure -
Django doesn't change language when visiting URL with language code
I'm facing a weird situation when trying to change language after appending the language code to the url example -- domain.pt/en If I visit the site normally throught the domain without the language code appended, it works perfectly, I'm able to change language without problem. If somehow I copy the link and paste it on the browser, the language switcher stops working. example -- domain.pt I have translated a few Django websites so far and found out this happens on all of them. #urls.py urlpatterns = [ path('i18n', include('django.conf.urls.i18n')), path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns( path('', include('base.urls')), prefix_default_language=True, ) template <form id="lang-switcher" action="{% url 'set_language' %}" method="post">{% csrf_token %} <input type="hidden" name="next" value"{{ redirect_to }}"> <select class="language_selector" name="language" id="" onchange="this.form.submit()"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{ language.code }} </option> {% endfor %} </select> </form> settings.py LANGUAGE_CODE = 'pt' TIME_ZONE = 'Europe/Lisbon' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ BASE_DIR / 'locale', ] LANGUAGES = [ ('pt', 'Português'), ('en', 'Inglês'), ('es', 'Espanhol'), ('fr', 'Francês'), ('de', 'Alemão'), ] For the … -
How to format date in html from month dd,yyyy to yyyy-mm-dd
I am trying to set value to the input of type 'date', i am fetching data from mysql table and set it as the value attribute of input tag. On first time it doesn't work, but if set date once then it starts working i.e. input tag shows the content of value attribute even after refreshing. For first time the date is shown as: Nov 12,2021 and from second time it shows like: 12-11-2021 Here is my code for view: def profile(request,id): project=Project.objects.get(id=id) if request.method=='POST': deadline=request.post.get('deadline') project.deadline=deadline project.save() return render(request,'edit_project.html',{'id':id,'project':project}) <html> <body> <form method="POST"> <input type='date' value={{project.deadline}}> <input type='submit' value='submit'> </form> </body> </html>