Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to empty all contents of a Django table in a management command before filling it with new data
I am quite new to Django so forgive me if this is an easy answer. I'm creating a simple app that will display data that I scrape from the web on a daily basis. This will be pricing data for certain items; so basically on a daily basis, the only thing that would really change would be the price of a given item. Eventually, I will have an app that contains an HTML table in which I will populate an item ID as well as its price using only the data that is scraped for the current day... i.e any item ID in the table should appear only once and have today's price. I want to keep historical data for another app where I will display prices over time. I set up a management command which will run the scraper for me and dump my data into the sqlite database and am also using django-simple-history to store historical data. The way I understand this is working is my scraper dumps my data into both the table that I created (model_data) as well as a historical table (model_historicaldata). What I am hoping my scraper will do on a daily basis is … -
Django DRF incorrect pagination count
I use a custom yet simple pagination class for my django drf application: from rest_framework.pagination import PageNumberPagination class CustomPagination(PageNumberPagination): page_size = 10 page_size_query_param = "page_size" max_page_size = 100 I have also a ViewSet action that does some operation on the inherited queryset and return the result paginated: class MatchOfJobViewSet(ModelViewSet): serializer_class = MatchSerializer filter_backends = (DjangoFilterBackend,) # classic filter inheriting from django_filter.FilterSet filter_class = MatchFilter def get_queryset(self): job_pk = self.kwargs["job_pk"] return Match.objects.filter(job_pk=job_pk) @action( detail=False, methods=["get"], url_path="dynamic", serializer_class=MatchDynamicSerializer ) def dynamic(self, request, *args, other_args, **kwargs): """return the list of matches with a dynamic serializer""" # some operation on the queryset queryset = self.get_queryset().select_related("some_field") # apply the filters queryset = self.filter_queryset(queryset) # paginate page = self.paginate_queryset(queryset) # I use a custom serializer that takes extra arguments # to update dynamically the fields to be serialized serializer = self.get_serializer(page, many=True, other_args=other_args) # unchanged from the generic list response return self.get_paginated_response(serializer.data) The response I get from the view is like this { "count": 308, "next": "https://blabla.com?page=2&page_size=100", "previous": "https://blabla.com?page=4&page_size=100", "results": [...] } The count indicates 308 entries although there are only 297 entries when I check in the database (which causes the last page to end up empty) From what I read the count parameter is … -
hot to get all url of changelist from django
im using django 1.11 and python version 3.6. im building a middleware in django which will check only the changelist page and save the url, req, response data into the table. i have builded the middleware but stuck in a situation where i have to match the current/present url is whether a changlist or not. i got the current url by request.get_full_path() i can list all the urls by ./manage.py show_urls. for example ./manage.py show_urls command shows my changelist url is /admin/shipment/providerpincode/ now how i will match/get the all changelist url with present url in the code. sorry for my bad english -
How we can create generic API in django?
I'm totally new to Django. I'm creating Generic API. List and Create are working well but ID is not visible in DELETE and UPDATE. This is my views.py file from rest_framework import generics from rest_framework import mixins This is my urls.py code from .views import GenericApiView path('inspections-templates', GenericApiView.as_view()), But as I check documents the ID is not available for UPDATE & DELETE. Can you please someone guide me on how can I update and delete the record. Thanks in advance -
Django AdminDateWidget appreaing as TextInput
I don't understand how widgets work. I tried this minimum example : in my forms.py class PartialResetForm(forms.Form): date = forms.DateField( label="Starting date", widget=AdminDateWidget() ) in my admin/intermediary_reset_page.html {% extends "admin/base_site.html" %} <!--Loading necessary css and js --> {{ form.media }} {% block content %} <form action="" method="post">{% csrf_token %} <!-- The code of the form with all input fields will be automatically generated by Django --> {{ form }} <!-- Link the action name in hidden params --> <input type="hidden" name="action" value="custom_action" /> <!-- Submit! Apply! --> <input type="submit" name="apply" value="Submit" /> </form> {% endblock %} in my admin.py as the definition of an action def custom_action(self, request, queryset): form = PartialResetForm() return render(request, "admin/intermediary_reset_page.html", { "items": queryset, "form": form }) For now I don't care about the queryset, it will be my next topic. With this simple example, I wanted to have a calendar in order to help pick a date, but only a TextInput appeared. I believe it is due to the fact that AdminDateWidget inheritates from TextInput. My question is why isn't it appearing as a calendar ? I imported the media and declared my widget, I don't understand what else I'm supposed to do. -
React Native, Django and Google places integration
I have an app I'm building with react native and django... I created a post model which stores location coordinates, now I want a situation where a user tries to create a post, they will use google places to get the address they want. Then it should store the coordinates in the backend. And also in the frontend, it should not display coordinates from the backend but the address as it is from google places. -
How can I lists all the products according to their foreign key?
I am working on my first eshop website using django framework and I got stuck on a problem. I have created a general model for different kinds of products (like laptops, books etc.). Each product that is added to the website can be found by on its foreign key that links that product to a specific category. models.py class ComputerScienceCategory(models.Model): name = models.CharField(max_length=50, blank=True, null=True) description = models.CharField(max_length=300, blank=True, null=True) img = models.ImageField(upload_to='gallery', blank=True, null=True) def __str__(self): return self.name class Meta: verbose_name = "Category" verbose_name_plural = "Categories" class ComputerScienceProducts(models.Model): name = models.CharField(max_length=50, blank=True, null=True) price = models.FloatField(blank=True, null=True) description = models.TextField(max_length=300, blank=True, null=True) resealed = models.BooleanField(blank=True, null=True) category = models.ForeignKey(to=ComputerScienceCategory, on_delete=models.CASCADE, blank=True, null=True) img = models.ImageField(upload_to='gallery', blank=True, null=True) def __str__(self): return self.name class Meta: verbose_name = "Product" verbose_name_plural = "Products" views.py class ComputerScience(ListView): model = ComputerScienceCategory template_name = "computer_science.html" context_object_name = "category" class CompSProd(ListView): model = ComputerScienceProducts template_name = "laptops.html" context_object_name = "products" laptops.html {% extends 'index.html' %} {% block title %} <title>Laptops</title> {% endblock %} {% block cont2 %} <p style="margin-top:100px;">dsfhsdifsdfsdfsd</p> {% for prod in products %} <p style="margin-top:150px;"> {{ prod.name }} <img src="{{ prod.img.url }}" alt="image"> </p> {% endfor%} {% endblock %} The question is how can I … -
Django Admin not allowing to enter data to table
So am using django admin in my project , i already had some columns during development of my project , as time went the column is reduced from 2 to 1 and column name is changed . So i made changes in code but i am not able to write to django admin . inn django admin UI or in django code . it says table not present admin.py from django.contrib import admin from .models import SalesforceTicket, UploadedFiles # Register your models here. admin.site.register(SalesforceTicket) admin.site.register(UploadedFiles) views.py def files(request): num_of_files = 1 filled_multi_file_form = MultipleForm(request.GET) if filled_multi_file_form.is_valid(): num_of_files = filled_multi_file_form.cleaned_data['num_of_files'] FilesFormSet = formset_factory(FilesForm, extra=num_of_files) formset = FilesFormSet() if request.method == 'POST': filled_form = SnippetForm(request.POST, request.FILES) filled_formset = FilesFormSet(request.POST, request.FILES) if filled_form.is_valid() and filled_formset.is_valid(): SalesforceTicket = filled_form.save(commit=False) SalesforceTicket.save() SalesforceNumber = filled_form.cleaned_data['SalesforceNumber'] for form in filled_formset: data = form.save(commit=False) data.SalesforceTicket = SalesforceTicket data.save() file = form.cleaned_data['files_to_upload'] path = form.cleaned_data['path'] server = form.cleaned_data['server'] note = 'File Uploaded Successfully !!' filled_form = SnippetForm() filled_formset = FilesFormSet() else: note = 'Please try again!' return render(request, 'myforms/files.html', {'note': note, 'SnippetForm': filled_form, 'formset': filled_formset}) else: form1 = SnippetForm() filled_formset = FilesFormSet() return render(request, 'myforms/files.html', {'SnippetForm': form1, 'formset': filled_formset}) forms.py from django import forms from .models import SalesforceTicket, UploadedFiles … -
How to Create and Update data in nested serializer using generic ListCreateAPIView and RetrieveUpdateDestroyAPIView?
I am working on genericAPIViews in DRF. I am using a built in user model with UserProfile model having one to one relation with it. But I am unable to create user due to nested serializer. My question is that how I can create and update my built in User model and Profile User model at the same time as UserProfile model is nested in User model.Here is my code: Models.py USER_CHOICE = ( ('SS', 'SS'), ('SP', 'SP') ) LOGIN_TYPE = ( ('Local', 'Local'), ('Facebook', 'Facebook'), ('Google', 'Google') ) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') cell_phone = models.CharField(max_length=15, blank=True, default="", null=True) country = models.CharField(max_length=50, blank=True, default="", null=True) state = models.CharField(max_length=50, blank=True, default="", null=True) profile_image = models.FileField(upload_to='user_images/', default='', blank=True) postal_code = models.CharField(max_length=50, blank=True, default="", null=True) registration_id = models.CharField(max_length=200, null=True, blank=True, default=None) active = models.BooleanField(default=True) # roles = models.ForeignKey(Role, null=True, on_delete=models.CASCADE, related_name='role', blank=True) user_type = models.CharField(max_length=50, choices=USER_CHOICE, null=True, blank=True) login_type = models.CharField(max_length=40, choices=LOGIN_TYPE, default='local') reset_pass = models.BooleanField(default=False) confirmed_email = models.BooleanField(default=False) remember_me = models.BooleanField(default=False) reset_code = models.CharField(max_length=200, null=True, blank=True, default="") reset_code_time = models.DateTimeField(auto_now_add=True, blank=True) longitude = models.DecimalField(max_digits=80, decimal_places=10, default=0.00) latitude = models.DecimalField(max_digits=80, decimal_places=10, default=0.00) r_code = models.CharField(max_length=15, null=True, blank=True) refer_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="user_refer") referred = models.ManyToManyField(User, related_name="user_referred", null=True, blank=True) … -
How to use the length method in Django ORM Query
In the below class, I need to display the length of name above 25 and country =UK class Emp(models.Model): name=models.CharField(max_length=2000) country=models.CharField(max_length=1000) -
Display specific property between related models in admin panel
I have one model lets call it A. It has N number fields, something like that: class A(models.Model) field1 = models.CharField(max_length=100) field1 = models.CharField(max_length=100) name = models.CharField(max_length=100) I have another model B, which is related to A 1:M class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) field1 = models.CharField(max_length=20) field2 = models.CharField(max_length=20) Here is my admin.py about model B: from django.contrib import admin from project_apps.b_apps.models import B admin.site.register(B) So far so good, but in admin page, when i click on B model it shows me relation to A in that way: A object(1), A object(2) etc. ( for example) That is very confusing. How can i achieve to display A.name1, A.name2 etc. instead of A object(1) -
Error: You don't have permission to access that port
i am using ubuntu server and want to deploy django project in aws using ec2, and it requires me to use port 80 to access its http how do i solve this problem? i heard from other people using sudo and enabling env but this error is all i got ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Please help I really need help -
NoReverseMatch at /wiki/ [duplicate]
What is a NoReverseMatch error, and how do I fix it? Reverse for 'title' with keyword arguments '{'title': ''}' not found. 1 pattern(s) tried: ['wiki/(?P[^/]+)$'] I'm quite new on programming. I can´t load my index.html due to the above error. Looks like the variable title is empty and I can't understand which kind of pattern is (?P[^/]+)$' Might be a problem with variables or is a url problem? When I hardcode the others urls it works fine (ex wiki/add, wiki/css, wiki/edit, wiki/search) This is views.py def index(request): entries = util.list_entries() return render(request, "encyclopedia/index.html", { 'entries':entries, "form":form, }) This is urls.py from django.urls import path from . import views app_name = "wiki" urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.get_page, name="title"), ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path("wiki/", include("encyclopedia.urls")), ] Any kind of help will be much appreciated, i have not been able to fix it since yesterday. I wals looking a helpful reply "What is a NoReverseMatch error, and how do I fix it?" but i wasn´t able to fix my bug. -
why instance.profile.save() when its not declared
I have some trouble understanding this code and i'll like someone to explain vividly how the signals and receivers work including the parameters declared in the create_profile() function #impor of libraries from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() Why do we need to execute instance.profile.save() here, given that post_save signal is a proof that the user is already saved and a profile associated that user is already created? Please help me understand the below too! Thanks In instance.profile.save() is profile an in-built keyword? -
Specify method at as_view in Django urls. (GET, POST etc)
I have some classes with (APIView) and obviously I include them in my urls.py. Question is, if there is a way, to specify method, when I use construction like that: path('mods/mix', MixCUD.as_view()), path('mods/mix/update/<int:mixId>', MixCUD.as_view()), path('mods/mix/delete/<int:mixId>', MixCUD.as_view()), Because, if I understand correctly, I can call delete method of a MixCUD from mods/mix/update/int:mixId address. So I need something like that: path('mods/mix', MixCUD.as_view([POST])), path('mods/mix/update/<int:mixId>', MixCUD.as_view([UPDATE])), path('mods/mix/delete/<int:mixId>', MixCUD.as_view([DELETE])), I can't change them all to a single address, so I have to manage this somehow. -
uwsgi not loading webpacks bundle files (.js)
I'm having a hard time with uwsgi. What happens is (I assume) uwsgi fails to attach main.js in index.html which Django routes. main.js is a webpack bundle from npm run build. My application runs in docker and in it I specified /vol/web/static/frontend directory to include main.js and it is there. curl 127.0.0.1:8000 gives me html (as expected), but in Mozilla, on same socket I get a blank page (with 200 OK http request and response of below html). At 127.0.0.1:8000/static/main.js I receive this main.js file. Why do I get a blank page ? Any clues ? My effort on this is I've reworked my whole static files rooting and directories in Django, tried a 1000 different flags on uwsgi cmd and different static files directories and paths to load from. None of this worked for now. Response html <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Label It</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> </head> <body style="margin: 0"> <div id="main"> <div id="app"> </div> </div> <scipt type="application/javascript" src="/static/main.js"></scipt> </body> </html> I've set up my uwsgi connection to: uwsgi --http 0.0.0.0:8000 \ --master \ --module label_it.wsgi \ --processes 2 \ --static-map /static=/vol/web/static/frontend \ --static-map /static/main.js=/vol/web/static/frontend/main.js \ --check-static /vol/web/static/ … -
Django Admin: Give initial data to form field
I need to manually add an entry to the database via the admin panel, but the admin should not be able to set all the values: #models.py class Product(models.Model): price = models.DecimalField("price") status = models.PositiveIntegerField("status") name = models.CharField("name", max_length=31, unique=True) ## tried: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.initial['status'] = 2 #admin.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ["price", "name",] @admin.register(Product) class ProductAdmin(admin.ModelAdmin): form = ProductForm ## tried: def get_changeform_initial_data(self, request): return {'status': 99} Admin should be able to create a Product and give it a name and price, but the status value should be set to 0. I already tried this approach and this, but no success. I tried: Using an __init__ method to add initial values get_changeform_initial_data() method to add a status. I always end up with sqlite3.IntegrityError: NOT NULL constraint failed: _TEST_Product.status -
Django - How to do complex query with left join and coalesce?
Scenario: Showing all voucher that a user can apply. I have 2 tables Voucher (with all information of a voucher) and VoucherCustomer (listing number of vouchers that a user has used) A validation voucher that can show to user on the application should be Within use-able duration Do not exceed number of times used within a day Do not exceed number of times used per user Do not exceed number of times used for a voucher Must active Here is my model: class Voucher(models.Model): code = models.ForeignKey('VoucherCustomer', related_name= 'voucher_code', on_delete = models.CASCADE) (1) start_at = models.DateTimeField() (2) end_at = models.DateTimeField() (3) usage_limit_per_customer = models.BigIntegerField() (4) times_used = models.BigIntegerField() (5) usage_limit_daily = models.BigIntegerField() (6) times_used_daily = models.BigIntegerField() (7) is_global = models.BooleanField(blank=True, null=True) (8) is_active = models.BooleanField() (9) class VoucherCustomer(models.Model): voucher_code = models.CharField(max_length = 255, primary_key=True) (1) customer_id = models.IntegerField() (2) times_used = models.BigIntegerField(blank=True, null=True) (3) created_at = models.DateTimeField(blank=True, null=True) (4) updated_at = models.DateTimeField(blank=True, null=True) (5) Here is the sample data: +++++++ Voucher ++++++++ (1) (2) (3) (4) (5) (6) (7) (8) (9) TEST01 | 2020-11-30 17:00:00 | 2021-03-01 16:59:59 | 100 | 1124 | 5000 | 6 | true | true +++++++ VoucherCustomer ++++++++ (1) (2) (3) (4) (5) TEST01 10878 … -
Extended User Model not updating
Hii I'am new to Django rest frame work and was preparing API's So this is my models.py class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class User_log(models.Model): user = models.OneToOneField(auth.models.User,on_delete=models.CASCADE,related_name='user_logs') fullname=models.CharField(max_length=255) fb_login=models.BooleanField(default=False) def __str__(self): return self.fullname serializers.py class userSerializers(serializers.ModelSerializer): fullname=serializers.StringRelatedField(source='user_logs.fullname',read_only=False) fb=serializers.BooleanField(source='user_logs.fb_login') class Meta: model = User fields=('id','username','email','fullname','fb') related_fields = ['user_logs'] def update(self, instance, validated_data): # Handle related objects for related_obj_name in self.Meta.related_fields: print('exe') print(instance,validated_data) # Validated data will show the nested structure data = validated_data.pop(related_obj_name) related_instance = getattr(instance, related_obj_name) # Same as default update implementation for attr_name, value in data.items(): setattr(related_instance, attr_name, value) related_instance.save() return super(userSerializers,self).update(instance, validated_data) viewset.py class Userview(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class=userSerializers Now the problem: whenever i try to update fullname column through json request { "id": 2,"username": "karam","email": "karam@83ideas.com","fullname": "karm","fb": true } i am getting this error "POST /accounts/accounts/2/ HTTP/1.1" 405 41 and as in serializers.py update method i have printed the validated data instead of this karam {'username': 'karam', 'email': 'karam@83ideas.com', 'user_logs': {'fullname':'karam','fb_login': True}} i am getting this karam {'username': 'karam', 'email': 'karam@83ideas.com', 'user_logs': {'fb_login': True}} SO any idea how to resolve it? -
Some question about django restful summary
I have a table namely my_activity the models is: class myActivity(models.Model): ac_date=models.DateField(auto_now=True) user = models.ForeignKey(User,verbose_name='使用者',on_delete=models.CASCADE,related_name='my_activity') title = models.ForeignKey(Activity,verbose_name='活動名稱',default='',on_delete=models.CASCADE,related_name='activity') point = models.IntegerField(default=0,verbose_name='點數') I want to write a restful api to summary the point by use_id,like [{'user': 1, 'score': 9}, {'user': 2, 'score': 9}]。 I write the urls.py router.register(r'Score',ScoreSet) In the views.py , I add class ScoreSet(viewsets.ModelViewSet): queryset = myActivity.objects.values('user').annotate(score=Sum('point')) serializer_class = ScoreSerializers and in serializers.py ,I add class ScoreSerializers(serializers.ModelSerializer): class Meta: model = myActivity fields = ('user','point') When I execute the api,I get the error。How can I finish this code? Your help is appreciate. AttributeError at /api/Score/ 'int' object has no attribute 'pk' Request Method: GET Request URL: http://127.0.0.1:8000/api/Score/ Django Version: 3.1.3 Exception Type: AttributeError Exception Value: 'int' object has no attribute 'pk' Exception Location: D:\Program\Workspace\Python\envs\DjangoEnv\lib\site-packages\rest_framework\relations.py, line 271, in to_representation Python Executable: D:\Program\Workspace\Python\envs\DjangoEnv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['D:\\Program\\Workspace\\Python\\usr', 'D:\\Program\\Workspace\\Python\\usr', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.2.2\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32', 'D:\\Program\\Workspace\\Python\\envs\\DjangoEnv', 'D:\\Program\\Workspace\\Python\\envs\\DjangoEnv\\lib\\site-packages', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.2.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Thu, 18 Feb 2021 17:42:55 +0800 -
django filter with user and profile model
I'm using the default User model that has a one-to-one relationship to the Profile model I'm using django-filter to search for things, but it only works for the User model and nothing in the profile model works. How can I include the profile model into the search? filters.py: class AdminUserFilters(django_filters.FilterSet): first_name = CharFilter(field_name='first_name', lookup_expr='icontains') last_name = CharFilter(field_name='last_name', lookup_expr='icontains') username = CharFilter(field_name='username', lookup_expr='icontains') email = CharFilter(field_name='email', lookup_expr='icontains') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email',) models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthdate = models.DateField(null=True, blank=False, max_length=8) -
Django form is valid() returns false
I am encountering form.is_valid() returning false. I have tried printing form.erorrs and it gives me the following: <ul class="errorlist"><li>uploaded_images<ul class="errorlist"><li>“b&#x27;\xbd\x06D\xcd3\x91\x85,\xdf\xa5K\n&#x27;” is not a valid value.</li></ul></li></ul> I am not sure how to interpret this general error. Been searching for quite some time but couldn't find an answer. I must be missing something simple but I just can't find it!! Another pair of eyes to help me sieve through would be very appreciated! views.py from django.shortcuts import render,redirect from django.views.generic.edit import FormView from .forms import BRForm from .models import * class BRHomeView(FormView): form_class = BRForm model = TargetImage template_name = 'br/br-home.html' context_object_name = 'bankrecon' def get(self, request): form = BRForm(request.POST, request.FILES) return render(request, self.template_name, {'form': form, 'title': 'Bank Reconcilation'}) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('uploaded_images') print("POST") print(request.POST) print("FILES") print(request.FILES) print(form.errors) if form.is_valid(): form.save() return redirect('br-home') models.py from django.db import models # Create your models here. class UploadedImages(models.Model): image_files = models.ImageField(null=True, blank=True, upload_to='images/') class TargetImage(models.Model): invoice_date = models.DateTimeField() recon_date = models.DateTimeField() uploaded_images = models.ManyToManyField(UploadedImages) def __str__(self): return self.invoice_date forms.py from django import forms from django.core.validators import FileExtensionValidator from .models import * class BRForm(forms.ModelForm): class Meta: model = TargetImage fields = ('invoice_date', 'recon_date', 'uploaded_images') widgets = … -
User to paying registration fee for Django application
I have a Django application with a basic UserRegisterForm and I would like the user to pay the entry fee before the user is created. I am thinking PayPal as it seems the easiest to integrate. Do I direct them to the Paypal payment on submit and then redirect run the buy function in my views within that call to register the data? views.py def buy(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): data = form.cleaned_data email = f"{data['email']}" username = f"{data['username']}" form.instance.username = username form.save() return redirect('login') else: form = UserRegisterForm() return render(request, 'users/buy.html', {'form': form}) forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() username = forms.CharField(max_length=20) class Meta: model = User fields = ['email', 'username', 'password1', 'password2'] -
Multiply every form value in Django template
I'm created a form where values are coming from my view and the value is daily basis and I want to give a drop down where user can change it to weekly basis and the values will be multiplied by 7. As you can see in the above picture, I'm giving a drop down option where user can change it to weekly basis and monthly basis and the value inside the form will change as per the selection. But I'm not aware how I can achieve this. My code: return render(request, 'test.html', {'List1': l1, 'List2': l2, 'List3': l3} and my form.html is readonly form which renders these list in order. <form> <div class="form-row"> {% for l in List1 %} <div class="form-group col-md-4"> <label>x</label> <div class="input-group mb-3"> <input type="text" value="{{l}}" readonly> </div> </div> {% endfor %} </div> ........simliary for rest list. </form> I want to multiply every value inside form by 7 when user selects weekly in drop-down. How can I achieve it? -
Django + MQTT how to make request and wait for response in view
I am writing a django application and I need a way how to ask for data on MQTT and wait for response (or timeout). Something like this in view: mqtt.subscribe('response/topic') mqtt.publish('request/topic', '{my json request message}') for m in mqtt.on_message(): if m.payload == '......' # OK I have response, render data from response to page, ... # timeout could be implemented by raising exception in on_message() How can i integrate paho mqtt? Or is there any other way? I need to wait for response on several places in views, one global on_message callback is not really useful. Where should I put mqtt.loop_forever() in django? Thank you