Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make multiple object in one request put or delete? Django Rest
It allow me to pass in json format data to post for creating record after i make def create so that json format like [{data:data,data:data}] can post in. How should i do so that i can also make put request with multiple object in one request or using post method to update? Below is views.py. from django.shortcuts import render from .models import ListForm # Create your views here. from rest_framework import viewsets from .serializers import ListFormSerializer from rest_framework import filters import django_filters.rest_framework from rest_framework.response import Response from rest_framework import status, viewsets class ListFormViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = ListForm.objects.all().order_by('group') serializer_class = ListFormSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter,) filterset_fields = ['group','key_description'] search_fields = ['group'] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=isinstance(request.data,list)) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) # return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) -
How to pass the values of a given table to a template based on the foreign key within that table that links to a value in another table?
I'm not sure the title is the most accurate way of stating my issue, and I'm very new to Django. I'm displaying speedrun entries. It's set up so users can enter their record information in a form, with a dropdown menu for the game, which is a foreign key to a GameName object. They enter their game on a separate page if it wasn't listed. I wanted people to be able to add their games because there are too many for me to list out in the short amount of time I have to do this. I have a page that displays all games entered into the dB so far. When a user clicks on the game name I would like to redirect to a page that lists all entries entered for that game title. This is where I am having trouble. I need to create a views function that can populate a html table with all relevant values from my object Record but based on the name of the game found in the GameName dB table. I can't come up with the right function to output all records/rows from the Record object that match a specific game_name/GameName pk. models.py … -
Django rename uploaded file: append specific string at the end
I'm restricting the upload button to allow only csv files. I need help please to append _hello at the end of each file uploaded by the user, but before the extension. (e.g. user_file_name.csv becomes automatically user_file_name_hello.csv) Optional: I'd like the original file to be first renamed automatically, then saved to my uploads directory. models.py from django.db import models # validation method to check if file is csv from django.core.exceptions import ValidationError def validate_file_extension(value): if not value.name.endswith('.csv'): raise ValidationError(u'Only CSV files allowed.') # Create your models here. class user_file(models.Model): user_file_csv = models.FileField(upload_to='documents/user_files/', validators=[validate_file_extension]) forms.py from django import forms from .models import user_file from django.forms import FileInput class user_file_form(forms.ModelForm): class Meta: model = user_file widgets = {'user_file_csv': FileInput(attrs={'accept': 'text/csv'})} fields = ('user_file_csv',) Thank you! -
django,postgres error:column " " of relation " " does not exist
I have 3 tables: event,event_type,patient both event_type and patient are foreign keys for event table. event fields:id, event_type(foreign key),event_unit, event_value,event_time, patient(foreign key) event_type fields: id, type_name patient fields : patient_id ,patient_name I used Django to build the tables: class Event_type(models.Model): type_name = models.CharField(max_length=40,null=True,unique=True) 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 Event(models.Model): event_id = models.AutoField(unique=True, primary_key=True) event_type = models.ForeignKey(Event_type, null=True, blank=True,on_delete=models.CASCADE, verbose_name='event type',default="",to_field='type_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,default="") and I have a csv file events.csv: import csv with open(r'/Users/williaml/Downloads/events.csv') as csvfile: spamreader = csv.reader(csvfile, delimiter=',' ,quotechar=' ') for row in spamreader: print(row) the output is: ['"PATIENT ID', 'PATIENT NAME', 'EVENT TYPE', 'EVENT VALUE', 'EVENT UNIT', 'EVENT TIME"'] ['"1', 'Jane', 'HR', '82', 'beats/minute', '2021-07-07T02:27:00Z"'] ['"1', 'Jane', 'RR', '5', 'breaths/minute', '2021-07-07T02:27:00Z"'] ['"2', 'John', 'HR', '83', 'beats/minute', '2021-07-07T02:27:00Z"'] ['"2', 'John', 'RR', '14', 'breaths/minute', '2021-07-07T02:27:00Z"'] ['"1', 'Jane', 'HR', '88', 'beats/minute', '2021-07-07T02:28:00Z"'] ['"1', 'Jane', 'RR', '20', 'breaths/minute', '2021-07-07T02:28:00Z"'] ['"2', 'John', 'HR', '115', 'beats/minute', '2021-07-07T02:28:00Z"'] ['"2', 'John', 'RR', '5', 'breaths/minute', '2021-07-07T02:28:00Z"'] Now I want to insert these rows into database: import psycopg2 conn = psycopg2.connect(host='localhost', dbname='patientdb',user='username',password='password',port='') cur = conn.cursor() import … -
name 'user' is not defined
I'm trying to make a custom registration page without using usercreationform i've made the model and imported it but when i run it I keep encountering this error NameError at /register name 'user' is not defined the line in particular is: if user.password != user.repassword: and i tried changing the method to GET instead of POST and i got a different error MultiValueDictKeyError 'fname' views.py from django.shortcuts import render,redirect from .models import User from django.contrib import messages def home(request): return render(request, 'home.html') def register(request): global user if request.method == 'POST': user = User() user.fname = request.POST['fname'] user.lname = request.POST['lname'] user.email = request.POST['email'] user.password = request.POST['password'] user.repassword = request.POST['repassword'] if user.password != user.repassword: return redirect("register") elif user.fname == "" or user.password == "" : messages.info(request,f"some fields are empty") return redirect("register") else: user.save() return render(request, 'register.html') models.py from django.db import models class User(models.Model): id=models.AutoField(primary_key=True) fname=models.CharField(max_length=100) lname=models.CharField(max_length=100) email=models.CharField(max_length=50) password=models.CharField(max_length=100) repassword=models.CharField(max_length=100) html page {%extends 'base.html'%} {%load static%} {%block content%} <link rel="stylesheet" href="{%static 'css/style.css'%}"> <form method="post"> {%csrf_token%} <label for="fname">First Name</label> <input type="text" name="fname" placeholder="Enter your First Name"><br> <label for="lname">Last Name</label> <input type="text" name="lname" placeholder="Enter your Last Name"><br> <label for="email">Email</label> <input type="email" name="email" placeholder="Enter your Email"><br> <label for="password">Password</label> <input type="password" name="password" placeholder="Enter a password"><br> <label for="repassword">Re … -
Method Not Allowed (POST): /property/like/
My form submit keeps throwing this error Method Not Allowed (POST): /property/like/ <form action="{% url 'property:like-post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="property_id" value="{{obj.id}}"> {% if request.user not in obj.liked.all %} <button class="btn love-badge btn-raised btn-wave btn-icon btn-rounded mb-2 white" type="submit"> <i class="mdi mdi-heart-outline"></i></button> {% else %} <button class="btn love-badge btn-raised btn-wave btn-icon btn-rounded mb-2 teal" type="submit"> <i class="mdi mdi-heart-outline"></i></button> {% endif %} </form> view.py def like_property(request): user = request.user if request.method == 'POST': property_id = request.POST.get('property_id') property_obj = Property.objects.get(id=property_id) if user in property_obj.liked.all(): property_obj.liked.remove(user) else: property_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, property_id=property_id) if not created: if like.value == 'Like': like.value == 'Unlike' else: like.value = 'Like' like.save() return redirect('property:list') urls.py app_name = 'property' urlpatterns = [ path('like/', views.like_property, name='like-post'), ] Any insight on anything I'm doing wrong would be appreciated. -
Django SetPasswordForm doesn't render anything
Django's SetPasswordForm doesn't render anything, please help. This is what I got: views.py from django.contrib.auth.forms import SetPasswordForm @login_required def profile_security(request): template = "profiles/profile_security.html" form = SetPasswordForm print("form.base_fields: %s" % form.base_fields) context = {"profile_index_active": "active", "underline_security": "text-underline", "form": form} return render(request, template, context) html <form method="post">{% csrf_token %} {{ form.as_p }} </form> tried this html as well <form method="post">{% csrf_token %} <div class="form-group field-password1"> {{ form.new_password1.errors }} <label for="id_new_password1">New Password</label> {{ form.new_password1 }} </div> <div class="form-group field-password2"> {{ form.new_password2.errors }} <label for="id_new_password2">Repeat New Password</label> {{ form.new_password2 }} </div> <div class="form-group"> <input class="btn btn-success text-uppercase w-100" type="submit" value="Guardar nueva contraseña"> </div> </form> It does print the fields correctly: form.base_fields: {'new_password1': <django.forms.fields.CharField object at 0x7f49174e2790>, 'new_password2': <django.forms.fields.CharField object at 0x7f49174e2940>} but it doesn't render anything. What am I doing wrong? -
How to implement SSO across multiple sites
We have a couple of websites for which we are looking to implement Single Sign on. These are both Django / Wagtail websites. They both currently are using the standard Django login for authentication. We want to make it so that if a user logs into one of the websites they are automatically logged into the other and the same for logging out. I've done a google search and OpenID Connect seems to come up a lot of times but it seems to have quite a steep learning curve and I suspect a lot of it isn't relevant to my specific situation and I don't want to get lost down a long maze of technical details. It seems like I need to run my own OpenID Connect server which I have not done before. I've even tried looking on Docker Hub for a dockerised solution but I didn't find any of them with adequate documentation. Ideally I would like a solution where I could just add in a new Django authentication backend and perhaps just configure the host and port of the identity server in some settings file. Additionally I need to migrate the user database to the identity server … -
Create Django Form from ForeignKey
I'm trying to create a simple Django app that allows users to create and edit Recipes which consist of Ingredients. models.py class Recipe(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) class Ingredient(models.Model): api_id = models.IntegerField(primary_key=True) # id in Spoonacular database name = models.CharField(max_length=100) # human-readable name units = models.CharField(max_length=10) # unit of measure (e.g. 'oz', 'lb'), includes '' for 'number of' amt = models.PositiveIntegerField() # number of units recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) I have a detail view that displays the Ingredients for a given Recipe, along with buttons to add and remove ingredients. The primary key of the recipe is in the URL. view of detail page with add/remove ingredient buttons I'm trying to get it so that when a user clicks on the 'Remove Ingredients' button, it redirects them to a form where they can select which Ingredients from the given Recipe they want to remove. This is the part I can't get to work. As best I can tell, this requires a ModelChoiceField with a queryset where the ForeignKey of the Ingredient matches the primary key of the Recipe ('recipe_pk'). It seems like I need to pass the primary key of the given Recipe into the Form via **kwargs … -
Django ask for fill a form not required
I've a strange bug with my forms. In a page I must hande 2 separate forms, the 1st one have no problem at all and I can add the record in DB , the 2nd one raise me an error asking to fill a required data of 1st form. The POST dictionary looks ok Here the log: <QueryDict: {'csrfmiddlewaretoken': ['lvt5Ph2SA1xxFK4LMotdHOWk2JuZzYDo0OKWc77rKICYKYmemy3gl0dBphnRNcFb'], 'pk_atto': ['1.1'], 'pk_persona': ['1'], 'capacita': ['11'], 'Aggiungi_persona': ['persona'], 'tipo': ['fondo']}> <ul class="errorlist"><li>pk_particella<ul class="errorlist"><li>This field is required.</li></ul></li></ul> the views: if request.method == 'POST': if("Aggiungi_particella" in request.POST): save_atto = AttiPartenzeParticelleForm(request.POST) else: save_atto = AttiPartenzePersoneForm(request.POST) print(request.POST) print(save_atto.errors) if save_atto.is_valid(): save_atto.save() return redirect('/aggiungi_atto_partenza' + '/' + str(save_atto['pk_atto'].value())) the forms: class AttiPartenzeParticelleForm(ModelForm): pk_atto = forms.ModelChoiceField(queryset=Atti.objects.all(), widget=forms.Select (attrs={'class': 'form-control'})) pk_particella = forms.ModelChoiceField(queryset=Particelle.objects.all(), widget=forms.Select (attrs={'class': 'form-control'})) capacita = forms.CharField(max_length=30, widget=forms.NumberInput (attrs={'class': 'form-control'})) tipo = forms.CharField(max_length=30, initial="fondo", widget=forms.TextInput (attrs={'class': 'form-control'})) class Meta: model = Acquisizioni_Cessioni_particella fields = '__all__' class AttiPartenzePersoneForm(ModelForm): pk_atto = forms.ModelChoiceField(queryset=Atti.objects.all(), widget=forms.Select (attrs={'class': 'form-control'})) pk_persona = forms.ModelChoiceField(queryset=Persone.objects.all(), widget=forms.Select (attrs={'class': 'form-control'})) capacita = forms.CharField(max_length=30, widget=forms.NumberInput (attrs={'class': 'form-control'})) tipo = forms.CharField(max_length=30, initial="fondo", widget=forms.TextInput (attrs={'class': 'form-control'})) class Meta: model = Acquisizioni_Cessioni_particella fields = '__all__' and the HTML <div id="particella" class="content-section d-flex justify-content-center mt-5"> <form action="" method="POST" id="particella_f"> {% csrf_token %} <fieldset class="form-group"> <div style="visibility:hidden"> {{ form.pk_atto|as_crispy_field }} </div> <div … -
Fetch human-readable value of a Django Form field
I have the below code in my forms.py: class MultiFilterForm(forms.Form): review_choice =(('gte', 'Reviews >=',), ('exact', 'Reviews =',), ('lte', 'Reviews <=',)) reviewsign = forms.ChoiceField(choices = review_choice, required = False, widget = forms.Select(attrs={'id': 'reviewSign','class': 'form-control',})) What I need to do, is in my template, display the 2nd value in each tuple. I can write {{form.review.value}} and that'll access the 1st value in each tuple like gte or exact or lte, but how can I access the human readable form in the 2nd position in each tuple? To clarify, I've already read up on the get_FOO_display() for model fields. But again, this is for a form field to be displayed in the template, not the model field. Any pointers, please let me know! I'm at my wits end. Thanks -
Using DRF FlexFields on Extra Actions
I want to use flexfields on viewset extra action serializers.py class FarmSerializer(FlexFieldsModelSerializer): class Meta: model = Farm fields = [ 'id', ... 'varieties', 'conditions', 'created_at', 'updated_at', 'created_by' ] expandable_fields = { 'varieties': ('labels.serializers.VarietySerializer', {'many': True}), 'conditions': ('labels.serializers.ConditionSerializer', {'many': True}), } views.py class GrowerViewSet(BaseViewSet): ... serializer_class = GrowerSerializer @action(detail=True, methods=['GET']) def farms(self, request, pk=None): ... serializer = FarmSerializer(queryset, many=True) return Response(serializer.data) Then, when I request http://localhost:5000/api/labels/grower/3/farms/?expand=varieties,conditions flexfield expand params dont work: -
Django how do you loop using range through two lists simultaneiously
I'm working with Django and would like to iterate through two lists so that the're side by side: my views file: def displayDict(request): data = ["a", "b", "c"] data2 = ["x", "y", "z"] return render(request, 'chattr.html', {'range': range(0,len(data)-1),'dictItems': data, "otherDict" : "other_bot", "dictItems_bot": data2, "otherDict2": "bot" , "duo" : (data, data2)}) my template: {% for i in range %} <p> {{i}} <br> <b>{{otherDict}}:</b> {{dictItems.i}} <br> <b>{{otherDict2}}:</b> {{dictItems_bot.i}} <br> {% comment %} {{a|add:1}} {% endcomment %} </p> {% endfor %} I'd like a webpage that looks like: other_bot: 'a' dictItems_bot: 'x' other_bot: 'b' dictItems_bot: 'y' other_bot: 'c' dictItems_bot: 'z' Currently nothing renders except the bot names: other_bot: dictItems_bot: other_bot: dictItems_bot: I may also be able to do this inner loop using tuples, Django Template: looping through two lists. But this would be a lot more complex,... -
How can I define and refer to custom user groups in Django that I can sort against like user.is_superuser?
I’ver created some custom user groups in my Django app because I want to show them different admin fieldsets. I thought they would work similarly to user.is_superuser. But they don’t. I have this def in my ModelAdmin: def is_approver(user): return user.groups.filter(name='approver').exists() (I don’t know what that’s called, by the way. Do you just call it a “def”?) So this works: def get_fieldsets(self, request, obj=None): if request.user.is_superuser: return self.superuser_fieldset I get the expected fieldset. But this doesn’t work: def get_fieldsets(self, request, obj=None): if request.user.is_approver: return self.approver_fieldset However, this does work: def get_fieldsets(self, request, obj=None): if request.user.groups.filter(name='approvers').exists(): return self.approvers_fieldset So, I guess my basic question is: why don’t my defs work like I expect? (Python 3.9.7, Django 3.1) -
In Django, how do I define a string value for IntegerChoices enum?
I'm using Django 3.2 and Pythnon 3.9. In my model, I define an int enum. I woudl also like to define readable string values for it, so I tried class Transaction(models.Model): class TransactionTypes(models.IntegerChoices): BUY = 0 SELL = 1 labels = { BUY: 'Buy', SELL: 'Sell' } translation = {v: k for k, v in labels.items()} but this definition fails with the error TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict' How would I define strings for each value? I don't mind if hte strings are just the literal variable names (e.g. "BUY", "SELL") -
Django bulk update db table using model from html table
MODEL class BGD(models.Model): #need to update name # id=models.IntegerField(primary_key=True) Workgroup = models.CharField(max_length=50) Center = models.CharField(max_length=50, blank=True, null=True) Description = models.CharField(max_length=250) InsertDate = models.DateTimeField(default=datetime.now, blank=False) Is_Active = models.CharField(max_length=25, blank=True, null=True) # def __str__(self): # return "%s" % (self.id) class Meta: managed = False db_table="table" View def Control_Bidding_Groups (request): B_G_Results=BGM.objects.all() if request.method == 'POST': data = request.POST.dict() data.pop('csrfmiddlewaretoken', None) print('//////',data) for i in data.B_G_Results(): print('???',i) obj = Bidding_Group_Description.objects.get(id=i[0].split("_")[1]) print('55',obj) # Bidding_Group_Description.objects.filter(id=id).update(Is_Active) if not str(obj.Is_Active) == str(i[1]): #here check int or char datatype since 1 not equal "1" obj.Is_Active = i[1] print(obj.Is_Active) obj.save() return render(request, "Control_Bidding_Groups.html", { "B_G_Results": B_G_Results}) else: return render(request, "Control_Bidding_Groups.html", { "B_G_Results": B_G_Results}) #, "edit": edit HTML <section id="golf"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mainbg padding-all-zero"> <div class="row panelBg"> <label class="parav" for="ddlSubmit"> <button class="btn btn-danger" value="Insert Records"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Submit</button> </label> <table class="table table-striped" width="100%"> <thead> <tr> <th>Workgroup</th> <th>Center</th> <th>Bidding Group Description</th> <th style="text-align:left;">Is Active</th> <th>Is Active</th> </tr> </thead> <tbody class="ui-sortable"> {% for d in B_G_Results%} <tr> <td>{{d.Workgroup}}</td> <td>{{d.Center}}</td> <td>{{d.Description}}</td> <td>{{d.Is_Active}}</td> <td><input type="text" value="{{d.Is_Active}}" name="d_{{d.id}}"> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </form> </section> ERROR 'dict' object has no attribute 'B_G_Results' data {'17': '17', '18': '18', '19': '19', '74': '74', '75': '75', '76': '76', '77': … -
Printing the table with same foreign key as users id . Using django and mysql
I am trying to print all the lists in the list table for a logged-in user on my web app on the main page. I have assigned a foreign key in the list model. I am not familiar with the syntax but I do know I have to do something to match my foreign key with the user id and print all the stuff in the list model. for that I will run a for loop in my HTML, but the syntax to get objects from different table and match with the table im worming in, I m not familiar with it. my views.py look like this def addnew(request): if request.method == 'POST': form = Sublist(request.POST) if form.is_valid(): try: form.save() messages.success(request, ' Subscirption Saved') name = sublist.objects.get(name=name) return render (request, 'subscrap/main.html', {'sublist': name}) except: pass else: messages.success(request, 'Error') pass else: form = Sublist() return render(request, 'subscrap/addnew.html', {'form': form}) @login_required(login_url='login') @cache_control(no_cache=True, must_revalidate=True, no_store=True) def main(request): return render(request, 'subscrap/main.html') def mod(request): student = students.objects.all() return render(request, 'subscrap/mod.html' , {'students': student}) Add new is supposed to add new data to the list model. It works but there is one thing it doesn't know the id of the user and ask me when inputting … -
I am not able to create OneToOneField and ForeignKey field with User model?
I have these two model class TaskModel(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,primary_key=True) name=models.CharField(max_length=100) start=models.DateField() end=models.DateField() note=models.CharField(max_length=300) class ProfileModel(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) img=models.ImageField(upload_to='profileimg',blank=True) desc=models.TextField(max_length=500) occupation=models.CharField(max_length=100) martial=models.CharField(max_length=50) but when i run makemigrations command then it showing me this error:: eg:- app.TaskModel.users: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. This is my problem, I made TaskModel as a ForeignKey but it working like OneToOne Filed. I am new in django please help me? -
PYODBC not looping through sql queries
I currently have a view function in Django that is needed to calculate 2% interest on accounts that are in debt of more than 200 and print that to an excel sheet However, I am running into a problem whereby my function is only displaying one record for each table it loops through The structure of the function is as follows: It loops through the database fetching a list of table names: def InterestCharge(request): # Getting list of DB Names cnxn = pyodbc.connect('DRIVER={SQL Server};' 'SERVER=;' 'PORT=;' 'UID=kyle_dev_ro;' 'PWD=;') databaseName = "SELECT name FROM sys.databases WHERE database_id > 4 AND name <> 'SageEvolution' AND name <> 'DEMO' AND name <> 'Stonearch' AND name <> 'Caro Brooke HOA' AND name <> 'Casper' AND name <> 'Copy of Dennehof' AND name <> 'Founders View' AND name <> 'Hadedas' " \ "AND name <> 'Hillside' AND name <> 'Hillside Estate HOA' AND name <> 'SageCommon' AND name <> 'Villa Grove' AND name <> 'Kyle' and name <> 'Prudential House' AND name <> 'The Pearls of Fourways' " cursor = cnxn.cursor(); cursor.execute(databaseName); XdatabaseNames = cursor.fetchall() cursor.close() dbNames = [] for row in XdatabaseNames: rdict = {} rdict["name"] = row[0] dbNames.append(rdict) Then from there, it creates … -
Django, Effective way to redirect URL
When a DOM change occurs, a Javascript function fires and redirect to the same website's page with certain parameters. From the performance point of view, is the below method right? const fire=(arg)=>{ location.href = '/admin/arg/'; } Or should I use the {% URL 'path' %} tag ? if so, how ? -
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 …