Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework 'list' object has no attribute values
I have the code and error stacktrace below. I am trying to access localhost:8000/fundamentals/ but I get the error 'list' object has no attribute 'values' error web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner web_1 | response = get_response(request) web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 202, in _get_response web_1 | response = response.render() web_1 | File "/usr/local/lib/python3.7/site-packages/django/template/response.py", line 105, in render web_1 | self.content = self.rendered_content web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/response.py", line 70, in rendered_content web_1 | ret = renderer.render(self.data, accepted_media_type, context) web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 724, in render web_1 | context = self.get_context(data, accepted_media_type, renderer_context) web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 655, in get_context web_1 | raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request) web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/renderers.py", line 563, in get_raw_data_form web_1 | data = serializer.data.copy() web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 562, in data web_1 | ret = super().data web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 264, in data web_1 | self._data = self.get_initial() web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 412, in get_initial web_1 | for field in self.fields.values() web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 413, in <listcomp> web_1 | if not field.read_only web_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 412, in get_initial web_1 | for field in self.fields.values() web_1 | … -
Session key failed
i am creating todo app. After login when i add any task. It show error: failed 'SESSION_KEY'. When i debug the code it show SESSION_KEY. after removing the request.seesion from post method in TODOlist class it works. I don't know how to fix this issue. class Login(TemplateView): template_name = 'login.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): try: username = self.request.POST.get('username').strip() password = self.request.POST.get('password').strip() if username is None or password is None: return HttpResponse('Invalid User', 500) user = authenticate(request, username=username, password=password) if not user: return HttpResponse('User Doest exist', 500) else: login(request, user) if SESSION_KEY in request.session: return redirect('todolist') except Exception as e: return HttpResponse({'failed {}'.format(e, 200)}) class Todolist(TemplateView): template_name = 'todo_page.html' def get(self, request, *args, **kwargs): if SESSION_KEY in request.session: return render(request, self.template_name) def post(self, request): if SESSION_KEY in request.session: try: data = self.request.POST.get task_list = Task( user_id=request.session["SESSION_KEY"], task=data('task') ) task_list.save() return redirect('todolist') except Exception as e: return HttpResponse('failed {}'.format(e), 500) -
Django -- Forbidden (CSRF token missing or incorrect.): /vote/
I have a website with an AJAX upvote or downvote option on a post. The problem I am having is that the voting works on my Post detail page but not on my index page. I am getting the error Forbidden (CSRF token missing or incorrect.): /vote/ Both pages call the same view and URL pattern. index.html: {% for post in posts %} <span id="post_{{forloop.counter}}" data-value="{{post.id}}"></span> <button class="vote_action" value="upvote_button"> + </i></button> <span id="votes">{{post.points}}</span> <button class="vote_action" value="downvote_button"> - </button> {% endfor %} <script type="text/javascript"> // JQUERY - AJAX SCRIPT FOR voting $(document).ready(function(){ {% for post in posts %} $('.vote_action').click(function(e) { var postid = document.getElementById('post_{{forloop.counter}}').getAttribute('data-value'); var button = $(this).attr("value"); e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "vote" %}', data: { postid: postid, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'postvote', button: button, }, success: function(json){ if (json.length < 1 || json == undefined) { //empty } document.getElementById("votes").innerHTML = json['result'] }, error: function(xhr, errmsg, err) {} }) }) {% endfor %} }) </script> post_detail.html: <span id="vote_id" data-value="{{post.id}}"></span> <button class="vote_action" value="upvote_button"> + </i></button> <span id="votes">{{post.points}}</span> <button class="vote_action" value="downvote_button"> - </button> <script type="text/javascript"> // JQUERY - AJAX SCRIPT FOR voting $(document).ready(function(){ $('.vote_action').click(function(e) { var postid = document.getElementById('vote_id').getAttribute('data-value'); var button = $(this).attr("value"); e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "vote" … -
Photos removed from the disk continue to appear on the website
I'm developing a website for my student project. I use Django and Docker for containers. I cloned from GitLab the part that my friend did (code, photos, etc.) and then removed some photos from a folder with photos on my disk, but the photos still exist on my website (on localhost). I cleaned cache, removed and created containers again, double-checked my code, but still, photos appear. What can I do? Where are the photos stored? My code for showing photos: <div class="row justify-content-center"> <div class="col-12 col-lg-10"> <ul class="nav nav-tabs" id="bitTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="bit1-tab" data-toggle="tab" href="#bit1" role="tab" aria-controls="bit1" aria-selected="true">BIT1</a> </li> . . . <div class="tab-content" id="bitGalleryTabContent"> <div class="tab-pane fade show active" id="bit1" role="tabpanel" aria-labelledby="bit1-tab"> {% for i in i|rjust:15 %} <a style="border: 0;" href="{% static 'images/bit1/' %}{{ forloop.counter }}.png" title="BIT"> <img src="{% static 'images/bit1Thumbnails/' %}{{ forloop.counter }}.png" alt="BIT1"> </a> {% endfor %} </div> . . . -
Why DRF Nested Serializer is returning an error
I am using django rest framework for my rest api based project. I am using nested serializer to save child model object along with parent object. Below is snap of my code This is my parent model : class DeliveryNote(models.Model): vdate=models.DateField("Date") voucherno=models.OptionalCharField("Voucher No.") class Meta: verbose_name="Delivery Note" verbose_name_plural="Delivery Notes" db_table="INV_DeliveryNote" This is my child model : Class DeliveryItem(models.Model): deliverynote=models.ForeignKey(DeliveryNote,on_delete=models.CASCADE,related_name='items') itemname=models.CharField("Item Name") qty=models.FloatField("Quantity") class Meta: verbose_name="Delivery Item" verbose_name_plural="Delivery Items" db_table="INV_DeliveryItems" This is my parent serializer: class DeliveryNoteSerializer(eserializer): items=DeliveryItemSerializer(required=False,many=True,read_only=False) def create(self, validated_data): items_data=validated_data.pop('items',None) vinstance=DeliveryNote.objects.create(**validated_data) if items_data: for item in items_data: DeliveryItem.objects.create(deliverynote=vinstance,**item) return vinstance def update(self,instance,validated_data): items_data=validated_data.pop('items',None) vinstance=super(DeliveryNoteSerializer, self).update(instance, validated_data) items_dict=dict((i.id,i) for i in instance.items.all()) if items_data: for item in items_data: if "id" in item.keys(): iinstance=items_dict.pop(item["id"]) item.pop('id') for x in item.keys(): setattr(iinstance,x,item[x]) iinstance.save() else: DeliveryItem.objects.create(deliverynote=vinstance,**item) if len(items_dict)>0: for item in items_dict.values(): item.delete() return vinstance class Meta: model = DeliveryNote fields='__all__' This is my child serializer: class DeliveryItemSerializer(serializers.ModelSerializer): def create(self, validated_data): return DeliveryItem.objects.create(**validated_data) class Meta: model = DeliveryItem fields='__all__' I am using django rest framework viewset to generate end points. My payload is: { "vdate":"31-08-2020", "voucher_no":"111", "items":[ { "itemname":12, "qty":"10.00" } ] } This generates following error : "items": [ { "deliverynote": [ "This field is required." ] } ] What am I doing … -
How to serialize uploaded image in django rest framework
My Profile_pic doesnt show in response. Only id, username and email. profile_pic is already stored in db with correct user_id. userdetailmodel.js from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class UserDetail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(null=True, blank=True) serializer.js class ProfilePicSerializer(serializers.ModelSerializer): profile_pic = serializers.ImageField(max_length=None, use_url=True) class Meta: model = UserDetail fields = '__all__' class UserSerializer(serializers.ModelSerializer): profile_pic = ProfilePicSerializer(source='user.userdetail.profile_pic',read_only=True, many=True) class Meta: model = User fields = ('id', 'username', 'email','profile_pic') api.js class UserAPI(generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated,] serializer_class = UserSerializer def get_object(self): return self.request.user -
How to update this data from a forms?
i have tried UpdateView, but it didn't work out! please help me quickly I have a form on a page that gets information from database. How to update this data from a forms? Lorem ipsum dolor sit amet consectetur, adipisicing elit. Debitis repudiandae delectus, pariatur quibusdam doloribus. Voluptatem ad ab beatae dolorum magnam architecto, velit perspiciatis, provident delectus dolores, repudiandae sunt expedita eos voluptates deserunt nam dicta earum mollitia obcaecati! Nam minima enim soluta ratione, vel, sapiente illum eligendi recusandae deleniti earum, aliquid iusto ullam, doloribus tempore aperiam ipsum velit assumenda nostrum quo. views.py class EntityUpdate(UpdateView): model = Entity fields = [ 'entity_type', 'full_name', 'identifier', ] template_name_suffix = '_update_form' def ex_record(request, pk): enforcement = Enforcements.objects.get(pk=pk) enform = EnforcementForm(instance=enforcement) debtor = EntityForm(instance=enforcement.debtor_id, prefix='debtor') claimer = EntityForm(instance=enforcement.claimer_id, prefix='claimer') issuer = EntityForm(instance=enforcement.issuer_id, prefix='issuer') claims = ClaimsForm(instance=enforcement) if request.method == 'POST': if debtor.is_valid() and claimer.is_valid() and issuer.is_valid() and claims.is_valid() and enform.is_valid(): # save without commit enform_instance = enform.save(commit=False) # save id of Forein Keys debtor_instance = EntityForm(request.POST, instance=enforcement).save() claimer_instance = EntityForm(request.POST, instance=enforcement.claimer_id).save() issuer_instance = EntityForm(request.POST, instance=enforcement.issuer_id).save() claims_instance = claims.save() # connect ForeinKeys in Enforcement enform_instance.debtor_id = debtor_instance enform_instance.issuer_id = issuer_instance enform_instance.claim_id = claims_instance enform_instance.claimer_id = claimer_instance # commit to DB enform_instance.save() return render(request, 'zzam_db/view.html', … -
Why is my .css file not fully rendering on server, but working locally?
Essentially, my style.css file is only partially rendering on the live server, despite working properly in my local development environment. Prior to this update I just pushed, things were working fine - I changed some content in the .css file, but not the content that is being affected by this issue. The parts of the CSS file that seem to be affected: table.student { width: 75%; border: 3px inset; margin-left: auto; margin-right: auto; } table.admin { width: 50%; border: 3px inset; margin-left: auto; margin-right: auto; } h1{ font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif; font-size: 30px; padding: 1%; text-align: center; } The rest of the .css file is being applied just fine. I didn't change the file location (myapp/static/css/style.css), or how/where the file is called (in my base.html file with the line <link rel="stylesheet" href="{% static 'css/style.css' %}">). I have run collectstatic with no discernible effect. The python version I am using is 3.7.2 -
One button affecting another form. Django Python
I am creating Blog where user can Like and Pin their Favourite posts. My problem is that when I pin my post and then click on like so it automatically unpin and I have to pin it again . Please test it yourself and help me that how to prevent two forms clashing with each other. ThankYou... Please Help... My Post model with Like and Pin. class Post(models.Model): """Blog Post""" title = models.CharField(max_length=255) title_tag = models.CharField(max_length=55) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name='liked_posts') pins = models.ManyToManyField(User, related_name='pinned_posts') views = models.IntegerField(default=0) My like view : def like_post(request, post_id): post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.views = post.views - 1 post.save() liked = False else: post.likes.add(request.user) post.views = post.views - 1 post.save() liked = True return HttpResponseRedirect(reverse('blog:post', args=[post_id])) My pin view: def pin_post(request, post_id): post = get_object_or_404(Post, id= request.POST.get('post_id')) pinned = False if post.pins.filter(id=request.user.id).exists(): post.pins.remove(request.user) post.views = post.views -1 post.save() pinned = False else: post.pins.add(request.user) post.views = post.views -1 post.save() pinned = True return HttpResponseRedirect(reverse('blog:post', args=[post_id])) My post view: def post(request, post_id): post = Post.objects.get(id=post_id) post.views = post.views + 1 post.save() total_likes = post.total_likes() liked = False if … -
Querying from AJAX in Django (GET)
I have a template (menu.html), and I am making an AJAX call with JavaScript. Then, I want to process that call (throughout the GET parameters) and make a query from Django's ORM. \ My JavaScript code is: $.ajax("/showcart", { type: "GET", data: { product: product, type: product_type }, success: function(response) { console.log("SUCCES SUCCESS SUCCESS") console.log(response); }, error: function(resp) { console.log("ERROR ERROR ERROR!") console.log(resp) } }) product is the name of my product, and product_type is the size of my product. Then, in my views.py, I handle this call with: def showcart(request): product = request.GET['product'] if request.GET['type'] == "small": size = f"{request.GET['type']}_price" elif request.GET['type'] == "large": size = f"{request.GET['type']}_price" else: size = "price" product_name = product.split("-")[0] product_id = product.split("-")[1] return JsonResponse( { "product_name": product_name, "product_id": product_id, "size": size, "queryresult": "nothing here", } ) For example, product_name is "Sub" and I have a model in models.py called Sub. My goal is querying the price, for instance, with the product_name. But, since it is a string type, Django doesn't allow me to do that. Does anyone know how this works? Thanks, -
Is there a way to expose Django admin as a RESTful API?
I want to create, update and delete my objects using an API just like I can from an admin panel but I already have a user API and I don't want to repeat myself. Is there a library I can use to achieve what I want? I've tried django-restful-admin but it did not work properly on Django 3.1 (django.core.exceptions.AppRegistryNotReady was raised though I configured it properly). -
My django form is not working when i iterate through it using for loop
Basically if I tried to use this code {% for field in form %} <div class="input"> <label for="" class="labelinput">{{field.label}}</label> {{field}} </div> {% endfor %} the form data wont make it pass is_valid().But it renders out the form fine. and if I use this code <form action="" method="post"> {% csrf_token %} {{form}} <input type="submit" value=""> it worked perfectly fine. How do I get the first code to work because I want to add classes between the label and the input field -
Pinoychannel build desktop zoom the same as mobile zoom in c++?
Hi every one i am pinoychannel and i want to make the desktop app of zoom in similar to mobile app of zoom in by using C++. is their anyone expert to give me the easy way to make it? -
ValidationError doesn't get printed in my web
I've been learning django for two weeks now and I'm currently learning raising forms.Errors such as forms.ValidationError. Here's the code I've written: def clean_email(self, *args, **kwargs): email = self.cleaned_data.get('email') if not email.endswith("gmail.com"): raise forms.ValidationError("This is not a valid email") return email The problem I have is when I write an email that doesn't contain gmail.com, ValidationError doesn't get printed in the web. -
how to implement an admin approval system for posting blogs in pythondjango
I am building a website where user come and login, after login user publish articles with admin approval . I do not know how to do it. I made a user authentication system where user can login. But i do not know how to make him post data with admin approval. -
Django 500 error report in production exclude Invalid HTTP_HOST header errors
I'm running a Django 2.2 application in production configured using AWS ECS and Load balancer. Since the application is in production mode, it is sending all 500 errors to the ADMIN email configured. I see the logs and receiving lots of Invalid HTTP_HOST errors where I see users are trying to visit the website by the IP address of the ELB or the ELB URL and not the URL pointing CNAME to the ELB. The errors receiving are frequent at an interval of 5 to 10 minutes and are being logged by the Google Groups Since I'm sure that the application will be accessible only to the IP or host mentioned in the ALLOWED_HOSTS settings and other requests will be blocked. Is there any way to prevent such requests? If not, how can I prevent Django to report such errors? -
Searching database table through get method in django
i am new to django and having trouble to get result from my models database table through 'GET' method, my model is: ``` class records(models.Model): sex = ( ('M', 'MALE'), ('F', 'FEMALE'), ) reg_number = models.CharField(max_length=15) mic_number = models.CharField(max_length=15) dog_name = models.CharField(max_length=20) dog_breed = models.CharField(max_length=50) color = models.CharField(max_length=20) dog_Sex = models.CharField(max_length=1,choices=sex) Breeder = models.CharField(max_length=30) Owner_name = models.CharField(max_length=50) address = models.TextField(max_length=264)``` my views is: ```from django.shortcuts import render import datetime from .forms import RecordForm from .models import records # Create your views here. def index (request): return render(request, "newyear/index.html") def search (request): mic = request.GET['mic'] r = records.objects.filter(mic_number__iexact = mic ) return render(request,"newyear/search.html", {"records": r} )``` my index template is: ```<form action="{% url 'search'%}" enctype="application/x-www-form-urlencoded" method="GET"> <ul> <input type="text" name = "mic"> </ul> <button type="submit" name= "search">search</button> </form> ``` my search template is: ```!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>THIS IS RESULT PAGE</h1> {% if records %} <table> {% for records in records %} <tr> <td>{{records.color}}</td> <td>{{records.dog_name}}</td> <td>{{records.mic_number}}</td> </tr> {% endfor %} </table> {% endif %} </body> </html>`<form action="{% url 'search'%}" enctype="application/x-www-form-urlencoded" method="GET"> <ul> <input type="text" name = "mic"> </ul> <button type="submit" name= "search">search</button> </form> ``` my search template is: {% if records … -
append shipping address and billing address on checkout object
This is about the first process of checkout. Here the argument that will be sent to server will be email, lines which consists of quantity and variant's id, shipping_address and billing address. I have no problem in saving email and lines(quantity and variants) but for shipping address and billing address there are multiple cases. Guest user will not have address book so they can't send already created address. Logged in user can either send already created address or new address. So now user should be able to send new address as well thus my schema a server needs to create checkout object is as follow # these are the arguments needed to pass to server while creating checkout input CheckoutCreateInput { lines: [CheckoutLineInput]! email: String shippingAddress: AddressInput billingAddress: AddressInput } input AddressInput { firstName: String lastName: String companyName: String streetAddress1: String streetAddress2: String city: String cityArea: String postalCode: String country: CountryCode countryArea: String phone: String } on such cases, what is the proper way to handle shipping address and billing address? Here is how I tried def resolve_checkout_create(obj, info, input): print('input', input) user = info.context.user checkout = Checkout() if (input['email']): try: user = User.objects.get(email=input['email']) except User.DoesNotExist: print('User does not exist') … -
Django, combining a list of QuerySets into 1 Queryset
So I am building a clothing comparer in Django. I have created multiple checkboxes so that people can filter the products into for instance: Jackets and Trousers. To get all the products in my Postgresql database I made a dictionary with the keys being the categories and the values being the words that are linked to the category. If a match is found the products get appended to a list which contains all the products I want to show. The problem is that I have multiple QuerySets in that list and I cant output it to my HTML. Is there a way to combine all the QuerySets in the list into one QuerySet? The code: mylist = request.POST.getlist('checkbox') categorie_list = ['jackets', 'sweaters', 't-shirts', 'polo-shirts', 'trousers', 'shorts', 'hats', 'bags'] cat_dict = {'jackets': ['zip-up', 'jacket', 'overshirt', 'parka'], 'sweaters': ['hoodie', 'sweatshirt', 'jumper']} list1 = [] for item in mylist: if item in categorie_list: if item in cat_dict.keys(): print(item) for value in cat_dict[item]: print(value) data = models.Product.objects.filter(name__regex=value) list1.append(data) else: pass else: pass print(list1) list1 looks something like this: [<QuerySet [<Product: >, <Product: >]>, <QuerySet [<Product: >, <Product: >]>, <QuerySet [<Product: >, <Product: >]>] -
ModuleNotFoundError: No module named '\\ --access-logfile'
please i need help with gunicorn. i am a junior developer in python. i was setting up a server for a client, when i came across this error No module named '\ --access-logfile'. this is the gunicorn.service unit [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target this is the gunicorn.service Service [Service] User=metalcode Group=www-data WorkingDirectory=/home/metalcode ExecStart=/home/metalcode/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ gworldtc.wsgi:application please help me. -
Project for making Categories and Subcategories and product and displaying it
I need to make project where in a webpage --> product has to be taken from user and subcategories and categories have to be taken from django admin and then have to display whole database to user.All subcategories are link to category and all products are Linked to Subcategory. It has to be made in django I am wroking on it from 1 month and still not able to get desired result . -
How to after django form is submitted to be redirected to another webpage and have form data to be sent to backend database
Aim: for when django form is submitted for data to be sent and saved to admin side. problem: i can redirect it to another page after form is submitted but when i go onto admin side the data is not saved. how can i fix this? using django or javascript? html: <form method="post" > {% csrf_token %} {{form.as_p}} <input class="btn" type="submit" value="Log In"> </form> models.py: from django.db import models from django import forms class Customer(models.Model): first_name = models.CharField(max_length=200, verbose_name='') last_name = models.CharField( max_length=200, verbose_name='') def __str__(self): return self.first_name + ', ' + self.last_name forms.py: from django.forms import ModelForm from django import forms from .models import Customer class CustomerForm(ModelForm): class Meta: model = Customer fields = '__all__' views.py: from django.shortcuts import render from .forms import CustomerForm def index(request): form = CustomerForm() if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'app/index.html', context) if you need any other files just ask -
Django queryset values get foreign key field "foo" instead of "foo_id"
according to the django documentation below: If you have a field called foo that is a ForeignKey, the default values() call will return a dictionary key called foo_id, since this is the name of the hidden model attribute that stores the actual value (the foo attribute refers to the related model). When you are calling values() and passing in field names, you can pass in either foo or foo_id and you will get back the same thing (the dictionary key will match the field name you passed in). For example: >>> Entry.objects.values() <QuerySet [{'blog_id': 1, 'headline': 'First Entry', ...}, ...]> >>> Entry.objects.values('blog') <QuerySet [{'blog': 1}, ...]> >>> Entry.objects.values('blog_id') <QuerySet [{'blog_id': 1}, ...]> So, Is that possible to call values() or any other way without passing fields explicitly to get fields without "_id"? >>> Entry.objects.values() <QuerySet [{'blog': 1, 'headline': 'First Entry', ...}, ...]> -
Retrieve saved FileFiled to save beside manage.py using django
I have saved a docx file in database using FileField of django. mainFile = models.FileField(upload_to='media/', null=True) Now, in views.py, I am writing a function to send this file to the user once requested. But I must do some edits and add some sentences in into its content before sending to user. So, I decided to retrieve the file from database and save it on my folders beside manage.py. Then open it and do my edits using python-docx. But when I write doc= MyFiles.objects.get(Label=l).mainFile with open(r"result.docx", 'w') as f: f.write(doc) f.close() in views.py I receive the error of write() argument must be str, not FieldFile How can I save the files in the database and then retrieve and save them in my backend codes folder beside manage.py with proper original extension (here .docx)? Any help would be appreciated -
Skip to the right section in the contact form
how can I make the page jump right to the chosen section of the main page (for reference: klient/#contact) after submitting a contact form? def klient(request): if request.method == 'GET': form = ContactFormForClient() else: form = ContactFormForClient(request.POST) if form.is_valid(): messages.success(request, 'Form submission successful') company = form.cleaned_data['company'] from_email = form.cleaned_data['from_email'] phone = form.cleaned_data['phone'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] full_messege = """ WIADOMOŚĆ OD KLIENTA Firma: %s Numer telefonu: %s Adres e-mail: %s Temat: %s Treść: %s """ % (company, phone, from_email, subject, message) try: send_mail(company, full_messege, from_email, ['bow.infos.kontakt@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return render(request, 'client_pl.html') return render(request, "client_pl.html", {'form': form})