Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting the expiry of access token using drf-social-oauth2
So I am using DRF, React and drf-social-oauth2 for Google Login and I want to set the expiry time of the access token given after Google login. I tried using the same settings as OAuth Toolkit OAUTH2_PROVIDER = { 'ACCESS_TOKEN_EXPIRE_SECONDS': 10, 'OAUTH_SINGLE_ACCESS_TOKEN': True, 'OAUTH_DELETE_EXPIRED': True } which means expiry should be 10 seconds, but the response is, access_token: "d2UAuxY5uv9sEtlE60pgMeuLqTuJV1" expires_in: 33352.043033 refresh_token: "fhm8Zy88HaitJF6q3QEwmSEd3bC1wU" scope: "read write" token_type: "Bearer" the expires_in is wierd. What does this mean? And how do I set the expiry for drf-social-oauth2, can't find any help regarding this anywhere -
NFT payment gateway django
How to accept NFTs on django site? Right now there are two models: class Product(models.Model): ''' Product represents what a user can purchase to fund their wallet''' TYPE_CHOICES = ((-1, "NONE"),(0,"BTC"),(1,'NFT'), (2, "FIAT"), (3, "DUMB")) type = models.IntegerChoices(choices = TYPE_CHOICES, default = -1, blank = False) price = models.FloatField(default = 0.00, null=False, blank=False) title = models.CharField(max_length=50) # TODO qr_code = models.ImageField(upload_to='qr_codes', blank=True) description = models.TextField() # active = models.BooleanField Whether a product is active or not objects = ProductManager() class Invoice(models.Model): ''' The invoice represents a transaction when a user purchases a product''' STATUS_CHOICES = ((-1,"Not Started"),(0,'Unconfirmed'), (1,"Partially Confirmed"), (2,"Confirmed"), (3, "Wallet Credited")) user = models.ForeignKey(User, on_delete = models.CASCADE) product = models.ForeignKey("Product", on_delete=models.CASCADE) status = models.IntegerField(choices=STATUS_CHOICES, default=-1) order_id = models.CharField(max_length=250) address = models.CharField(max_length=250, blank=True, null=True) btcvalue = models.IntegerField(blank=True, null=True) received = models.IntegerField(blank=True, null=True) txid = models.CharField(max_length=250, blank=True, null=True) rbf = models.IntegerField(blank=True, null=True) created_at = models.DateField(auto_now=True) objects = InvoiceManager() We want to accept NFTs as one sort of product such that users are able to send us NFTs and the backend credits their accounts with those NFTs. Is there a good package/service that does this? -
DRF SERILAZATION
I serialize the field named "product" with ProductSerializer() inside OrderItemSerializer(). That's what I want. class OrderItemSerializer(serializers.ModelSerializer): product = ProductSerializer() class Meta: model = models.OrderItem fields = ('id','order', 'product', 'quantity') The output is; But when I try to request with POST Method needs to send Product as a dictionary, just giving the id value is not enough. How can I POST by sending only the id value? -
Template not rendering Django (NoReverseMatch)
I am not exactly sure what the issue is but I have this code in my project that once I select a date it will bring up a table with the name of students in my classroom but Django keeps telling me that there isnt NoReverseMatch. i have double check and everything is fine but not sure why it not working. ERROR SHOWN Reverse for 'attendance-page' with arguments '('',)' not found. 1 pattern(s) tried: ['attendance/(?P[0-9]+)\Z'] urls.py path('attendance_class', views.attendance_class, name='attendance-class'), path('attendance/<int:classPK>', views.attendance, name='attendance-page'), path(r'attendance/<int:classPK>/<str:date>',views.attendance, name='attendance-page-date'), path('save_attendance', views.save_attendance, name='save-attendance'), views.py @login_required def attendance_class(request): classes = Room.objects.all() context = {} context['classes'] = classes return render(request, 'school/attendance_page.html', context) @login_required def attendance(request, classPK=None, date=None): _class = Room.objects.get(id=classPK) students = Student.objects.filter(id__in=ClassStudent.objects.filter(classIns=_class).values_list('student')).all() context = {} context['class'] = _class context['date'] = date att_data = {} for student in students: att_data[student.id] = {} att_data[student.id]['data'] = student if not date is None: date = datetime.strptime(date, '%Y-%m-%d') year = date.strftime('%Y') month = date.strftime('%m') day = date.strftime('%d') attendance = Attendance.objects.filter( attendance_date__year=year, attendance_date__month=month, attendance_date__day=day, classIns=_class).all() for att in attendance: att_data[att.student.pk]['type'] = att.type print(list(att_data.values())) context['att_data'] = list(att_data.values()) context['students'] = students return render(request, 'school/attendance_control.html') def save_attendance(request): resp = {'status': 'failed', 'msg': ''} if request.method == 'POST': post = request.POST date = datetime.strptime(post['attendance_date'], '%Y-%m-%d') year = … -
Django Backend with two different data sources
I am working on a react web app ( I am a begginer) that'll enable the user to store new data rows and edit/udpate old data rows. The reference data, for the react form, is stored in ADLS Gen1 parquet format and The app will write data to a different ADLS location in parquet format. The question is: How can I setup the django backend with these two different data source, I want to read some reference data from ADLS Gen1 and write and edit into another ADLS in parquet format. Any help,litreture or blog-post related to this would be appreciated? Thanks -
Is it posible to listen to an MQTT server and publish with Websocket (endpoint) from our own server
I have got an mqtt consumer that listens to a topic and based on that, I used to send a response on another topic. However now I would like to create a Websocket Secure wss endpoint where i could stream this processed information. Could you tell me if it is possible to do that wth mqttasgi library, if yes how. Here I leave the code of my consumer. from mqttasgi.consumers import MqttConsumer from mqtt_handler.tasks import processmqttmessage import json class MyMqttConsumer(MqttConsumer): async def connect(self): await self.subscribe('application/+/device/+/event/up', 2) await self.channel_layer.group_add("stracontech", self.channel_name) async def receive(self, mqtt_message): print('Received a message at topic:', mqtt_message['topic']) print('With payload', mqtt_message['payload']) print('And QOS:', mqtt_message['qos']) dictresult = json.loads(mqtt_message['payload']) jsonresult = json.dumps(dictresult) processmqttmessage.delay(jsonresult, mqtt_message['topic']) pass async def publish_results(self, event): data = event['result'] await self.publish("stracontech/procesed/"+event['result']['device_id']+"/result", json.dumps(data).encode('utf-8'), qos=2, retain=False) async def disconnect(self): await self.unsubscribe('application/+/device/+/event/up') Pd: @Santiago Ivulich maybe you can help me with that. -
django queryset sorting by fields
i have this model: class ProgrammingQuestionAnswer(models.Model): programming_question = models.ForeignKey(ProgrammingQuestion, on_delete=models.CASCADE, related_name='programming_question_a', null=True, blank=True) time = models.DateTimeField(default=timezone.now) score = models.IntegerField(null=True, blank=True, default=0) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='writer_answer_programming_question', null=True, blank=True) accept = models.BooleanField(default=False) file = models.FileField(upload_to=content_file_name) result = models.TextField(null=True, blank=True) file_name = models.CharField(max_length=500, null=True, blank=True) max_score = models.IntegerField(null=True, blank=True, default=0) I want to write a query for get users who solve more questions(have more accept=True) and those who are equal are sorted by time(time field) Thanks -
django the print() is not working in the terminal
I am currently doing Django project with sqlite3 with ORM method. I am unable to debug as print() is not working in the terminal even if I put print() function in views.py. I checked in python shell, the queryset is working. In views.py from django.shortcuts import render,redirect from .models import BookBoardModel def index(request): all_books = BookBoardModel.objects.all() print(all_books) for item in all_books: print(item.title) context = {'all_books': all_books} return render(request, 'category_books_page/index.html', context) The terminal shown with warning sign and not giving print(): Due to this, the variable all_books are not properly rendered in the index.html which will not generate any objects in index.html -
Signup creating user, but getting error 'Invalid format string'
Struggling to figure out what's wrong with my signup view/serializer. When I signup, a new user is created, however I get the error message: Invalid format string with a 500 internal Server Error message this is my api endpoint: path('api/register', RegisterApi.as_view()), This is my RegisterApi: class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer #remove this if it doesn't work authentication_classes = (TokenAuthentication,) permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "message": "User Created Successfully. Now perform Login to get your token", }) and this is my RegisterSerializer: class RegisterSerializer(serializers.ModelSerializer): city = serializers.CharField(source='profile.city', required=False) country = serializers.CharField(source='profile.country', required=False) profile_pic = serializers.ImageField(source='profile.profile_pic', required=False) is_online = serializers.BooleanField(source='profile.is_online', required=False) is_active = serializers.BooleanField(source='profile.is_active', required=False) class Meta: model = User #removed url from fields fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'profile_pic', 'is_online', 'is_active'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = User.objects.create_user( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() #added fields from profile user.profile.city = validated_data['city'] user.profile.country = validated_data['country'] user.profile.bio = validated_data['bio'] return user Please let me know what i'm doing wrong -
CSRF Verification with Arduino
I have a Django webserver for which I would like to send a POST request using a NodeMCU ESP8266 board. My relevant code is as follows: String httpGETRequest(const char* serverName) { WiFiClientSecure client; client.setInsecure(); HTTPClient http; String jsondata=("{\"my_data\": \"whatever\"}"); // Your IP address with path or Domain name with URL path http.begin(client, serverName); http.addHeader("Content-Type", "Content-Type: application/json"); int httpResponseCode = http.POST(jsondata); //Send the actual POST request String payload = "{}"; if (httpResponseCode>0) { Serial.print("HTTP Response code: "); Serial.println(httpResponseCode); payload = http.getString(); } else { Serial.print("Error code: "); Serial.println(httpResponseCode); } // Free resources http.end(); return payload; } Now my problem is that the Django website uses a CSRF verification, and I was not able to find any guides how to do that with arduino sketch. -
message Request-URI Too Long
I'm kinda new at django and I have a problem with Error 414. I've made a web-application which should get a text from html textarea, process it and return processed text to a user but when I try to test it with +-big text I get an error 414. There's a code if needed: def result(request): get_text = request.GET['usertext'] get_r = request.GET['urls'] if get_r == 'urlsn': get_text = fm.func1(get_text) get_text = fm.func2(get_text) get_text = fm.func3(get_text) get_text = fm.func4(get_text) get_text = fm.func5(get_text) elif get_r == 'urlsy': get_text = fm.func1(get_text) get_text = fm.func2(get_text) get_text = fm.func3(get_text) get_text = fm.func4(get_text) get_text = fm.func6(get_text) return render(request, 'pt_result.html', {'processed_text':get_text}) -
DRF create method raise 'null value in column "project_id_id" violates not-null constraint' django rest framework
I got an integrity error while assign new sites to the existing project id's I followed the same solution from this answer Please find there models & serializers & views while trying with below script I got integrity error 'null value in column "project_id" violates not-null constraint DETAIL: Failing row contains (18, , null, 2022-06-14 16:43:12.319679+00, 2022-06-14 16:43:12.319679+00, t, 3, 3, null).' class CreateNewProjetSerial(serializers.ModelSerializer): site_name = ProjectSiteSerializer(many=True, read_only = True) assigned_to_id = AssignedUserSerializer(many=True, read_only = True) site_names = serializers.ListField( child = serializers.CharField(), write_only = True) user_ids = serializers.ListField( child = serializers.IntegerField(), write_only = True) project_ids = serializers.ListField( child = serializers.IntegerField(), write_only=True ) class Meta: model = Project fields = ['site_name','project_name','assigned_to_id', 'project_ids','site_names', 'user_ids'] def create(self, validated_data): site_names = validated_data.pop('site_names') user_ids = validated_data.pop('user_ids') project_ids = validated_data.pop('project_ids') new_project = ProjectSite.objects.create(**validated_data) for project in project_ids : new_project_site = Project.objects.create(project_id_id=project, **validated_data) for user_id in user_ids: Assignment.objects.create(assigned_to_id__id=user_id, site_id=new_project_site) return new_project json object for post { "site_names": ["site1106", "site2106"], "user_ids": [1], "project_id": [16] } -
How to convert QuerySet string intro String in Django template?
Django template shows the categories as for example <QuerySet [<Category: Fashion>]> I want it to show just as Fashion. index.html {% for auction in auctions %} <li>Auction: {{ auction.title }} Content: {{ auction.content }} Price: {{auction.price}} Category: {{ auction.category.all|slice:":1" }} <img src="{{auction.pic}}" alt="{{auction.title}} pic"> </li> {% endfor %} models.py class Category(models.Model): FOOD = 'FO' TOYS = 'TO' FASHION = 'FA' ELECTRONICS = 'EL' HOME = 'HO' NOTHING = 'NO' CHOICECATEGORY = ( (FOOD,'Food'), (TOYS,'Toys'), (FASHION,'Fashion'), (ELECTRONICS,'Electronics'), (HOME,'Home') ) category = models.CharField(max_length=300, choices=CHOICECATEGORY) def __str__(self): return self.category class Auctionmodel(models.Model): title = models.CharField(max_length=300) content = models.TextField() price = models.IntegerField() pic = models.CharField(max_length=300, blank=True) category = models.ManyToManyField(Category, related_name='Category') categorysomething = Category.objects.filter(category=category).first() views.py def index(request): return render(request, "auctions/index.html", { "auctions": Auctionmodel.objects.all() }) -
Django crispy forms renders select2 field twice
I am using django crispy forms for a ModelForm. In this form I have a field which I would like to display as a Select2MultipleWidget (Provided by django-select2). When displaying the form like this: {{ form }} the field renders just fine. However when using the crispy tag like {% crispy form %} the select2 widget renders twice: This problem does not arise when using the crispy filter like this: {% form|crispy %}. Why is this happening? Should I simply use the filter instead of the tag or is there any workaround here? -
Django - Parent imageField url isnt showing on template
This is my model structure. Institution - name - logo - .... Course - Owner ( foriegnKey with Institution ) - name - terms - ..... So now, am just calling data's like. courses = Course.objects.filter(name__icontains=query).values('id','name','terms','owner__name', 'owner__logo') And trying to display the owner__logo as {{data.owner__logo.url}}. But its not working, as the img src shows (unknown). But when this Institution logo thing works on some other view when i directly call it. but when i call via relationship its not working. If i use {{data.owner__logo}} then it just passes the url without the full path. How to make this work, please help ! -
Django REST multiple serializers aren't saved
I'm trying to add a user profile to the user so they can be updated . I tried to update it one by one and I found that serializer1 is updated if I didn't add serializer 2 to the list , it doesn't update the value and when the user doesn't have a profile it creates one for him views.py @api_view(['POST']) def user_update(request,pk): if request.method == "POST": user = User.objects.get(pk=pk) try: user_p = UserProfile.objects.get(user=user) except: user_p = UserProfile.objects.create(user=user) serializer1 = UserSerializer(instance = user , data = request.data) serializer2 = UserUpdateSerializer(instance = user_p , data = request.data) if serializer1.is_valid() and serializer2.is_valid(): serializer1.save() serializer2.save() Serializer_list = [serializer1.data, serializer2.data] return Response(Serializer_list) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email'] class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = '__all__' models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) image = models.ImageField(upload_to='user',default='default.png') def save(self, *args, **kwargs): super(UserProfile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300 : output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) -
Django stand alone app - sharing data with projects that use standalone app
I am using Django 3.2. I have written a stand alone app that handles user profile management. The app use MaxMindDb to map IP addresses to Countries and Cities. Applications that use my app, need to set a variable GEOIP_PATH in their settings.py file. Currently, I'm having to do this: GEOIP_PATH = os.path.join(BASE_DIR, 'geodata') Which means that I will have to make copies of the huge database for each project using the app. Is there a way to package the MaxMindDb with my app, so that I can refer to it's location a bit like this: GEOIP_PATH = os.path.join([PATH_TO_PIP_INSTALLATION_OF_MY_STANDALONE_APP], 'geodata') -
Django - how to sum 2 DecimalFields in a model and display in admin view?
I have 2 DecimalFields in 1 model. How can I sum both fields together and have the total show up in the admin view? price = models.DecimalField(max_digits=6, decimal_places=2) spotters = models.DecimalField(max_digits=6, decimal_places=2, default=150) There has to be a "container to retain the sum in admin view so I have: total_price = models.DecimalField(max_digits=100, decimal_places=3, default=0) at the end then I finish with a return method: def get_cost(self): return self.price + self.spotters but its not working -
ISSUES IMPORTING MODELS
Hope anyone here would be able to help me out. I'm trying to makemigrations but it's been impossible :/ I keep getting the following error: File "C:\Users\User\Documents\EBAC\Django\django\bookstore\order\models_init_.py", line 4, in from .order import Order File "C:\Users\User\Documents\EBAC\Django\django\bookstore\order\models\order.py", line 4, in from product.models import Product ModuleNotFoundError: No module named 'product.models' as you can see on the the file structure I have 2 apps order and product, I am trying to import the Product model inside my Order model, but it keep saying that there is no module named 'product.models' from django.contrib.auth.models import User from django.db import models from product.models import Product class Order(models.Model): product = models.ManyToManyField(Product, blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE) I have declared both apps on the settings.py: INSTALLED_APPS = [ ... 'django.contrib.staticfiles', 'order', 'product', ] and have also create the init.py for the models folder: from .category import Category from .product import Product I have the impression that all the set up is correct and also the code, but it's not working, if anyone could help me out to find the issue here I would strongly appreciate. Thanks a lot -
Django doesn't validate or see the JWT token from Azure
I used azure-ad-verify-token 0.2.1 on Django-rest backend to validate a jwt token from Microsoft Azure, where the user is authenticated on the frontend with React. According to the documentation, this library should do everything on its own. from azure_ad_verify_token import verify_jwt azure_ad_app_id = 'my app id' azure_ad_issuer = 'https://exampletenant.b2clogin.com/0867afa-24e7-40e9-9d27-74bb598zzzzc/v2.0/' azure_ad_jwks_uri = 'https://exampletenant.b2clogin.com/exampletenant.onmicrosoft.com/B2C_1_app_sign_in/discovery/v2.0/keys' payload = verify_jwt( token='<AZURE_JWT_TO_VERIFY_HERE>', valid_audiences=[azure_ad_app_id], issuer=azure_ad_issuer, jwks_uri=azure_ad_jwks_uri, verify=True, ) print(payload) I don't understand the line token='<AZURE_JWT_TO_VERIFY_HERE>', how can I put the token there? Authorization from Azure on React is successful, and I get a access jwt-token that I can extract: token = request.headers['Authorization'] But I need to validate it and somehow insert it into a string token='<AZURE_JWT_TO_VERIFY_HERE>', but it doesn't recognize the request here. How can I put a token= from the header? And in general, is this the right way? Or am I missing something? Any help and hints would be very helpful and would be greatly appreciated. Or advise another library for token validation in Python. -
Generate a link to Stripe Customer Account Link regardless of the current browser account
I'm using Stripe in Django, I would like to generate a navigation link from django admin portal to Stripe Customer Account. eg: [Customer Id] I've concatenated the id to the following url: "https://dashboard.stripe.com/customers/" to be "https://dashboard.stripe.com/customers/cus_LX88WdbprptpWe" If I click the link, supposedly it opens the Stripe Account and navigates to the customer, this is incase the customer exists in this account. While if the customer actually exists, but currently in the browser I'm logged on a different stripe account, the customer response will not be found. eg: [Customer not found] What I wonder is how to generate a valid stripe customer account link that redirects to the customer's account as well as the correct Stripe Account to avoid the "not found customer" issue. Thanks -
How can i solve this error? I'm working with django on a school project and i'm stuck
i get this error " ModuleNotFoundError: No module named 'models' ". I created a model called Job and I imported it to the admin. But I have that error. I've tried switching up the names of the model and some other folder on the project cause I read somewhere that could be the issue but I can't seem to get my head around it. from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Job(models.Model): title = models.CharField(max_length=150) company = models.CharField(max_length=100) location = models.CharField(max_length=200) salary = models.CharField(max_length=100) nature = models.CharField(max_length=10, choices=TYPE_CHOICES, default=FULL_TIME) experience = models.CharField(max_length=10, choices=EXP_CHOICES, default=TIER1) summary = models.TextField() description = models.TextField() requirements = models.TextField() logo = models.ImageField (default='default.png', upload_to='upload_images') date_created = models.DateTimeField(default=timezone.now) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return '{} looking for {}'.format(self.company, self.title) then this is my input in the admin.py file from django.contrib import admin from models import Job admin.site.register(Job) -
How to redirect one html page to another html page in django
[this is my second page html code to redirect from first page][1] when I click the button in login I need to generate the next page by verifying valid login details how please help????? I will give my view.py file also this is views.py file please verify and help how to write efficient code -
Why aren't changes saved when editing a Django product?
Created a website with products. I need to make a window for editing them on the site in order to change the manufacturer and other characteristics. This must be done in a pop-up window. I have data displayed, I change it, but nothing changes when I save it. How can this problem be solved. My vievs: def parts(request): added = '' error = '' PartAllView = Part.objects.order_by('-id') if request.method == 'POST' and 'parts_add' in request.POST: form = PartForm(request.POST, request.FILES) if form.is_valid(): form.save() added = 'Добавлено' else: error = 'Данная запчасть уже добавлена' if request.method == 'POST' and 'parts_edit' in request.POST: PartPost = int(request.POST['parts_edit']) PartID = Part.objects.get(id=PartPost) if PartID: PartID.save() added = 'Запчасть успешно отредактирована' else: error = 'Ошибка редактирования' form = PartForm() data = { 'added': added, 'error': error, 'form': form, 'PartAllView': PartAllView, } return render(request, 'kross/parts.html', data) My HTML: {% if PartAllView %} {% for el in PartAllView %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="modal fade" id="partEdit{{ el.id }}"> <div class="modal-dialog modal-dialog-centered text-center" role="document"> <div class="modal-content modal-content-demo"> <div class="modal-header"> <h6 class="modal-title">Добавление запчасти</h6><button aria-label="Close" class="btn-close" data-bs-dismiss="modal"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class="row row-sm"> <div class="col-lg-6"> <div class="form-group"> <input type="text" class="form-control" name="brand" value="{{ el.brand }}"> </div> </div> <div class="col-lg-6"> … -
django ORM query for sort by 2 item
I have one Model with name " ProgrammingQuestionAnswer ". at that I have user, time, accept I want to write a query for get Users have many accepted Question and those who are equal are sorted by time please help me this is my model: class ProgrammingQuestionAnswer(models.Model): programming_question = models.ForeignKey(ProgrammingQuestion, on_delete=models.CASCADE, related_name='programming_question_a', null=True, blank=True) time = models.DateTimeField(default=timezone.now) score = models.IntegerField(null=True, blank=True, default=0) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='writer_answer_programming_question', null=True, blank=True) accept = models.BooleanField(default=False) file = models.FileField(upload_to=content_file_name) result = models.TextField(null=True, blank=True) file_name = models.CharField(max_length=500, null=True, blank=True) max_score = models.IntegerField(null=True, blank=True, default=0)