Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create model instance in drf serializers
I am new to DRF. I want to get saved the model ... Thank in advance. In models.py, PackageDetails and PhysicalDetail have foreignkey relationship to Member my serializers.py is as follows from rest_framework import serializers from .models import Member, PackageDetails, PhysicalDetail class PackageDetailsSerializer(serializers.ModelSerializer): is_expired = serializers.SerializerMethodField() members_expiry_date = serializers.SerializerMethodField() class Meta: model = PackageDetails exclude = ['id'] extra_fields = ['is_expired', 'members_expiry_date'] def get_is_expired(self, instance): return instance.is_expired def get_members_expiry_date(self, instance): return instance.members_expiry_date class PhysicalDetailSerializer(serializers.ModelSerializer): class Meta: model = PhysicalDetail exclude = ['id'] class MemberSerializer(serializers.ModelSerializer): physical_details = PhysicalDetailSerializer(many=True) package_details = PackageDetailsSerializer(many=True) class Meta: model = Member fields = '__all__' extra_fields = ['physical_details', 'package_details'] def create(self, validated_data): physical_detail_data = validated_data.pop("physical_details") package_detail_data = validated_data.pop("package_details") member = Member.objects.create(**validated_data) PhysicalDetail.objects.create(member=member, **physical_detail_data) PackageDetails.objects.create(member=member, **package_detail_data) return member views.py : class MemberViewset(viewsets.ModelViewSet): queryset = Member.objects.all() serializer_class = MemberSerializer class PackageDetailViewset(viewsets.ModelViewSet): queryset = PackageDetails.objects.all() serializer_class = PackageDetailsSerializer class PhysicalDetailViewset(viewsets.ModelViewSet): queryset = PhysicalDetail.objects.all() serializer_class = PhysicalDetailSerializer In GET request it worked well.. but in POST request with the same json format it responses the following: { "physical_details": [ "This field is required." ], "package_details": [ "This field is required." ] } I've provided the fields.. so why this happening.. -
Django 4 update form fields dynamically using HTMX
I developed a Django application in which i have a form with some fields. Depending on the input additional fields are displayed are hidden. Now everything worked quit fine in Django 3.2.14 since the update in Django 4.0.6 it didn't worked anymore. I first build a form, where if a "field_rule_display" exists the field widget is set as "HiddenInput". class AnalysisForm(forms.Form): def __init__(self, analysis_form_template: AnalysisFormTemplate, disable_required: bool, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout() self.helper.add_input(Submit("submit", _("Evaluate"), css_class="btn-primary btn-lg")) analysis_field_queryset = analysis_form_template.analysis_fields analysis_form_url = reverse("analysis_form", args=(analysis_form_template.id,)) for field in analysis_field_queryset.all(): htmx_dictionary = _htmx_dictionary(analysis_form_url, field) self.fields[field.name_for_formula] = _get_field_by_type( field, htmx_dictionary, analysis_form_template, self.data ) self.fields[field.name_for_formula].empty_values = empty_values() self.helper.layout.fields.append( Div(Field(field.name_for_formula), css_class=AnalysisFieldKind(field.kind).name) ) if field.field_rule_display is not None and disable_required is False: self.fields[field.name_for_formula].widget = forms.HiddenInput() self.fields[field.name_for_formula].widget.attrs["disabled"] = True if disable_required: self.fields[field.name_for_formula].required = False After the user enters a specific input into the form, htmx will send a request and i rebuild the form with the new fields. And here the problem starts, even if i update my field in the "self.fields" Django does not render the update and my form field is still hidden. if field.field_rule_display is not None: evaluated_result_display = self._evaluated_formula( field, analysis_form_template, field.field_rule_display, field.field_rule_display.formula, cleaned_data, ) if evaluated_result_display: field_type = … -
Image not visible despite adding every neccessary detail
I am doing CRUD using serializers(as it is my task) where one of the thing I need to insert is an image.I have added everything neccesary for image to be displayed ,the image added is not visible as shown below below are the models,functions,additions made in settings and html urls if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) settings STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR,'media/') MEDIA_URL = '/media/' models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) def filepath(request,filename): old_filename = filename timeNow = datetime.datetime.now().start('%Y%m%d%H:%M:%S') filename = "%s%s" % (timeNow,old_filename) return os.path.join('uploads/',filename) insert function def insert(request): data = {} if request.method == "POST": print('POST',id) data['categories'] = request.POST.get('categories') data['sub_categories'] = request.POST.get('sub_categories') data['color'] = request.POST.get('color') data['size'] = request.POST.get('size') data['title'] = request.POST.get('title') data['price'] = request.POST.get('price') data['sku_number'] = request.POST.get('sku_number') data['product_details'] = request.POST.get('product_details') data['quantity'] = request.POST.get('quantity') data['image'] = request.FILES['image'] form = POLLSerializer(data=data) print(form) if form.is_valid(): print('form after valid:',form) print("error of form:",form.errors) form.save() messages.success(request, "Record Updated Successfully...!:)") return redirect("polls:show") else: print('form not valid') print(form.errors) if request.method == "GET": print('POST',id) category_dict = Categories.objects.filter(isactive=True) category = … -
How to make a query to a specific object DJANGO does not work for me,
the idea is that in the django admin, do an action that generates a pdf, I already have the pdf format and the records are shown to me, but I only want to choose a specific record and that the data of that object appears in the Pdf. `#MODELOS class SalidaDotaciónPersonal(models.Model): solicitado_por=models.CharField(max_length=40,verbose_name="Solicitado por:") unidad=models.CharField(max_length=24,verbose_name="Unidad", default="Arco Iris") fecha = models.DateField(verbose_name="Fecha") @staticmethod def encryptId(pedido_id): signer = Signer() return signer.sign(pedido_id) @staticmethod def decryptId(encrypted_id): try: signer = Signer() return int(signer.unsign(encrypted_id)) except BadSignature: return None class Meta: abstract = True class DetalleSalida(models.Model): ESPECIFICACION = ( ('REPOSICIÓN POR ROTO', 'REPOSICIÓN POR ROTO'), ('REPOSICIÓN POR DETERIORO', 'REPOSICIÓN POR DETERIORO') ) usuario= models.ForeignKey(pacienteArcoiris,on_delete=models.CASCADE,null=True, blank=True) producto = models.ForeignKey(ElementoArcoirisPersonal,on_delete=models.CASCADE,null=True, blank=True) cantidad= models.DecimalField(max_digits=10, decimal_places=2) especificacion= models.CharField(max_length=24, choices= ESPECIFICACION, verbose_name="Especificación") class Meta: abstract = True class SalidaDotacionPersonalFORM(SalidaDotaciónPersonal): id=models.AutoField(primary_key=True, verbose_name="ID",) usuario = models.ForeignKey(pacienteArcoiris,on_delete=models.CASCADE,null=True, blank=True) class Meta: verbose_name = "Salida Dotación Personal" verbose_name_plural = "Salidas Dotación Personal" def __str__(self): return str(self.usuario) class DetalleSalidaDotaciónPersonal(DetalleSalida): salida_dotacion_personal = models.ForeignKey(SalidaDotacionPersonalFORM,on_delete=models.CASCADE,null=True, blank=True) class Meta: verbose_name = "DETALLE SALIDA" verbose_name_plural = "DETALLE SALIDA" def __str__(self): return "DSDP" + str(self. salida_dotacion_personal)` #VIEWS.PY from django.shortcuts import render from django.contrib.auth.models import User from django.views.generic import TemplateView from report.utils import convert_to_64 from report.report import report from .models import DetalleSalidaDotaciónPersonal,SalidaDotacionPersonalFORM class Index(TemplateView): template_name = "index.html" … -
Migrating data from a JSONfield to individual fields
I have a DJango Model class in which it was decided to store a bunch of data in a blob form. The reasons for this decission are not clear to me ... Regardless I now have the task of converting that JSONField into individual Model fields. My question is, how would I go about creating a custom DJango migration that would extract the data from the JSONField and migrate it into the new fields? My first idea is to make a migration in which I add all the new fields, then a second migration that will be custom made. In this second one I will use the django orm to go through every instance of my model and extract the JSON data and then loop through the field structure and alter the newly added fields with the JSON values. The only issue that I could see is if the fields have special constrants then it would get pretty tedious to get everything wright. Any suggestions on my approach? -
Django admin header customisation with my software release
I have in version of my software (settings.release=1.0.14) and I want to show this info in django admin header under or after the product logo, but no idea how to do it. My base_site.html is: {% extends "admin/base.html" %} {% load static %} {% block title %}{% if subtitle %}{{ subtitle }} | {% endif %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"> <a href="{% url 'admin:index' %}"> <img src="{% static 'lumbara.png' %}" height="50px" /> </a> </h1> {% endblock %} {% block extrastyle %} <style> .module h2, .module caption, .inline-group h2,#header { /*margin: 0;*/ /*padding: 2px 2px 2px 2px;*/ /*font-size: 12px;*/ /*text-align: left;*/ /*font-weight: bold;*/ background: #006400 url(../img/default-bg.gif) top left repeat-x; color: #fff; } </style> {% endblock %} {% block nav-global %}{% endblock %} -
Django + DRF: Make Django API route wait for subprocess to finish before returning response
My question is around waiting for subprocess to finish before returning response to the API caller. I had a scenario where I was using python-gnupg library that was running encryption withing a different process. That could sometimes fail with BrokenPipeError. Exception would be swallowed because the response would be returned to the caller with 200, even though there was error in place. So let's say we have def create(self, request: Request, *args: Any, **kwargs: Any) -> Response: method_with_subprocess() return super().create(request, *args, **kwargs) # this method can throw an exception such as "BrokenPipeError" def method_with_subprocess(): result = Popen(cmd, shell=False, stdin=PIPE, stdout=PIPE, stderr=PIPE, startupinfo=si) ... ... ... return result -
What is the alternative of Amazon's Simple Storage System (S3)
I'm trying to deploy my django projct into heroku so I need to server my static files in another service so I don't want to server it in Amazon's Simple Storage System (S3) can anybody help me ? -
Updating database object in Django
I am making a Django project where the user uploads their picture, and it gets saved in the database. And if the user uploads the same picture multiple times on the same day, it uploads the existing field, rather than creating a new one. My error is that while it updates the existing field, it also creates a new one. How do I fix this? Here is my code: if img == None: messages.error(request, "Please submit an image.") return render(request, 'page.html') elif Image.objects.filter(user=user, date=today).exists(): image_file_like = ContentFile(base64.b64decode(img)) a=str(uuid.uuid4()) image = Image(user=user) image.img.save(f"{a}.png", image_file_like, save=True) path = f"media/{a}.png" toUpdate = Image.objects.filter(user=user, date=today) toUpdate.update(img = path) print('works2') return render(request, 'page.html') else: image_file_like = ContentFile(base64.b64decode(img)) a=str(uuid.uuid4()) image = Image(user=user) print('works3') image.img.save(f"{a}.png", image_file_like, save=True) image.save() return render(request, 'page.html') Thanks -
Django ORM: I want to convert raw query to Django ORM [NEED HELP]
Depending on User's type, I want to join related table. if user type is 'pi' prefetch_related('content_object__stores) else prefetch_related('content_object__store_set), but combine both query together. Any idea converting the raw query to Django ORM?? SELECT * FROM user AS u LEFT JOIN provisioning_company AS c ON u.company_id = c.id AND u.type != 'pi' LEFT JOIN provisioning_picker AS p ON u.company_id = p.id AND u.type = 'pi'; class User(AbstractUser): content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, default=None, null=True) related_id = models.IntegerField(default=None, null=True) content_object = GenericForeignKey('content_type', 'company_id') type = models.CharField(max_length=2, choices=user_type_choices) class Picker(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=128) email = models.EmailField(max_length=256) mobile = models.CharField(max_length=16, unique=True) stores = models.ManyToManyField( Store, verbose_name='stores', blank=True, help_text="stores", related_name="picker_set", related_query_name="picker_set", db_table="provisioning_picker_store", ) class Store(CommonModel): companies = models.ManyToManyField( Company, verbose_name='companies', blank=True, help_text="companies", related_name="store_set", related_query_name="store_set", db_table="provisioning_company_store_relation", ) tried something like User.objects.prefetch_related( Prefetch("content_object__store_set", queryset=User.objects.exclude("pi")) ).prefetch_related(Prefetch("stores", queryset=User.objects.filter("pi"))) but it does not work like the raw query. Any help would be appreciated. -
Not able to upload image in CRUD using serializers
I am doing CRUD using serializers as I am tasked. In this context I am new to images and studied it,I have made files called 'media' to store images but I am getting an error like this I have been trying to solve this error but didnt have much success below is the insert function def insert(request): data = {} if request.method == "POST": print('POST',id) data['categories'] = request.POST.get('categories') data['sub_categories'] = request.POST.get('sub_categories') data['color'] = request.POST.get('color') data['size'] = request.POST.get('size') data['title'] = request.POST.get('title') data['price'] = request.POST.get('price') data['sku_number'] = request.POST.get('sku_number') data['product_details'] = request.POST.get('product_details') data['quantity'] = request.POST.get('quantity') data['image'] = request.FILES['images'] form = POLLSerializer(data=data) print(form) if form.is_valid(): print('form after valid:',form) print("error of form:",form.errors) form.save() messages.success(request, "Record Updated Successfully...!:)") return redirect("polls:show") else: print('form not valid') print(form.errors) if request.method == "GET": print('POST',id) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict, many=True) sub_category_dict = SUBCategories.objects.filter(isactive=True) sub_category = SUBCategoriesSerializer(sub_category_dict,many=True) color_dict = Colors.objects.filter(isactive=True) color = ColorsSerializer(color_dict,many=True) size_dict = Size.objects.filter(isactive=True) size = SizeSerializer(size_dict,many=True) hm = {"context": category.data,"sub_context":sub_category.data,"color_context":color.data,"size_context":size.data} return render(request, "polls/product_insert.html", hm) models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) def filepath(request,filename): old_filename = filename … -
Cpanel python detecting wrong version
Im trying to deploy django application on cpanel But as I setup python3.7.12 but it detecting python2.6.6 Im tried please help me -
Pass values from django views to django forms
I am trying to pass a value from views.py to forms.py in django views.py: def pods(request): clusterName = request.GET.get('data') ----> this is the value I want to pass to forms return render(request,'pods.html',{"nodeForm":forms.getPodsOnNodes()}) forms.py: class getPodsOnNodes(forms.Form): nodeName = forms.ChoiceField(label='Node Name',choices=functions.choiceMaker(functions.nodesList(**this is where I want to use clusterName from views**))) Would you please let me know how I can do this? -
Sending data with post method via Fetch API to Django backend doesn't work
I'm writing a shopping cart in Django which uses sessions. I want to send the ID of the selected item to the server via Javascript's fetch API. When I use HTML's native form with method=post, my server app works correctly but when I use fetch API I get errors. Here is my button code: <button class="btn btn-primary addtocart" id=2 onClick="GFG_click(this.id)">Add to Cart</button> Here is the JavaScript: <script> function GFG_click(clicked) { fetch('cart/add/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id : '1' }), }) .then((res) => JSON.stringify(res.json())) .then((data) => { // Do some stuff ... }) .catch((err) => console.log(err)); } </script> Here is the Django's URL pattern: path('cart/add/', views.cart_add, name='cart_add') Here is the cart_add view: def cart_add(request): if request.method == 'POST': cart = Cart(request) id = request.POST.get('id') product = Product.objects.get(id=id) cart.add(product=product) return JsonResponse("success") And this is the error I get: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 DoesNotExist at /playground/cart/add/ Product matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/playground/cart/add/ Django Version: 4.0.5 Exception Type: DoesNotExist Exception Value: Product matching query does not exist. In this line: product = Product.objects.get(id=id) -
How can I make a request to profile API? User was redirected to the profile page after login and i want to make a get request to the user profile API
I want to make a get request to get details of the user from profile API that I have created. The profile API gives details of their user(username, email) But when I make the request in react, I keep getting errors. I am highly confused. The code for Login page and profile page are shown below. As well as error from the console of the browser. import { useRef, useState, useEffect, useContext } from 'react'; import AuthContext from "./context/AuthProvider"; import axios from './api/axios'; import { useHistory } from "react-router-dom"; const LOGIN_URL = '/login/'; const Login = () => { const { setAuth } = useContext(AuthContext); const userRef = useRef(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); useEffect(() => { userRef.current.focus(); }, []) const history = useHistory() const handleSubmit = async (e) => { e.preventDefault(); const response = await axios.post(LOGIN_URL, JSON.stringify({ email, password }), { headers: { 'Content-Type': 'application/json' }, withCredentials: true } ); if (response.status === 200) { history.push("/profile"); console.log('Successfully Login'); } console.log(response.status) console.log(response.data) //console.log(JSON.stringify(response?.data)); //console.log(JSON.stringify(response)); const accessToken = response.data.accessToken; const roles = response?.data?.roles; setAuth({ email, password, roles, accessToken }); setEmail(''); setPassword(''); } return ( <> <section> <h1>Sign In</h1> <form onSubmit={handleSubmit}> <label htmlFor="email">Email</label> <input type="text" id="email" ref={userRef} … -
Pip found no matching distribution found for distributions that exist AWS Elastic Beanstalk
I am running a Django app on AWS elastic beanstalk, and to install dependencies on the virtual environment, I just need to add them to the requirements.txt file. However, I recently added the flair ai package to my project with all its dependencies, and now Elastic beanstalk is unable to download/find multiple packages. I keep getting errors like these, where there are no versions, or only earlier versions of the package. I am not sure what the issue here could be? I am now unable to deploy my app and the environment is degraded because of these issues. ERROR: Could not find a version that satisfies the requirement pywin32==304 (from versions: none) ERROR: No matching distribution found for pywin32==304 WARNING: You are using pip version 22.0.4; however, version 22.1.2 is available. -
Trying to complete the DJANGO intro tutorial as seen on the w3schools website - https://www.w3schools.com/django/django_intro.php
Following along the tutorial as seen on https://www.w3schools.com/django/django_intro.php Basically I have: Created virtual environment Started Django project - myworld Created a members app and edited the views exactly as mentioned Added to urls.py in the project and members directory Still get this error that empty path didn't match any of these A screenshot of the error message I am seeing instead of Hello world! and welcome to Django A screenshot of my urls.py file Is this an issue with me being in a wrong path, or do I need to specify more in path('blog', ) section? -
RSA encryption private key among a group of people
I am currently trying to implement the RSA encryption algorithm with my Django application. So the way I want it to be Is that the users enter some data through like quiz or surveys and then that data is encrypted using a public key of the users. Then I have a group of admins who only can see what the user enters in their own portal (not the Django admin), like maybe a group of admins at a school or something . How can I implement this ? Because a thing that struck me is that I can't decrypt the data with multiple private keys since 1 user's data can be shown to multiple admins for analysis purposes. So I want that a user's data should be decrypted and shown in the admin portal of multiple admins. -
How to overwrite form.valid with a funcion base view
So, i just want to tell my view, to use the request.user as the author of the company im creating. I can find how to do that with class base views, overwriting the form.valid, but i cant find how to do that with a funcion base view enter image description here -
Convert raw query to django ORM (prefetch_related, left join with mutiple conditions)
I want to convert the raw query to Django ORM, but I got no idea. SELECT * FROM user AS u LEFT JOIN animal AS a ON u.related_id = a.id AND u.type != 'animal' LEFT JOIN human AS h ON u.related_id = h.id AND u.type = 'animal'; tried something like User.objects.prefetch_related(Prefetch('name1', queryset=User.objects.exclude('animal'))).prefetch_related(Prefetch('name2', queryset=User.objects.finter('animal')) but it does not work like the raw query. Any help would be appreciated. -
How to fix CORS error while using Models.Pointfield function of GeoDjango Framework?
User is required to click on the location in map using Pointfield. This is my code for models class Marker(models.Model): """A marker with name and location.""" Market_Place_Name = models.CharField(max_length=255) GPS_Location = models.PointField() Http_Location = models.CharField(max_length=255) def __str__(self): """Return string representation.""" return self.name I get error message saying the following and map doesn't load either as shown below: I've tried adding these following codes on setting.py of geodjango project, but nothing seems to work INSTALLED_APPS = ['corsheaders'] MIDDLEWARE = ["corsheaders.middleware.CorsMiddleware",'django.middleware.security.SecurityMiddleware'] CORS_ALLOWED_ORIGINS = [ "http://localhost:8000", "http://127.0.0.1:8000"] -
How to get value from HTML select form inside the views?
1.In HTML template i created a select form passing into it player names from Player Model. 2.I want to delete the player selected in this form. 3.Inside my views, i am trying to get the selected value as a string but i can't. for me it would be Player.objects.get(name="what is selected inside the form"). Can you please help? What should i do in order to get this value inside my views? <div> <form method="POST" action = "" enctype="multipart/form-data"> {% csrf_token %} <select name="to_delete" > {% for pl in players %} <option value="1">{{pl.name}}</option> {% endfor %} </select> <input type="submit" value="Delete"/> </form> </div> def deletePlayer(request,pk,sk): room = Room.objects.get(number=pk) player = Player.objects.get(number=sk) players = Player.objects.filter(room=room) if request.method == "POST": result = reguest.get('1') to_delete = Player.objects.get(name=result) to_delete.delete() context = {'room': room, 'players':players,'player':player} return render(request, 'base/delete_player.html', context) -
@classmethod or @staticmethod In python(Django)
I have used spring framework for developing server application, and now I start to learn Django. I got one question when I use Django. "Is there no issue about memory when using @classmethod or @staticmethod? in python" In spring(java), there is issue about abusing static and spring also support controlling object(IoC container). But when I use Django, there is no decorator or setting about object. Just I use @classmethod, and use it with class name (ex. AccountService.join() ) -
Do I need to buy an SSL certificate for my new domain?
I was hosting my app on Heroku and it said it was "secure" in the domain bar with no problem. I have the following setting on: SECURE_SSL_REDIRECT = True Now I added my own domain and reconfigured my app to point to the domain. Did I lose some sort of SSL by doing this? Sometimes now I get an error when I try to load the webpage that says ERR_SSL_UNRECOGNIZED_NAME_ALERT -
Django funcion views, creating a company with user associated
So, i have this problem when im trying to create my "company", when i didnt have user authentication the view worked just fine. Now i've added django allauth, and this screen appears to me: enter image description here So i will leave here my model and my view to create the company Im just a begginner so sry for my bad explanation enter image description here enter image description here