Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i change security name in django swagger specticuler?
enter image description here in settings.py SPECTACULAR_SETTINGS = { 'TITLE': 'title', 'VERSION': '1.0.0', 'SERVE_INCLUDE_SCHEMA': False, 'CONTACT': {'name':'name','email':'noreplay@gmail.com'}, 'SCHEMA_PATH_PREFIX_TRIM': True, 'SERVERS': [{'url': env('SWAGGER_SERVER')},], 'PREPROCESSING_HOOKS': ["custom.url_remover.preprocessing_filter_spec"], } in django by default schema and swagger generation i am not able to solve this issue -
Django display list of dictionary in template - dict key as variable
I am using Django 4.0 to display a frontend page which source data is a list of dict. I want to order the keys of the dict and then display all dict in the list in the same order. Here is my views.py: def UserGoalstatus(request, promise_token): print("__UserGoalstatus__") from cmd_utils import Retrieve_goal data = Retrieve_goal(promise_token) keys = set() for item in data: keys.update(set(item)) key_order = sorted(keys) context = { "data": data, "key_order": key_order, } return render(request, 'json_table.html', context) Here is the content of my 'data' variable: [ {'goal_key': '286815', 'goal_type': 'hotelreservation', 'goal_id': 16149845, 'promise_token': '9ba51cbc-830b-64d603904099', 'campaign_id': 1002204, 'properties': {'price': 100, 'created': '2022-06-13 10:48:34', 'checkout': '2022-06-13', 'currency_code': 'USD', 'completed_booking_status': 1}}, {'goal_key': '1208107', 'goal_type': 'hotelreservation', 'goal_id': 16149846, 'promise_token': '9ba51cbc-830b-64d603904099', 'campaign_id': 1002204, 'properties': {'price': 100, 'created': '2022-06-13 10:48:35', 'checkout': '2022-06-13', 'currency_code': 'USD', 'completed_booking_status': 1}} ] Here is my html file which I would like to print all content in data in the order of 'key_order' <table id="dtBasicExample" class="table table-hover table-striped table-bordered" cellspacing="0" width="100%"> <thead> <tr> {% for key in key_order %} <th>{{ key }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in data %} <tr> {% for key in key_order %} <td>{{ item.get(key) }}</td> {% endfor %} </tr> {% endfor %} </tbody> … -
I am trying to make an api request to another app in django but in the same project, how do i pass the url to my api view, local deployment is working
``` def getpk(request, pk): current_user = request.user obj = LetterBody.objects.get(id=pk) company = obj.company_details.short_code location = obj.company_details.location.short_code datetime = str(date.today()) token = Token.objects.get(user=current_user.id) url = request.build_absolute_uri(reverse('create')) payload={ 'company':company, 'location':location, 'date':datetime } headers = { 'Authorization': f'token {token}', 'Content-Type': 'application/json' } if obj.reference_code: return redirect('letters') else: response =requests.request( 'POST',url, headers=headers, data=json.dumps(payload)) data = json.loads(response.text) objid =data.get('id') obj.reference_code = str(location) + "/" + company + "/" + str(datetime) + "/" + str(objid) obj.save() return redirect('letter_detail', obj.id) local production is working just fine but once i deploy the api is not working.create is the name to my create url in the api aplication -
chart bars not showing
am trying to display a chart using plotly in django project, the chart appears fine in the page, yet i can't see the bars even though data exist in the database. please help in views.py import pandas as pd from plotly.offline import plot import plotly.express as px def viewReport(request): attendance = Attendance.objects.all() graph_data = [ { 'Student': x.student_id, 'Start': x.date, 'Finish': x.date, 'Course': x.course_id } for x in attendance ] graph_frame = pd.DataFrame(graph_data) figure = px.timeline( graph_frame, x_start="Start", x_end="Finish", y="Student", color="Course" ) figure.update_yaxes(autorange="reversed") gantt_plot = plot(figure, output_type="div") # print(attendance) attendfilter = AttendanceFilter(request.GET, queryset=attendance) attendance = attendfilter.qs context = {'attendance': attendance, 'attendfilter': attendfilter, 'gantt_plot':gantt_plot} return render(request, 'LogInApp/ViewReport.html', context) model.py, the model am retrieving data from class Attendance(models.Model): ATTENDANCE = ( ('absent', 'Absent'), ('present', 'Present') ) student_id = models.CharField(max_length=100, null=True) course_id = models.CharField(max_length=100, null=True) date = models.DateField(auto_now_add=True, null=True) time = models.TimeField(auto_now_add=True, null=True) #week_num = models.CharField(max_length=2, blank=True) attendanceState = models.CharField(max_length=20, null=True,choices=ATTENDANCE) def __str__(self): return '{}'.format(self.student_id) viewattendance.html {% block content%} <div> {% autoescape off %} {{ gantt_plot }} {% endautoescape%} </div> {% endblock content%} </div> -
Printful django connection for creating orders
i want to make a link between django and printful via API to create an order within the printful store. I am looking at the documentation site but I think it is done badly, could someone who is familiar with or has already done this thing could help me? I'm not super expert in API and connections I'm trying to learn, so please if you can show me how you do it or link me some tutorials or useful resources you would do me a great favor @login_required def test(request): # variabili per connessione token = "Fqtsbpy18lIl5DHKCtrKRAm4CNu1fNZnr9V551QZ" url = "https://api.printful.com/" # dati ordine { "external_id": "4235234213", "shipping": "STANDARD", "recipient": { "name": "John Smith", "address1": "Via milano 55", "city": "Milano", "country_code": "IT", "country_name": "Italy", "zip": 20020, "email": "email@gmail.com", }, "items": [ { "id": 1, "quantity": 1, "price": "13.00", "name": "Enhanced Matte Paper Poster 18×24", } ], "retail_costs": { "currency": "EUR", "subtotal": "10", "shipping": "5.00", "total": "15" }, } header = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'} test = requests.get(url + 'orders', headers = header) print('---------------', test, '------------') context = {'test': test.json()} -
Django-rest-auth : How refresh Token?
I'm using Django-rest-auth for authentication (https://django-rest-auth.readthedocs.io). but when I register a new account, the api sent back to me a Token who never change after. For more security, how can I do to have a new token every time I login ? -
Django+Haystack query does not find substrings in model's attributes
I am using haystack + whoosh in my app. And I have a model like this: class Person(models.Model): name = models.CharField(max_length=64) surname = models.CharField(max_length=64) and search index like this: class PersonIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='name') surname = indexes.CharField(model_attr='surname') def get_model(self): return Person def index_queryset(self, using=None): return self.get_model().objects.all() and here's my case: when I am looking for person 'Krzysztof' (it's polish name) it finds it, but when I search for 'rzysztof' there is no result. So how can I fix it so it could search for substrings in model attrs? -
Field 'id' expected a number but got <WSGIRequest: GET '/r/1/'>
i tried to make a project which would convert long url to short. take input url from html page and save it to database and redirect it to long url though my new url but got an error and the index.html looks like <h1>short any url here</h1> <form method="POST"> {% csrf_token %} <input type="url" name="url" placeholder="enter your url here"> <input type="submit" value="submit"> </form> {% for urlconverter in urlconv %} <li><a href="{% url 'shorturl:redirect' urlconverter.id %}">{{ urlconverter.short }} </a></li> {% endfor %} urls.py from django.urls import path from .import views app_name='shorturl' urlpatterns=[ path('shorturl/',views.indx,name='home'), path('r/<int:urlconverter_id>/',views.redirect,name='redirect'), ] the models.py from django.db import models # Create your models here. class urlconverter(models.Model): url=models.CharField(max_length=1000) short=models.CharField(max_length=100) def __str__(self): return self.url views.py from django.shortcuts import render,redirect,get_object_or_404 from django.http import HttpResponse from django.template import loader from .models import urlconverter # Create your views here. def indx(request): template=loader.get_template('urlconverter/index.html') urlconv=urlconverter.objects.all() if request.method=='POST': a=request.POST.get('url') b=urlconverter.objects.all() c=b.count() nwurl='/r/'+str(c) s=urlconverter(url=a,short=nwurl) s.save() context={ 'urlconv':urlconv } return HttpResponse(template.render(context,request)) def redirect(request,urlconverter_id): obj=get_object_or_404(urlconverter,pk=urlconverter_id) org_url=obj.url return redirect(org_url,request) and i got this error TypeError at /r/1/ Field 'id' expected a number but got <WSGIRequest: GET '/r/1/'>. Request Method: GET Request URL: http://127.0.0.1:8000/r/1/ Django Version: 4.0.5 Exception Type: TypeError Exception Value: Field 'id' expected a number but got <WSGIRequest: GET '/r/1/'>. … -
Static files and Images won't update on Django
I'm learning the Django, I just tried making a simple blog to see how it works out. Initially, when I started it was very responsive (even though I had to ctrl-f5 to refresh the changes on my chrome browser) there wasn't any problem I was facing. I decided to add an image in the background it wouldn't update not only the image but other edits like the font size and the colour etc. save the file on vscode and then ctrl f5 on the browser still it wouldn't show up. Stuck with this since then. tried to find solutions over the web but none of them worked. I'm still not sure if it's the problem with the code or the browser just won't load it any help is appreciated thanks! body { /* Typography Declarations */ color: #222222; font-size: 2em; font-size: unset; font-family: "Open Sans", "Helvetica Neue", sans-serif; } .content-footer, .masthead-heading, .masthead-intro { text-align: center; } .masthead { padding: 6em 0; background-image: url('/blog/static/blog/css/img/pat.jpg'); /* background-size: cover; background-repeat: no-repeat; */ border-top: solid 1em lightseagreen; } .masthead-intro { /* Layout Declarations */ margin-bottom: 0.1em; /* Typography Declarations */ font-family: "Gentium Book Basic", Georgia, serif; font-size: 20em; } .masthead-heading { /* Layout Declarations … -
Python Django regular expression filter
Only python knowledge is sufficient for this as i can convert it to django myself. I have few values in db for a column "customer_id".Values are of three types: Ben-t-3000386247-R123 Ben-t-3000386247-P123 Ben-t-3000386247-123 I only need to filter out this entries where there is a digit after last "-".Here it is "Ben-t-3000386247-123". Please help me out. Python regular expression code or django filter code. Thankyou all in advance In django we use "customer_id__iregex" as filters. -
Django - Convert UUID back to default ID
Is it possible to convert back from UUID to Django's default ID? Could there be any impact in the existing data? If I delete this line in my Model, Django could automatically add a field to hold the primary key? Any thoughts on this or previous experience? id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Thanks, -
Recursion error caused by __init__ method
I have a model Folder which has a ForeignKey refering to itself in order to represent a folders structure : class Folder(models.Model): folder_name = models.CharField(max_length=200) parent_folder = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True') def __init__(self, *args, **kwargs): super(Folder, self).__init__(*args, **kwargs) if self.pk is not None: self.initial_filepath = self.filepath() def filepath(self): if not self.parent_folder: return f'media/scripts/{self.folder_name}' else: return f'{self.parent_folder.filepath()}/{self.folder_name}' The issue is, when deleting a folder that has childrens, a recursion error occurs. I was able to determine that it was coming from the filepath method called in the __init__ one. However, what I don't understand, is why this is happening as I don't really understand how the __init__ method work. I'd be glad if someone could help me understand how I could go about dealing with this issue, as I'm currently lost as to what to do. Here's a glimpse of the unending traceback : Traceback (most recent call last): File "C:\Users\stephane.bernardelli\Documents\ScriptsApp\.env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 187, in __get__ rel_obj = self.field.get_cached_value(instance) File "C:\Users\stephane.bernardelli\Documents\ScriptsApp\.env\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'parent_folder' During handling of the above exception, another exception occurred: **Exact same error repeating till a recursion error occurs** And when the recursion error occurs, I have a long message (too long for me … -
Cryptocurrency chart to reflect the last 7 day performance
I am trying to generate the last 7 days performance for a number of tokens in Django. Please refer to the coinmarketcap.com which shows the performance of a token for last 7 days. I am getting the real-time price data from Coinbase API. I donot want to store huge historical data in order to generate the chart below. I am looking into the number of APIs which provides the summary of historical data to generate the line chart below. Any idea/pointers would be really helpful. As a solution, I am planning to display the same chart as in coinmarketcap: https://s3.coinmarketcap.com/generated/sparklines/web/7d/2781/1.svg -
Django website not showing dictionary values
I am using VS code for django. I am not sure why but the default django website is not showing the expected output. The output is ignoring the dictionary values. from django.shortcuts import render from django.http import HttpResponse def index(request): context = { 'name': 'Patrick', 'age' : 23, 'nationality':'British', } return render(request, 'index.html', context) ``` <h1> Welcome, {{name}}<br> You are {{age}} years old. </h1> (output in server website) Welcome, You are years old. -
Filter queryset in django select2 widget
Is it possible to filter queryset in Django Select2 forms? I got a form that sends a direct message to the user and I want to have the possibility to filter users. s2forms.ModelSelect2Widget, as I see, selects all instances of User model Now I need t to implement a flag to the User model (allow_direct_messages), and if the user allows sending direct messages, so I need to filter them accordingly. class DirectMessageCreateForm(forms.ModelForm): class Meta: model = DirectMessage fields = ("author", "recipient", "content") labels = { "author": "", } widgets = { "recipient": UsersWidget, "content": forms.Textarea(attrs={ 'class': 'block p-3 w-full text-md bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500' ' focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 ' 'dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500', 'placeholder': "Type your message here..." }), "author": forms.TextInput, } class UsersWidget(s2forms.ModelSelect2Widget): search_fields = [ "name__icontains", "email__icontains", ] Maybe someone knows how to make a custom queryset inside ModelSelect2Widget form? Thanks in advance -
Get last object of ManytoMany connected table in Django
I have a Django model like the following: class RFIDInventorySerials(models.Model): serial = models.CharField(max_length=50, blank=True, null=True, default=0) coordinate = models.CharField(max_length=100, blank=True, null=True, default=0) timestamp = models.DateTimeField(default=datetime.now) class RFIDInventory(models.Model): reference_number = models.IntegerField(default=0) serials = models.ManyToManyField(RFIDInventorySerials) and a list of serial such as : s = ['a', 'b', 'c', 'd', 'e'] for every serial I want to get the last time_stamp. How can I do that ? I did: last_seen = [] for i, v in df_hr1['Miss'].iteritems(): last = RFIDInventorySerials.objects.filter(serial=v).last() print("last", last) last_seen.append(last.start) But if the list becomes longer then the loop won't be a solution to this -
Bootstrapp not working on tablet (Acer B3-A30)
Good afternoon all, Bought an old tablet for a demo of an app. It looks like bootstrap is not working on some elements such modals, tabs. (its working fine on laptop and mobile). The tablet is from 2016. Not sure what information to give at this stage, so feel free to ask any question. Any pointers on how to fix this? -
TypeError: unsupported operand type(s) for +: 'int' and 'Time'
I want to sum minutes keeping in my table. class Time(models.Model): value = models.PositiveIntegerField(null=True) I'm trying to sum minutes in def function: def sum(request): times = ..._set.all() for time in times: total_min = total_min + time Then I have TypeError: unsupported operand type(s) for +: 'int' and 'Time'. The problem appears because I'm trying to summarize values of different types: int + object type. And to solve the problem I need to convert object model PositiveIntegerField into int. But how can I do this not in class, but in def function? -
Stripe error with when creating user on django admin panel
When I create a user on the Django admin panel, Stripe hooks throws the following error. I am not sure where to go to deal with this issue? File "/Users/.../drf_stripe/stripe_webhooks/handler.py", line 53, in handle_webhook_event e = StripeEvent(event=event) File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for StripeEvent event No match for discriminator 'type' and value 'customer.created' (allowed values: <EventType.CUSTOMER_SUBSCRIPTION_DELETED: 'customer.subscription.deleted'>, <EventType.CUSTOMER_SUBSCRIPTION_UPDATED: 'customer.subscription.updated'>, <EventType.CUSTOMER_SUBSCRIPTION_CREATED: 'customer.subscription.created'>, <EventType.INVOICE_PAID: 'invoice.paid'>, <EventType.INVOICE_CREATED: 'invoice.created'>, <EventType.INVOICE_PAYMENT_FAILED: 'invoice.payment_failed'>, <EventType.PRODUCT_UPDATED: 'product.updated'>, <EventType.PRODUCT_CREATED: 'product.created'>, <EventType.PRODUCT_DELETED: 'product.deleted'>, <EventType.PRICE_CREATED: 'price.created'>, <EventType.PRICE_UPDATED: 'price.updated'>, <EventType.PRICE_DELETED: 'price.deleted'>, <class 'str'>) (type=value_error.discriminated_union.invalid_discriminator; discriminator_key=type; discriminator_value=customer.created; allowed_values=<EventType.CUSTOMER_SUBSCRIPTION_DELETED: 'customer.subscription.deleted'>, <EventType.CUSTOMER_SUBSCRIPTION_UPDATED: 'customer.subscription.updated'>, <EventType.CUSTOMER_SUBSCRIPTION_CREATED: 'customer.subscription.created'>, <EventType.INVOICE_PAID: 'invoice.paid'>, <EventType.INVOICE_CREATED: 'invoice.created'>, <EventType.INVOICE_PAYMENT_FAILED: 'invoice.payment_failed'>, <EventType.PRODUCT_UPDATED: 'product.updated'>, <EventType.PRODUCT_CREATED: 'product.created'>, <EventType.PRODUCT_DELETED: 'product.deleted'>, <EventType.PRICE_CREATED: 'price.created'>, <EventType.PRICE_UPDATED: 'price.updated'>, <EventType.PRICE_DELETED: 'price.deleted'>, <class 'str'>) I am using this library here -
How to display image using django
I am having trouble on how to display an image on html? i just want to display all image that saves on my database {% for banner in banners %} <div class="mySlides fade"> <div class="numbertext">1 / 3</div> <img class="d-block w-100" src="{{ banner.banner }}" style="width:100%"> <div class="text">Caption Text</div> </div> {% endfor %} model class Banner(models.Model): banner = models.ImageField(upload_to='image/', null=True, blank=True) views def homepage(request): banners = Banner.objects.all() return render(request, 'mysite/homepage.html', {'banners': banners}) -
Django App Cloudformation YAML Stack - Nginx isn't reaching Django - Securitygroups conf without NAT
Having no background with aws/devops and after a lot of efforts and trial/error i succeeded building the here bellow stack for my django app : The stack relies heavily on celery wich consumes a lot of tasks so i migrated to sqs for cost reasons (instead of aws redis). For the same reason i decided to disable the nat gateways because it costs so much and i rely only on security groups and acl for security Initially i had two services : One with nginx, django, celery, pgadmin4, flower, and a second with Celery desired count 0 to scale up on heavy loads. When celery starts working it tend to consume 100% CPU and launch a lot of process taking all the available connections of postgres, new process fail, so i added pgbouncer for connection pooling I decided to migrate to 3 services, one admin service whith nginx, pgbouncer and pgadmin4, a second non scalable minimal service with django and one celery worker, and a third scalable celery service with desired count to 0 which will be launched and scaled down by an alarm on sqs queues. (i am also considering a forth service with django and a desired count … -
Django views.py change json before creating a model
I have a Django app and a model Unit in it. TYPES = ( ('offer', 'OFFER'), ('Category', 'CATEGORY'), ) class Unit(models.Model): id = models.CharField('ID', max_length=50, primary_key=True) unit_type = models.CharField(max_length=30, choices=TYPES) name = models.CharField('Name', max_length=50) date = models.DateTimeField('Date of creation or last update', null=True) parents_id = models.ForeignKey('self', related_name='children', blank=True, null=True, on_delete=models.CASCADE) price = models.PositiveIntegerField('Price', default=0, blank=True, null=False) But json passed to me always has an array of units called 'items' and a date "items": [ { "type": "CATEGORY", "name": "phones", "id": "d515e43f-f3f6-4471-bb77-6b455017a2d2", "parentId": "069cb8d7-bbdd-47d3-ad8f-82ef4c269df1" }, { "type": "OFFER", "name": "jPhone 13", "id": "863e1a7a-1304-42ae-943b-179184c077e3", "parentId": "d515e43f-f3f6-4471-bb77-6b455017a2d2", "price": 79999 }, { "type": "OFFER", "name": "Xomiа Readme 10", "id": "b1d8fd7d-2ae3-47d5-b2f9-0f094af800d4", "parentId": "d515e43f-f3f6-4471-bb77-6b455017a2d2", "price": 59999 } ], "updateDate": "2022-02-02T12:00:00.000Z" what I want to do is create a unit out of every element in items and pass updateDate as date to each unit. How can I do this with views and serializer? class UnitViewSet(viewsets.ModelViewSet): serializer_class = UnitSerializer queryset = Unit.objects.all() from rest_framework import serializers from .models import Unit from rest_framework_recursive.fields import RecursiveField class UnitSerializer(serializers.ModelSerializer): children = serializers.ListField(child=RecursiveField()) class Meta: model = Unit fields = "__all__" -
How to restrict user to change model values in Django admin and from psql
Restrict users to change model permission value via Django and psql. My web application is deployed on-premises, the whole code base is there then how to restrict users to access only purchased modules. There may one issue that user can know permission and update in the database for modules which is not subscribed. How to prevent that issue? -
Django serializer requiring a dict instead of a model instance
I'm trying to make a really simple serialization in a viewset in django, but my serializer, which should require the instance to be serialized, is requiring a dict. This is my custom serializer: class JSONAPIModelSerializer(serializers.ModelSerializer): def __init__(cls, *args, **kwargs): if kwargs.get('many', False) is True: context = kwargs.get('context', {}) context.update({'is_many': True}) kwargs.update({'context': context}) return super().__init__(cls, *args, **kwargs) def format_object(self, instance, attributes: dict, meta = None, relationships = None, links = None, is_many: bool = False) -> dict: jsonapi_data = { 'type': instance.__class__.__name__.lower() if not getattr(self.Meta, 'resource_type', None) else None, 'id': str(instance.id), 'attributes': attributes, } jsonapi_data.update({'relationships': relationships}) if relationships else None if is_many: jsonapi_data = { 'data': jsonapi_data } jsonapi_data.update({'meta': meta}) if meta else None jsonapi_data.update({'links': links}) if links else None return jsonapi_data def get_attrs(self, instance): return {} def get_meta(self, instance): return None def get_links(self, instance): return None def get_relationships(self, instance): return None def to_representation(self, instance): return self.format_object( instance=instance, is_many=self.context.get('is_many', False), attributes=self.get_attrs(instance), meta=self.get_meta(instance), relationships=self.get_relationships(instance), links=self.get_links(instance) ) class AnimeSerializer(JSONAPIModelSerializer): class Meta: model = Anime fields = '__all__' resource_name = 'anime' def get_attrs(self, instance): return { 'titles': { 'en': instance.title_en, 'es': instance.title_es, 'en_jp': instance.title_ro, 'ja_jp': instance.title_jp }, 'titleCanonical': instance.title_canonical, 'abbreviatedTitles': [i.value for i in instance.titles_abbreviated.all()], 'otherTitles': [i.value for i in instance.titles_others.all()], 'description': instance.description, 'coverImage': … -
Google removed less secure option and facing SMTP problem
Less secure apps & your Google Account To help keep your account secure, from May 30, 2022, Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password. Important: This deadline does not apply to Google Workspace or Google Cloud Identity customers. The enforcement date for these customers will be announced on the Workspace blog at a later date.