Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Amazon S3 + Cloudfront with Django - Access error in serving static files (400 - Bad Request authorization mechanism not supported)
I'm struggling with an issue I'm encountering while testing my Django project's production environment, and more especially with my static (and media) content by the use of S3 + Cloudfront. As I'm developing on Django, I make use of the latest version of django-storage. The problem is that in spite of loading all the environment variables in my settings.py file (more details below), my website is still always trying to load the static/media content using the S3 direct URLs of the form https://bucket_name.s3.eu-west-3.amazonaws.com/static/filename. The static content cannot be loaded using these URLs and I get the following error : Failed to load resource: the server responded with a status of 400 (Bad Request). When I try to access these URLs in my browser I get the following message : The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256 This error seems quite weird to me as I specified the signature version in my settings file (perhaps I miss something?). The other point is that I want to rely on Cloudfront as first layer so that my files get a unique path of the form "https://xxxxxx.cloudfront.net/static/..." So I defined a Cloudfront distribution with OAI and Bucket policy configured. … -
Django qry returning related Id not object when getting list(Message.objects.select_related("message_from").filter(message_to=user.user_id).values())
I'm using Django Reset Framework to return an API response as per the below. class MesagesTo(APIView): def get(self,request): try: user = User.objects.get(user_id=request.user.user_id) Messages = list(Message.objects.select_related("message_from").filter(message_to=user.user_id).values()) return JsonResponse({"response" : Messages}, safe = False) except Exception as ex: print(ex) return HttpResponseForbidden("Message get failed") with a model definition of: class Message(models.Model): message_id = models.AutoField(primary_key=True) message_from = models.ForeignKey(KSWUser, on_delete=models.DO_NOTHING, null=True, related_name="message_from") message_to = models.ForeignKey(KSWUser, on_delete=models.DO_NOTHING, null=True, related_name="message_to") message_date = models.DateTimeField(auto_now_add=True, blank=True) message_readdate = models.DateTimeField(blank=True, null=True) message_title = models.CharField(max_length=255) message_body = models.TextField() class Meta: app_label="quickstart" db_table = 'messages' But the problem is the the response only includes the id of the related object (unsurprising as its the structure of the DB entity) I really want the name and email address members of the user objects. What query should I make? Thank you -
How to order queryset by subset
I have a form being rendered which displays questions to a test. I would like the checked, initial, values to be in the front of the queryset (the top checkboxes). Does Django have a function built in for this? Code: self.fields["questions"] = forms.ModelMultipleChoiceField( queryset=Question.objects.all(), # here I would like to order_by('initial') widget=CheckboxSelectMultiple, initial=self.instance.question_set.all().select_subclasses()) # the initial checked values -
AttributeError: 'str' object has no attribute 'get' in django
I'm inserting data into a model in Django, and getting AttributeError: 'str' object has no attribute 'get' for line cidr_block=vpc.get('CidrBlock', 'N/A'). The lambda_response is a list of dictionaries, so vpc is a dict. I'm not sure why this is happening, so any help is appreciated! This is the part of the code I'm talking about: lambda_client = boto3.client('lambda') lambda_response = lambda_client.invoke(FunctionName='arn:aws:lambda:us-east-1:558232680640:function:cbi-cloudportal-report-vpc') lambda_payload = json.loads(lambda_response['Payload'].read()) lambda_response = lambda_payload['body'] VPC_info = [] for vpc in lambda_response: # each dictionary in the lambda_response VPC_info.append(VPC( cidr_block=vpc.get('CidrBlock', 'N/A'), dhcp_options_id=vpc.get('DhcpOptionsId','N/A'), state=vpc.get('State','N/A'), vpc_id=vpc.get('VpcId','N/A'), owner_id=vpc.get('OwnerId','N/A'), instance_tenancy=vpc.get('InstanceTenancy','N/A'), name=vpc.get('Name','N/A'), description=vpc.get('Description','N/A'), environment=vpc.get('Environment', 'N/A'), vpn_connected=vpc.get('VpnConnected', 'N/A'), app=vpc.get('App','N/A'), )) -
Why are my CSS variables not recognized in Django?
I'm writing some CSS for a Django project and ran into an issue with CSS variables. I've used them in plenty of other sites but this is my first try in Django. I tested that the CSS is working by manipulating the font size so I know my static files are serving correctly. However, it seems that the CSS variable syntax does not work in Django. Is this correct? I can't seem to find any info on this when searching. -
My Python Django program creates a word document and then should (but doesn't) save the document in a Files model
There is a Files model, like this: class Files(models.Model): name = models.CharField(max_length=100) document = models.FileField(upload_to='files') event = models.ForeignKey(Event, blank = True, null = True, on_delete = models.SET_NULL) The function that tries to save to this, first creates the word document, which works. It then tries to add the document to the above model, which doesn't work. Here is one of the versions of what I tried: doc_name = "Event_" + str(event.pk) + "_Summary.docx" doc.save(f'{settings.DEFAULT_FILE_STORAGE}/{doc_name}') new_file = File(doc) print(new_file) new_record = Files() new_record.name = doc_name new_record.event = event new_record.document = new_file.file new_record.save() Any suggestions gratefully received. -
DRF serializers how to best handle indirect references to a FK?
Let's say I have the following models: class Thing(models.Model): thing_key = models.AutoField(primary_key=True) state = models.ForeignKey(State, db_column='state_key', on_delete=models.CASCADE, default=0) [...other fields unrelated to the question...] class Meta: db_table = 'THING' class State(models.Model): state_key = models.AutoField(primary_key=True) flag = models.IntegerField(unique=True) description = models.CharField(max_length=50) class Meta: db_table = 'STATE' And let's say I need to create new Things based on data received via POST requests. And let's say these POST requests do NOT contain the FK of Thing, which is state_key, but actually the flag field from the State model. What is the best way to implement serializers that help accomplish the following things: Create a new Thing even though the state_key is unknown. Return a serialized representation of the newly created Thing without exposing the state_key. After reading and re-reading the documentation, the best I could do is the following. It works, but I'm suspect there's a much more straightforward way to do it: class FlagField(serializers.RelatedField): def to_representation(self, value): return value.flag def to_internal_value(self, data): return State.objects.get(flag=data) class ThingSerializer(serializers.ModelSerializer): state_flag = FlagField(queryset=State.objects.all(), source='state') class Meta: model = Thing exclude = ['state'] Is this an acceptable approach? If not, what is wrong with it and how else could I accomplish the goal? Thanks in advance! -
Unable to get json response
Views.py js file in console i should be getting item was added PLease Help -
Not Found The requested resource was not found on this server. django tutorial
I was following a tutorial to build social media using Django at this link: https://towardsdatascience.com/build-a-social-media-website-with-django-part-5-feed-app-templates-66ddad5420ca I followed all the code as it says but once I'm done, I ran "python manage.py runserver" in the terminal, it gave me the Not Found The requested resource was not found on this server. I'm not sure why as I'm new to Django. you can find my code here: https://drive.google.com/drive/folders/1GSIK6ZoAsuOude3m6QKbiHhV8iAOZ7um?usp=sharing Please help. Thank you! -
Back to homepage if value in searchbar is null Django
Hi i want to ask about searchbar in django, i want to create something like if there is no results to show, show all or back to homepage. And my question is how to do it ? Here is my code: views: def SearchPage(request): kategorie = Kategoria.objects.all() srh = request.GET['query'] kategorie_search = Kategoria.objects.filter(nazwa__icontains=srh) dane = {'kategorie' : kategorie, 'kategorie_search' : kategorie_search, 'search' : srh} return render(request, 'search_result.html', dane) html: {% for kat in kategorie_search %} <div class="flex-container"> <div class="between"> <a href = "/episodes/{{ kat.slug }}"><img id="resize" src="{{ kat.miniaturka }}" class="imgh" title="{{ kat.nazwa }}"></a> <figcaption class="caption"><a style= "color: #ffffff" href = "/episodes/{{ kat.slug }}"> {{kat.nazwa}} </a></figcaption> </div> </div> {% endfor %} -
In Django , how to display a html file within a webpage inside a div?
Amateur here.I am working on a project. I wanted to display the html file in the div.I came across this How do I load an HTML page in a <div> using JavaScript? . I have come across issue here. In function load_home() { document.getElementsByClassName("Analytic_area").innerHTML='<object type="html" data={% static 'app1\Venues_location.html' %}" ></object>;' } The problem is with data={% static 'app1\Venues_location.html' %}" It asks me to put ';' where there is need and because of this, on runtime the path doesn't parse correctly. Here is Vscode Home is the button ,clicking on which a html will be displayed in the div below -
Django ManyToManyField - Causes error on record create
So Im essentially joining two tables using a manyTomanyField. Everything works well until I go to my admin page to create some test data. I get an error which reads below: invalid input syntax for type bigint: "John97" LINE 1: ...ducers_producer_product_categories"."producer_id" = 'John97' Where "John97" is the pk of one table, which is a OneToOneField relating to another table with a pk of type CharField. For context, the second table in my manyTomany relation also has a pk of type CharField. It seems to me like Django is attempting to save my pk as a BigInt in the through table and is running into problems. My question is, why is this happening and how do I stop it? I would like to keep my pk as a OneToOneField with my User table, so if there is an alternative Im all ears! -
django rest api getting KeyError: 'image'
trying to create a function based post api views.py: @api_view(['POST']) @permission_classes([IsAuthenticated]) def post_blog(request): user = request.user data = request.data if data['image'] and len(data['image']) == 0: blog = Blog.objects.create( title=data['title'], description=data['description'], user=user ) else: blog = Blog.objects.create( title=data['title'], description=data['description'], image=data['image'], user=user ) serializer = BlogSerializer(blog) return Response(serializer.data) models.py: class Blog(models.Model): blog_id = models.AutoField(primary_key=True, editable=False) title = models.CharField(max_length=100, null=False) description = models.TextField(null=False) image = models.ImageField(null=True, blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title serializers.py: class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = ['blog_id', 'title','description', 'image', 'user', 'created_at'] after performing post request to "POST http://localhost:8000/api/blogs/post/" I am getting this error: File "D:\work environment\Django_Api\codersavvy\blog\views.py", line 65, in post_blog if data['image'] and len(data['image']) == 0: KeyError: 'image' -
Using a condition in a python query
I want to add a condition to a query if some variables are available i.e. if name is provided or year is provided the query would be select * from tab1, tab2, tab3 where tab1.name='%s' and tab1.year=%s and tab1.id=tab1.tb2_id and tab3.id=tab1.tb3_id else the query should be select * from tab1, tab2, tab3 where tab1.id=tab1.tb2_id and tab3.id=tab1.tb3_id please how can I do that -
How to execute iptables and ipset using golang
I am trying to execute ipset and iptables in golang but I got an error: executable file not found in $PATH exit status 1 func main() { arg := "-h" out, err := exec.Command("iptables ", arg).Output() if err != nil { log.Fatal(err) } fmt.Printf("%s", out) } -
Is there any special installation needed for django in venv?
I am trying to run the command : bash ../download_content.sh create_django_tables But i am facing the error ** no module name django ** It's pointing me towards this manage.py file in the line import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chat.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) Help needed. Thanks in advance. -
"Expected a list of items but got type \"str\"." in django rest framework
I have an addproduct api in which frontend is sending a formdata in a post axios call. Formdata is used because there is an image field that need to be sent. But I got the following error. "Expected a list of items but got type "str"." in django rest framework. The data is sent in the following form as shown below. { "merchant": 8, "category": "[3,4]", "brand":2, "name":"pvahnjjthhgjhtest", "best_seller":true, "top_rated":false, "collection":2, "description":"abc", "featured": false, "availability": "in_stock", "warranty": "no_warranty", "rating":5, "main_product_image":null, "services": "cash_on_delivery", "variants": "[1,2]" } Here the main issue is on category and on variants.The error is also shown in these two fields. Since frontend is sending formdata, these two fields are sent as string. Now how can I handle these two fields on backend?? What I need is get 1 and 2 as pk . How to get pks from the string. I tried json.load but it doenst work. My models: class Variants(models.Model): product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = models.ImageField(upload_to="products/images", blank=True,null=True) thumbnail = ImageSpecField(source='variant_image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available') class … -
JavaScript Function capturing only the last (element) data-attribute (django)
I am working on this Django web-app where i need a button to work as a like button (which sends friend request) HTML code : <div class="slideshow-container"> {% for p in profiles %} <div class="profile-container"> <div class ="left-div"> <div class="mySlides fade"> <img src="media/{{p.image}}" style="width:100%" id="user-media-img"> <div class="text">{{p.user_id}}</div> </div> </div> <div class="right-div"> <div class="details"> <h1>BIO</h1> <p>{{p.bio}}</p> <h1>Age:</h1><p>{{p.age}}</p> <h1>Location:</h1><p>{{p.location}}</p> <h1>Hobbies:</h1> <p>{{p.hobbies}}</p> </div> </div> </div> <button class="btn2" onclick="sendFriendRequest(this)" id="like{{p.id}}" data-id="{{p.user_id}}">LIKE</button> {% endfor %} </div> Let's say I have 3 profiles so the for loop will run 3 times for it and will make 3*(profile-container) divs* PROBLEM is this data-id="{{p.user_id}}" is catching only the last profile's {{p.user_id}} no matter what which profile i am liking! I have tried this in static html file the code is working fine then but not in django. Here's my JavaScript code: <script type="text/javascript"> function sendFriendRequest(id){ //var reqtype = $(this).attr("data-id"); var reqtype = id.getAttribute("data-id"); alert("Capture: " + reqtype); payload = { "csrfmiddlewaretoken": "{{csrf_token}}", "reciever_user_id": reqtype, } $.ajax({ type:"POST", dataType:"json", url:"friend_request/", timeout: 5000, data: payload, success: function(data){ console.log("Success:" + data) alert('data in to payload') if(data['response'] == "Friend Request Sent"){ alert('Request Sent') } else if(data['response'] != null){ alert(data['response']) alert('second') } else if(data['response'] == "Already Sent!"){ alert('Request Already Sent!') } else { … -
Django empty list when using ModelChoiceField
First of all, I'm new to Django or MVC frameworks in general and I've got quite little experience in Python. I've read stackoverflow threads with similar title, but yet I'm missing some puzzle piece. After trying for some time, this is what I ended up with... which renders empty list. I think it's due to the fact, that the referred table has no database entries. I can't seem to figure out how to evaluate values based on FK from another table: models.py class Employees(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return self.last_name def get_absolute_url(self): return reverse('employees') class Tasks(models.Model): type = models.CharField(max_length=30) duration = models.IntegerField() def __str__(self): return self.type def get_absolute_url(self): return reverse('tasks') class Records(models.Model): employee_id = models.ForeignKey(Employees) task_id = models.ForeignKey(Tasks) date_from = models.DateTimeField() date_to = models.DateTimeField() def __str__(self): return self.id def get_absolute_url(self): return reverse('records') forms.py class CreateRecordForm(forms.ModelForm): employee_id = forms.ModelChoiceField(queryset=Records.objects.all().values('employee_id')) task_id = forms.ModelChoiceField(queryset=Records.objects.all().values('task_id')) date_from = forms.DateTimeField() #doesnt matter at the moment class Meta: model = Records fields = ('employee_id', 'task_id', 'date_from') views.py class RecordCreateView(CreateView): form_class = CreateRecordForm template_name = 'record_new.html' model = Records #fields = ['employee_id', 'task_id', 'date_from'] Generic view below renders the drop-down selection correctly, so it is doable. class RecordCreateView(CreateView): template_name = 'record_new.html' model = Records … -
scss not render to css in bootstrap 5 sass
I work on a project of Django with bootstrap 5 sass when I run my project, CSS effects do not apply. then I tried to (npm run scss) to discover the problem i got this error message: Rendering Complete, saving .css file... Error: EEXIST: file already exists, mkdir 'C:\Users\10\Desktop\Projects\Markvira\static\css\base.css' This is My project Files: base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Markvira</title> <link rel="shortcut icon" type="image/jpg" href="{% static 'images/base/favicon.ico' %}"/> <link rel="stylesheet" type="text/css" href="{% static './css/base.css' %}"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> </head> <body> <!------> <!--Navbar--> <header> <nav class="navbar navbar-expand-lg navbar-light"> </nav> </header> <!--Navbar--> <!-----> <main> {% block content %} {% endblock %} </main> <footer> </footer> <!-- Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script> </body> </html> settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') package.json "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "scss": "node-sass --watch ./static/scss/base.scss -o ./static/css" }, "dependencies": { "bootstrap": "^5.0.0-beta3", "node-sass": "^6.0.0" } } base.scss @import "custom_bootstrap"; @import "navbar"; html, body { margin: 0; height: 100%; background-color: black; } project tree can you help in the following: why base.css … -
django change password hash before saving to database
when I register a new user, the password is stored this way bcrypt$$2b$12$8rxaT66ecwuSGbScMh1/J.p9zuX1k5k1EJpYKefXndyk0fF4.LS2W, I need to store it without the bcrypt$ prefix because authentication works this way. How do I do that and from where to start? -
Is it possible to get the data from a formset before it is validated in Django?
I know that after validation, formset.cleaned_data gives a list of dictionaries of a formset. Now, I need to check certain fields if I experience an error, or I want to check fields of a formset before validation. if request.method == 'POST': formset = SampleFormSet(request.POST, prefix='sample') print(formset...?) #Should print all the data in the formset if formset.is_valid(): ... else: formset... #Modify it -
unable to fetch record in django using list
View code: below is my view code function through which I want to retrieve details of user in list. def followingview(request): if request.user.is_authenticated: uid= request.session.get('uid') ufg= userfollowing.objects.filter(userno_id=uid) flist=[] for i in ufg: flist.append(i.following_id) print(flist) urr= User.objects.filter(id=(flist)) context={'ufg':ufg,'ur':urr} return render(request,'following.html',context) Html Code: <li class="text-center"> {%for j in urr%} <h4 class="text-capitalize">UserName: {{j.username}}</h4> <p class="text-muted text-capitalize">FirstName: {{j.first_name}}</p> <p class="text-muted text-capitalize">LastName: {{j.last_name}}</p> {%endfor%} </li> -
How to get details of a class using a method defined in another class in python django?
drf---> CustomDBLogger--->customdblogger_views.py import getpass import socket import sys import time class Logger: def __init__(self): self.username = getpass.getuser() def LoggerParams(request): start = time.time() params = {'user': getpass.getuser(), 'class_name': request.__class__.__name__, 'method_name': sys._getframe().f_code.co_name, 'module_name': __name__, 'ip_address': socket.gethostbyname(socket.gethostname()), 'process_time': time.time() - start, } return params attributes = Logger().LoggerParams() I need to capture the class_name, method_name, module_name(app in which the class is defined) of another class using the above class. destination class(class of which, the details needs to be captured) drf---> accounts---> views.py from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.views import APIView from CustomDBLogger.customdblogger_views import attributes import logging class Request(APIView): @api_view(['GET']) def test_api_method(request): db_logger = logging.getLogger('db') db_logger.info("Successfully entered into function", extra=attributes) try: 1 / 0 except Exception as e: db_logger.exception(e, extra=attributes) return Response({'data': True}, status=status.HTTP_200_OK) finally: db_logger.info("exited from the function", extra=attributes) -
How to dynamically fill a hiddenfield in django-rest-frameowork?
I have two model's as:- Model 1 Location: name organization coordinates address Model 2 FloorPlan: name floor location(Foreign Key Location Model) organization I am trying to create an endpoint for performing CRUD operation on the FloorPlan Model Here is my serializer & view function:- serializers.py class FloorPlanSerializer(ModelSerialzer): class Meta: model = FloorPlan fields = '__all__' views.py class FloorPlanListView(ListCreateAPIView): queryset = FloorPlan.objects.all() serializer_class = FloorPlanSerializer Now the problem I am facing is I want to hide the organization field in the response, and would like to fill its value, from it's location instance(foreignKey) with POST or PUT/PATCH requests. Can anyone suggest me a way to achieve this.