Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to remove #modal from url
I have a modal for confirm the action and this modal adds #modal to url but after i submit the url it stil there in the url even after i did redirect in views.py <div class="wf-modal" aria-hidden="true" id="{{sepet.id}}"> <article class="wf-dialog-modal"> <form action="" method="post"> {% csrf_token %} <div class="wf-content-modal"> <input type="hidden" name="cancel-id" value="{{sepet.id}}"> <label for="sebep">{%if sepet.siparis_durumu.durum == "Kargoya Verildi"%}İade{%else%}İptal{%endif%} Sebebi: </label> <textarea name="sebep" style="resize: none; margin-left: 2px;" cols="40" rows="5" {%if sepet.siparis_durumu.durum == "Kargoya Verildi"%}required{%endif%}></textarea> </div> <footer class="wf-footer-modal"> <button name="gonder" value="gonder">Gönder</button> <a href=""><button name="iptal" type="button">İptal</button></a> </footer> </form> </article> </div> views.py if req.get('gonder'): if ...: return redirect('/hesabim/iptal/') but the url stil like /hesabim/iptal/#modal-id -
Django - Find missing invitations for an event
I need to pick the community's brain on django. I'm still learning and the layer abstraction is my major challenge (as compared to a PHP/SQL script) Here's an extract of my models: A very simple contact, but with a "level" (like basic, gold, ...) class customer(models.Model): created_date = models.DateTimeField(auto_now_add = True, editable = False) modified_date = models.DateTimeField(auto_now = True, editable = False) surname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) fk_level = models.ForeignKey(level, on_delete=models.CASCADE) [...] An event with customers (any number) that need to be invited to: class event(models.Model): created_date = models.DateTimeField(auto_now_add = True, editable = False) modified_date = models.DateTimeField(auto_now = True, editable = False) eventdate = models.DateField('Date de la soirée') fk_customer = models.ManyToManyField(customer, blank=True) [...] The invites to an event, for a customer. class invite(models.Model): created_date = models.DateTimeField(auto_now_add = True, editable = False) modified_date = models.DateTimeField(auto_now = True, editable = False) fk_customer = models.ForeignKey(customer, on_delete=models.CASCADE) fk_event = models.ForeignKey(event, on_delete=models.CASCADE) [...] The description of the level, with the number of invites to be sent based on the customer's level. class level(models.Model): created_date = models.DateTimeField(auto_now_add = True, editable = False) modified_date = models.DateTimeField(auto_now = True, editable = False) name = models.CharField(max_length=200) eventinvites = models.IntegerField(default=2) [...] I don't want (and probably don't know how) … -
Microsoft Graph API : Deleting/Modifying single occurrence from recurring series
i have an app which has subscription to office365 calendar. I'm trying to show the meetings in my application which are presents in outlook. My question is, if a single occurrence of the recurring booking it's modified or cancelled in outlook, how can I found out which event was that one, and what changed so I can update my app too with the changes? -
django related question querying list of won items by getting list of items then max bid from bid table for each item then check if user won it
I have a question here, I have two tables in my django models one for listings and one for bids class Listing(models.Model): class Meta: verbose_name_plural = 'Listing' title = models.CharField(max_length=64) description = models.TextField() price = models.DecimalField(max_digits=5, decimal_places=2) image = models.URLField(max_length=500, default='') category = models.CharField(max_length=32) created = models.CharField(max_length=32) addedon = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) def __str__(self): return self.title class Bid(models.Model): class Meta: verbose_name_plural = 'Bid' user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(Listing, on_delete=models.CASCADE) bid = models.DecimalField(max_digits=5, decimal_places=2) created = models.DateTimeField(auto_now_add=True) what i want is to show a page with all the user won items def won(request): listing = Listing.objects.filter(active=False) the question here how i can make list of all then check max bid of each listing, then check is the current user is the winner and display it in the template won.html like : getMaxBid = Bid.objects.filter(item_id=listing.id).aggregate(Max('bid')) maxBid = getMaxBid['bid__max'] then if the user is the winner display it return render(request, "auctions/won.html", { 'listing': listing, 'active': False }) thanks in advance -
Form to delete specific attributes in Django
Sorry for the noobish question, but I am trying to make a simple stock management website with Django and I could not get this part to work. I could not get the part where I register a certain amount of crates of soda and then when it gets taken away from the stock I want the web app to register it however amount less. My model is as follows: class Drink(models.Model): category = models.CharField(max_length=100) name = models.CharField(max_length=200, unique=True) crate = models.IntegerField() So if the stock manager registers 25 crates (crate) a certain drink (name) and then after some time takes 20 of the crates out for use, I want it to be able to register that 20 crates were taken out and that there are now 5 left. I want to do this on the front-end. I used this form to register a Drink object: class CrateForm(forms.ModelForm): class Meta: model = Drink fields = ["name", "category", "crate",] labels = {'name': "Name", "crate": "Crate",} So I guess my question is: how do I create a form that allows me to subtract whatever amount of crates I want to take out for use, and then registers the remaining amount back. It’s kind … -
Python strange import behavior [closed]
In my Django project, I've extended on the generic class based views by making my own 'base' views. These are sitting in "app/views/base/", for example 'app/views/base/base_list_view.py' which inside has a class BaseListView. I currently have 4 of these, each corresponding to a different CBV. (list, detail, update, redirect) When importing these for views that inherit from them, the import behavior seems different for 2 out of 4 classes. (Imported using pycharm intellisense shortcuts) from app.views import BaseUpdateView, BaseDetailView from app.views.base.base_list_view import BaseListView from app.views.base.base_redirect_view import BaseRedirectView example of views: class ProductListView(BaseListView): .... class ProductDetailView(BaseDetailView): .... I don't understand why 2 out of 4 base views, which have been created in exactly the same manner, have a different behavior in the import. Can anyone shed some light on this for me? -
SearchFilter misbehaves when data is a lot
I tested the SearchFilter when I had around 10 records , and it was working fine, but I went ahead and tested it when the data records are above 200, it just returning the same data without searching or filtering the data , below is my View file : class PostList(generics.ListCreateAPIView): """Blog post lists""" queryset = Post.objects.filter(status=APPROVED) serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = (PostsProtectOrReadOnly, IsMentorOnly) filter_backends = [DjangoFilterBackend, filters.SearchFilter] filter_fields = ('title', 'body', 'description',) search_fields = ( '@title', '@body', '@description', ) def filter_queryset(self, queryset): ordering = self.request.GET.get("order_by", None) author = self.request.GET.get("author", None) if ordering == 'blog_views': queryset = queryset.annotate( address_views_count=Count('address_views')).order_by( '-address_views_count') if author: queryset = queryset.filter(owner__email=author) return queryset This is how I search : /api/v1/blogs/?search=an+elephant But it just returns back all the data instead of filtering. -
InMemoryUploadedFile corrupted in server
I am creating an API with django REST Framework and I am having this problem when creating and endpoint. I am getting the file with file_details = request.FILES.get('file'). When I run the code on my machine, the file_details.size is 12679, but when I upload the code on the server the file_details.size is 21370 with the exact same file! Can anyone tell me why is this happening? Thanks in advance. -
Python based search engine or Elastic Search
In our project, we want to incorporate a search engine like ES/Solr for various use cases. Our backend stack is Python/Django. ES has a Java dependency. Is it advisable to use more popular and robust search engines like Elastic Search/Solr or use a native one like Whoosh or any other (suggestions welcome) -
How to do total on Django models.p
I am Trying to get total but i don't know why i am not getting the total and i have the code of models.py and it's output class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) table_num = models.CharField(max_length=50) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def total(self): total = 0 for order_item in self.items.all(): total += order_item.get_total_item_price() return total -
View saving to same model but different instances - not working
I have a view that saves form details through a html page to two different Person objects (which have different IDs), but which reside in the same table (on different rows) View person = Person.objects.filter(pk = user.related_person_id).first() medical_emergency_person = Person.objects.filter(related_entity=medical_emergency_entity).first() if request.method == "POST": form1 = PersonUpdateForm(request.POST, instance=person) form5 = MedicalPersonUpdateForm(request.POST, instance=medical_emergency_person) form1.save() form5.save() else: form1 = PersonUpdateForm( initial= { "title": person.title, "first_name": person.first_name, "last_name": person.last_name, "alias": person.alias } ) form5 = MedicalPersonUpdateForm( initial= { "title": medical_emergency_person.title, "first_name": medical_emergency_person.first_name, "last_name": medical_emergency_person.last_name, } ) context['personal_person_form'] = form1 context['personal_medical_emergency_person_form'] = form5 Forms class MedicalPersonUpdateForm(forms.ModelForm): # FORM META PARAMETERS class Meta: model = Person fields = ('title', 'first_name', 'last_name') labels = { 'title': _("Title*"), 'first_name': _("Emergency Contact First Name*"), 'last_name': _("Emergency Contact Last Name*") } # FORM INITIALISATION TO SET HTML STYLING def __init__(self, *args, **kwargs): super(MedicalPersonUpdateForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs['class'] = 'input' self.fields['first_name'].widget.attrs['class'] = 'input is-danger' self.fields['last_name'].widget.attrs['class'] = 'input is-danger' class PersonUpdateForm(forms.ModelForm): # FORM META PARAMETERS class Meta: model = Person fields = ('title', 'first_name', 'last_name', 'alias') labels = { 'title': _("Title*"), 'first_name': _("First Name*"), 'last_name': _("Last Name*"), 'alias': _("Alias") } # FORM INITIALISATION TO SET HTML STYLING def __init__(self, *args, **kwargs): super(PersonUpdateForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs['class'] = 'input' self.fields['first_name'].widget.attrs['class'] = 'input is-danger' self.fields['last_name'].widget.attrs['class'] … -
Can I get third party API fields as Foreign key to my Django Model?
That's true we can make foreign key relationships between models in Django. How about grabbing some fields from third party API fields as Foreign key for a specific Django model? Here is my Django model budiness_process.py class BusinessImpact(models.Model, ModelWithCreateFromDict): client = models.ForeignKey( accounts_models.Client, on_delete=models.CASCADE) business_process = models.ForeignKey( BusinessProcess, on_delete=models.CASCADE) hierarchy = models.CharField(max_length=255) business_assets = models.CharField(max_length=255) asset_name = models.CharField(max_length=255) vendors = models.CharField(max_length=255) product = models.CharField(max_length=255) version = models.CharField(max_length=10) cpe = models.CharField(max_length=255) asset_type = models.CharField(max_length=10) asset_categorization = models.CharField(max_length=255) asset_risk = models.CharField(max_length=50) _regulations = models.TextField(blank=True) _geolocation = models.TextField(blank=True) def __str__(self) -> str: return self.hierarchy + " - " + self.business_assets Here is my serializer.py class BusinessImpactSerializer(serializers.ModelSerializer): business_process = BusinessProcessListSerializer() class Meta: model = models.BusinessImpact fields = "__all__" Here is third API implementation for retrieving some of it's fields. @api_view( ["GET"], ) def cve_summery(request, key): r = requests.get( "https://services.nvd.nist.gov/rest/json/cves/1.0?cpeMatchString={}".format( key) ) if r.status_code == 200: result = [] res = r.json().get("result").get("CVE_Items") for rs in res: data = { "VulnID": rs.get("cve").get("CVE_data_meta").get("ID"), "Summery": rs.get("cve").get("description").get("description_data"), "exploitabilityScore": rs.get("impact") .get("baseMetricV2") .get("exploitabilityScore"), "severity": rs.get("impact").get("baseMetricV2").get("severity"), "impactScore": rs.get("impact").get("baseMetricV2").get("impactScore"), } result.append(data) return Response(result) return Response("error happend", r.status_code) So my intention here is, can I get "severity": rs.get("impact").get("baseMetricV2").get("severity") as Foreign key in my BusinessImpact model? Thanks! -
Django Rest Framework filtering a field with null and multiple values
I am using Django Rest Framework and want to filter the queryset in a view based on a certain field name, where the filter values would be null and additionally any other particular value for the field blog_category which is a ForeignKey value class Blog(ListCreateAPIView): permission_classes = [DjangoCustomModelPermissions] queryset = Blog.objects.all().select_related("blog_category") serializer_class = Blog_Serializer pagination_class = CustomPageNumberPagination filterset_fields = {'blog_category': ['isnull', 'exact', 'in']} I have added the lookup fields isnull to filter null values I have tried the following url requests but they do not work /?blog_catgeory__in=1,null /?blog_catgeory__in=1,isnull /?blog_catgeory__in=1,isnull=true How do I get this work? -
How to solve ssl certificate error in python code that is used to upload nft on opensea?
Traceback (most recent call last): File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 1348, in do_open h.request(req.get_method(), req.selector, req.data, headers, File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1282, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1328, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1277, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1037, in _send_output self.send(msg) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 975, in send self.connect() File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1454, in connect self.sock = self._context.wrap_socket(self.sock, File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 512, in wrap_socket return opener.open(url, data, timeout) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 519, in open response = self._open(req, data) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 536, in _open result = self._call_chain(self.handle_open, protocol, protocol + File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 496, in _call_chain result = func(*args) File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 1391, in https_open return self.do_open(http.client.HTTPSConnection, req, File "C:\Users\Jatin\AppData\Local\Programs\Python\Python310\lib\urllib\request.py", line 1351, in do_open raise URLError(err) urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:997)> PS C:\Users\Jatin\Downloads\bulk-upload-to-opensea-main> -
Django rest framework drf-yasg swagger multiple file upload error for ListField serializer
I am trying to make upload file input from swagger (with drf-yasg), when i use MultiPartParser class it gives me error drf_yasg.errors.SwaggerGenerationError: FileField is supported only in a formData Parameter or response Schema My code: class AddExperience(generics.CreateAPIView): parser_classes = [MultiPartParser] permission_classes = [IsAuthenticated] serializer_class = DoctorExperienceSerializer serializer: class DoctorExperienceSerializer(serializers.Serializer): diploma = serializers.ListField( child=serializers.FileField(allow_empty_file=False) ) education = serializers.CharField(max_length=1000) work_experience = serializers.CharField(max_length=1000) i also tried FormParser but it still gives me same error. also FileUploadParser parser but it works like JsonParser. -
Custom User Model in django login with phone
I wanted to personalize the Django user model and authenticate users with a phone number How is it possible? -
django admin panel deploy on server Forbidden (403) CSRF verification failed. Request aborted
I'm on course Test-Driven Development with Django, Django REST Framework, and Docker (Michael Herman). My problem is that in a locally running container, the admin panel opens without problems, but the container placed on heroku gives an error (Forbidden (403) CSRF verification failed. Request aborted.) .. Where to look? Thanks! -
Django deployment on pythonanywere
I did the deployment of my django app on pythonanywhere but i see that i have a probleme with relative path . this app can upload and save 2 files in a directory my code actually is: from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict def home(request): #upload file and save it in media folder if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls'): savefile = FileSystemStorage() #save files name = savefile.save(uploaded_file.name, uploaded_file) name2 = savefile.save(uploaded_file2.name, uploaded_file2) d = os.getcwd() file_directory = d+'\\media\\'+name file_directory2 = d+'\\media\\'+name2 results,output_df,new =results1(file_directory,file_directory2) i gived this error FileNotFoundError at / [Errno 2] No such file or directory: '/home/VIRAD\\media\\Listing /home/VIRAD/Django1/viruss/views.py, line 26, in home results,output_df,new =results1(file_directory,file_directory2) -
Limit anonymous petitions in Django
I have a landing page when you can get budgets. I am using JS/HTML in Frontend and Django in Backend. I would like to limit the petitions to anonymous users, because you do not have to be register to get the budgets. I get the IP like this: def visitor_ip_address(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip The point is, I do not know if is the best way to get a IP from one session or the same laptop, for limit it. My goal is limit the petitions in incognito navigation as well, from the same laptop. How is the best way to do it? Thanks -
How to increase file upload size in Django application running on EC2 instance with Nginx as revese Proxy?
I've a Django application that is running on EC2 instance. It is uploading file upto 100MB without any problems, but above 100MB file size, it gives error 413 Request Entity Too Large. I've tried in file /etc/nginx/sites-available/default under server configuration. client_max_body_size 10G; I've also applied the same configuration in my domain configuration files, but all in vein. This configuration works well in my other servers, where I am running php applications. Note: I've used gunicorn with supervisor for running Django application. -
get kwargs in test of serializer
I wrote a serializer in which I used the kwargs in its validate() . here is it: def validate(self, value): course_id = self.context.get("view").kwargs.get("course_id ") .... now I want to write a test but I don't know how to pass the kwargs to it. here is the test I am trying to write: def test_valid_data(self): serializer = CategorySerializer( data=self.category, ) self.assertTrue(serializer.is_valid()) I test this but it didn't work: def test_valid_data(self): serializer = CategorySerializer( data=self.category, kwargs={ "course_id": test_course_id }, ) self.assertTrue(serializer.is_valid()) -
access a Url with a query inside a modal
I want to open the content of a page inside a modal, but this page is accessed by a query string like: add_data?filter=crew So, my modal needs to access the page, but I can't include a url, just a html page: <button id="myBtn">+ Add</button> <div id="myModal" class="modal"> <div class="modal-content"> <span class="close">&times;</span> {% block survey_index %} {% include 'add_data?filter=crew' %} #It doesn't work {% end block %} </div> </div> This way doesn't work since the include expects me to pass a html page like: {% block sample_unit_type_index %} {% include 'inv/index/example.html' %} {% endblock %} How to access the page that is in add_data?filter=crew url code: path('add_data', add_data, name="add_data"), views.py return return render(request, 'inv/add_new.html', context) So the page add_new.html has the content accessed by the queries. Example: <a href="add_dados?filter={{path_info}}" class="btn3 add" role="button">Add</a> Any suggests to access the add_data?filter=crew page content in modal? -
How to integrate google analytics to a Django website dashboard?
I have linked my website hosted on heroku to google analytics. I want to display all the analytics on the dashboard of my website. I tried every stack overflow answer but nothing seemed to work for me. Can anyone please help? Here is a link to my website - sym-fi.herokuapp.com Here is a pic of the django directory I did find this package [https://pypi.org/project/django-google-analytics-app/], but I don't know how to use it. I'm a newbie in coding and I'll appreciate if you guys help me out. Thanks -
Can programmatically upload objects to S3 bucket but GET request is forbidden
I'm writing a django app which needs file uploads. I've created an S3 bucket and an IAM user with S3FullAccess permissions. I took the access key ID and the secret access key and put them in my code (using env variables). I'm using django_storages to send uploaded files to S3, and my config in my settings file is AWS_ACCESS_KEY_ID = os.environ.get('S3_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('S3_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = '<my bucket name>' AWS_S3_REGION_NAME = 'ap-south-1' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' The CORS policy for the bucket for now is [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "PUT", "POST", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] Using this configuration, I'm able to upload files to the S3 bucket from my application, but when that file is requested by the application, I get a 403 Forbidden error. How can I fix this? -
how show error message csv file does not exist
if i added a csv file name inccorrectly i wnat to show error message entered csv file does not exist please write the correct csv file name.how it make? class Command(BaseCommand): help = 'Load a company csv file into the database' def add_arguments(self, parser): parser.add_argument('filename.csv', type=str) def handle(self, *args, **options ): if Company.objects.exists(): print("Data already loaded!!") with open('companies.csv', 'r') as file: reader = csv.reader(file) for row in reader: create= Company.objects.get_or_create( name=row[0], hr_name=row[1], hr_email=row[2], hr_verified=row[3], user_id=row[4], primary_phone=row[5], comments=row[6], )