Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can someone please answer this question and check why my form is not getting saved?
I have two pages that help my users view and edit the complaints that they register. There are two types of complaints they can register. One is a written and the other is through a document. When the user tries to edit a written complaint, the edits get saved in the model but when i followed the same logic to edit my document complaints, the users can view them but on editing and saving, the edits are not getting saved, what's wrong? models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber @property def totalcomplaints(self): return Complaint.objects.count() class DocComplaint(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) event_date = models.DateField(null=True, blank=False) document = models.FileField(upload_to='static/documents', blank=False, null=True) def __str__(self): return str(self.event_date) forms.py: class EditComplaintForm(ModelForm): class Meta: model = Complaint fields = ['reportnumber', 'event_type', 'eventdate', … -
How to disable the password field in djoser for django rest framework?
Can i disable the password field in djoser as i have token authentication so i dont need the user to enter password and ill be using twitter login to verify user -
Wagtail Admin - Allow Editor to Edit Custom Setting
I have created a custom setting in Wagtail, allowing an alert banner to be edited in the admin. from django.db import models from wagtail.contrib.settings.models import BaseSetting, register_setting from wagtail.admin.edit_handlers import FieldPanel from ckeditor.fields import RichTextField @register_setting class AlertBanner(BaseSetting): enable_alert_banner = models.BooleanField(default=False) text = RichTextField(max_length=3000, default="", blank=True) panels = [ FieldPanel('enable_alert_banner'), FieldPanel('text'), ] class Meta: verbose_name = "Alert Banner" I don't want to have to give Admin privileges to certain users in order for them to access this. Is there a way that I can allow Editors to access this setting from the admin menu? -
How to add data to modal body dynamically while a function in views.py is running in Django
I have a BS Modal as below: <div id="myModal" class="modal fade" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" align="center">Add Some value</h4> </div> <div class="modal-body"> <form action = "{% url 'add_function' %}" method = "POST" role="form"> {% csrf_token %} <table> <tbody> <tr> <td> TaskId / Topology File </td> <td><input required name="value" type="text"><td> </tr> </tbody> </table> <br> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button> <input type="submit" value="Save" class="btn btn-success"> </div> </form> </div> </div> </div> </div> After the form is submitted, a function runs in views.py def add_function(request): sometask1 sometask2 sometask3 sometask4 return render(request,'some.html') These task takes some time to get finished. Hence, after submitting the form from Modal, it takes time to load the next page. I want to have a modal, that can dynamically load the status of the steps in execution from add_function in modal body like below: task1: done task2: done task3: running task4: todo -
Django how to save user email from custom model to AbstractUser model through signals?
I am using Abstract user model and just adding new models based on user type. here is my model for subscriber user. class Subscriber(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) how to pass the email of Subscriber model to my Abstract user model through signals? here is my full code: class UserManagement(AbstractUser): is_blog_author = models.BooleanField(default=False) is_subscriber = models.BooleanField(default=False) class Subscriber(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) email is saving in my Subscriber model and I also want it will save in my AbstractUser model. here is two screenshot for better understands: #pic1 here you will se the email for Subscriber model: pic2 here is no email for user jhon. I want when email put in Subscriber model then it automatically send the same same eamil to User model: -
Declare custom tag filter in Django template
Am trying to declare a custom function with 2 parameters but it isn't working as expected , am getting this error : Invalid block tag on line 4: 'original|get_customer_by_status:'CONFIRMATION_PENDING'', expected 'endblock'. Did you forget to register or load this tag? This is my template code : {% original|get_customer_by_status:'CONFIRMATION_PENDING' as customer_pending_loan %} Then my custom tag filter : @register.filter def get_ids_in_list(queryset, status): if isinstance(status, list): return queryset.loan_entries.filter( status__in=status).values_list('id', flat=True) return queryset.loan_entries.filter( status=status).values_list('id', flat=True) -
Getting 404 error on some files in static folder Django
I have configured my static file in setting but then though I am getting 404 error on some files. please give me a solution. -
Python Django rest framework external post api call returning un-authorized error
I am ab it new to Django rest framework external post API calls are not working and returning un-authorized error see my view below import json import requests as requests from rest_framework.response import Response from .serializer import * from rest_framework.decorators import api_view, renderer_classes from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer # Create your views here. @api_view(('POST',)) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def dataValidateView(request): print('data is') data = request.data.get('data') print(data) import dataValidate.config BASE_URL = dataValidate.config.BASE_URL DATA_VERIFY_URL = "{}/data-verify".format(BASE_URL) HEADERS = {"Accept": "application/json; charset=utf-8", "Authorization": "Bearer " + dataValidate.config.TOKEN, "Content-Type": "application/x-www-form-urlencoded"} print('data is') print(data) myobj = {'data': data} request.META.get('HTTP_X_FORWARDED_FOR', '') r = requests.request("POST", DATA_VERIFY_URL, data=myobj, headers=HEADERS) jsonData = r.json() print(jsonData) serializer = dataValidateSerializer(data=jsonData) if serializer.is_valid(): return Response(serializer.data) I know its working because the prins dont show -
Django and accessing POST data from forms.Form
For some reason, this form appears to only be able to POST the 'email' parameter. I would have expected that calling request.POST in the views.py file down below would have given me access to 4 variables, but I can only access 'email'. Any idea what is going on here? # forms.py class UserContactForm(forms.Form): # Correctly POSTs email = forms.CharField(widget=forms.TextInput( attrs = {'class': 'form-control', 'placeholder': 'Email...'} ), label = "Enter your email to be sent your secure login link." ) # drops from POST request second_field = forms.CharField(widget=forms.TextInput( attrs = {'class': 'form-control', 'placeholder': 'Dropped from POST request'} ), label = "I should be accessible in a POST request :(" ) # drops from POST request product = forms.CharField(widget=forms.HiddenInput(), initial="dropped :(") def __init__(self, *args, **kwargs): product_id = kwargs.pop('product_id') super(UserContactForm, self).__init__(*args, **kwargs) if product_id: self.fields['product'].initial = product_id # template <form action="{% url 'create-magic-token' %}" method="post" id="create-magic-token-form"> {% csrf_token %} {{ form.as_p }} <input type="text" name="testing_html_input_form" class="form-control" placeholder="Still drops..." required="" id="id_testing_html_input_form"> <p><input type="submit" value="Submit" class="btn btn-primary"></p> </form> #views.py @require_http_methods(["POST"]) @csrf_exempt def create_magic_token(request): print("post vars::", request.POST) # post vars:: <QueryDict: {'email': ['email@example.com']}> # the hidden variable, the second defined variable in the form, # and the variable defined by pure HTML are not accessible ... -
Django setUp class only execute once
I am currently following a django tutorial (https://youtu.be/UqSJCVePEWU?t=8655) and he uses the setUp function to make test cases. I did the same thing as him and I get an error that the username is not UNIQUE self.c = Client() User.objects.create(username='admin') Category.objects.create(name='django', slug='django') self.data1 = Product.objects.create(category_id=1, title='django beginners', created_by_id=1, slug='django-beginners', price='19.99', image='django') def test_url_allowed_hosts(self): response = self.c.get('/') self.assertEqual(response.status_code, 200) def test_product_detail_url(self): response = self.c.get(reverse('store:product_detail', args=['django-beginners'])) self.assertEqual(response.status_code, 200) so, after some hours I found that setUp is executed for every test (which does not create any problem in the tutorial) and I changed my function to @classmethod def setUpClass(self): which solves the problem, but now I don't know if I messed something up and the tutorial should work, or something in django has changed since then. Any help is appreciated and if any files or something is needed I'll provide them. Thank you in advance -
How to make web application to listen telegram channel with django
I want to provide web application to transfer messages which are posted in a telegram channel to another group. I implemented as follows with reference to https://python.plainenglish.io/telegram-channel-listener-with-python-8176ebe3c89b. This is the code which I wrote in view.py of django application. def transfer(request): api_id = '####' api_hash = '####' user_input_channel = 'https//####' TOKEN = '####' to_group_id = '####' try: client = TelegramClient('anon', api_id, api_hash) except: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) client = TelegramClient('anon', api_id, api_hash, loop=loop) @client.on(events.NewMessage(chats=user_input_channel)) async def newMessageListener(event, loop=None): if loop is None: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) #Get message newMessage = event.message.message if len(newMessage) > 0: print(newMessage) send_text(newMessage, to_group_id, TOKEN) else: print('Empty message') #client.start(bot_token = TOKEN) with client: client.run_until_disconnected() But it doesn't work. Error message is follows. Internal Server Error: /start_transfer/ Traceback (most recent call last): File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Documents/telegram/telegramsite/app/views.py", line 211, in transfer with client: File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/telethon/helpers.py", line 184, in _sync_enter return loop.run_until_complete(self.__aenter__()) File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete return future.result() File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/telethon/client/auth.py", line 713, in __aenter__ return await self.start() File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/telethon/client/auth.py", line 140, in _start await self.connect() File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/telethon/client/telegrambaseclient.py", line 524, in connect self.session.auth_key = self._sender.auth_key File "/.pyenv/versions/anaconda3-5.3.1/envs/telegram_bot/lib/python3.9/site-packages/telethon/sessions/sqlite.py", line 180, in … -
unsupported operand type(s) for +: 'DeferredAttribute' and 'DeferredAttribute'
I am a student learning Django. When I write the code, I get the following error: I wonder which part I wrote wrong. I would be grateful if you could help. Error: unsupported operand type(s) for +: 'DeferredAttribute' and 'DeferredAttribute' Request Method: POST Request URL: http://127.0.0.1:8000/join/join_create/1/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: unsupported operand type(s) for +: 'DeferredAttribute' and 'DeferredAttribute' Views.py : if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): element = Element() element.value_code = form.cleaned_data['value_code'] for i in designated_object: if i.price == Designated.price + Value.extra_cost: element.designated_code = Designated.objects.get(designated_code=id) element.save() else: element = Element() element.designated_code = Designated.objects.get(product_code=id) element.value_code == None element.save() -
How to fetch images from Django rest framework?
I am trying to fetch the images from my django API to react. Apart from images every other data is getting fetched perfectly, but images are not showing on react frontend. models.py from django.db import models class Test(models.Model): name = models.CharField(max_length=200) image = models.ImageField(null=True, blank=True, default='default.jpg') def __str__(self): return self.name serializers.py class TestSerializer(serializers.ModelSerializer): class Meta: model = Test fields = '__all__' views.py class Testview(APIView): def get(self, request): test = Test.objects.all() serializers = TestSerializer(test, many=True) return Response(serializers.data) settings.py STATIC_URL = '/static/' MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'images') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In addition when i tested this api on postman it worked fine. but at front it is not showing any images or error. -
how setting function after a few minutes run again in Django
I trying make a auto function in Django i reseached all afternoon i tried with library Selery but i can't I try this but fail setting.py CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'django-db' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Makassar' from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'MultiLevelApp.tasks.task_number_one', 'schedule': timedelta(seconds=30), } } tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task from .views import autocheck @shared_task def task_number_one(): autocheck() print("check") viewss.py from .tasks import task_number_one task_number_one() end it just run 1 times [enter image description here] -
3 table join in Django
I have 3 tables in a Django based course(and related book) management web app. 3 tables are : Title(book table), CourseInfo(course table), material(course-book relation table). Title table: id title 1 book1 ... CourseInfo table: id title code 1 course1 ICT1 ... material table: id book_id course_id 1 1 1 ... material table correlate book and course(one course could have multiple books and vice versa) Now I want to join select from these 3 tables, to get all the course code for each book . how to do that join select in Django? -
Django 2 different error: "local variable referenced before assignment" + "The view didn't return an HttpResponse object. It returned None instead. "
I try to render this view for a Django project and i can get out from these two errors. The first one is "local variable 'list_of_data' referenced before the assignment. After I change the scope of that variable I get another error "The view didn't return an HttpResponse object. It returned None instead." I tried a few solutions founded around on the web but i couldn't resolve them. Here is the views code: def forecast(request): if request.method == 'POST': city = urllib.parse.quote_plus(request.POST['city']) source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q='+ city +'&units=metric&appid=API_KEY').read() list_of_data = json.loads(source) day = datetime.datetime.today() today_date = int(day.strftime('%d')) forcast_data_list = {} # dictionary to store json data #looping to get value and put it in the dictionary for c in range(0, list_of_data['cnt']): date_var1 = list_of_data['list'][c]['dt_txt'] date_time_obj1 = datetime.datetime.strptime(date_var1, '%Y-%m-%d %H:%M:%S') if int(date_time_obj1.strftime('%d')) == today_date or int(date_time_obj1.strftime('%d')) == today_date+1: # print(date_time_obj1.strftime('%d %a')) if int(date_time_obj1.strftime('%d')) == today_date+1: today_date += 1 forcast_data_list[today_date] = {} forcast_data_list[today_date]['day'] = date_time_obj1.strftime('%A') forcast_data_list[today_date]['date'] = date_time_obj1.strftime('%d %b, %Y') forcast_data_list[today_date]['time'] = date_time_obj1.strftime('%I:%M %p') forcast_data_list[today_date]['FeelsLike'] = list_of_data['list'][c]['main']['feels_like'] forcast_data_list[today_date]['temperature'] = list_of_data['list'][c]['main']['temp'] forcast_data_list[today_date]['temperature_max'] = list_of_data['list'][c]['main']['temp_max'] forcast_data_list[today_date]['temperature_min'] = list_of_data['list'][c]['main']['temp_min'] forcast_data_list[today_date]['description'] = list_of_data['list'][c]['weather'][0]['description'] forcast_data_list[today_date]['icon'] = list_of_data['list'][c]['weather'][0]['icon'] today_date += 1 else: pass #returning the context with all the data to the forecast.html context = { 'forcast_data_list':forcast_data_list } return … -
M1 Mac - GDAL Wrong Architecture Error [Django]
I'm trying to get a django project up and running, which depends on GDAL library. I'm working on a M1 based mac. Following the instructions on official Django docs, I've installed the necessary packages via brew $ brew install postgresql $ brew install postgis $ brew install gdal $ brew install libgeoip gdalinfo --version runs fine and shows the version as 3.3.1 gdal-config --libs returns this path: -L/opt/homebrew/Cellar/gdal/3.3.1_2/lib -lgdal a symlink is also placed on the homebrew's lib directory, which is in my path. When I try to run django, it complains that it cannot find the GDAL package. When I try to specify the path to the GDAL library using GDAL_LIBRARY_PATH, I get this error: OSError: dlopen(/opt/homebrew/Cellar/gdal/3.3.1_2/lib/libgdal.dylib, 6): no suitable image found. Did find: /opt/homebrew/Cellar/gdal/3.3.1_2/lib/libgdal.dylib: mach-o, but wrong architecture /opt/homebrew/Cellar/gdal/3.3.1_2/lib/libgdal.29.dylib: mach-o, but wrong architecture P.s. I've already seen this answer, but it didn't help. Isn't that strange when I try to run gdalinfo it runs fine but when django tries to run it throws me this error? What am I doing wrong? -
how to show facebook data in django website
I am building a website where user can login and see his Facebook data, and other social networking sites at one place(likes, shares, posts, comments etc) I need to pull data from the Facebook. Is there a way that he can just enter email and password and we can pull that, I know about creating an graph API app in Facebook developer. 2 Website is based in Django, what approach will be the best and roadmap to achieve the goal. -
Django: TypeError at /login/ __init__() takes 1 positional argument but 2 were given
I'm trying to update Django version to 3.2.5 from 1.9 in my simple project, and all looks good. But when I try to access the Login page, I get the following error in the browser: Request Method: GET Request URL: http://localhost:49801/login/ Django Version: 3.2.5 Exception Type: TypeError Exception Value: __init__() takes 1 positional argument but 2 were given Exception Location: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response Python Executable: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe Python Version: 3.7.8 Python Path: ['C:\\source\\repos\\aud', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\python37.zip', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\DLLs', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\lib', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python37_64\\lib\\site-packages'] Traceback: Environment: Request Method: GET Request URL: http://localhost:49801/login/ Django Version: 3.2.5 Python Version: 3.7.8 Installed Applications: ['app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /login/ Exception Value: __init__() takes 1 positional argument but 2 were given Additional info from settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
How to determine in javascript when a dict of images created in django has loaded
I am using django and javascript. When a page is first loaded I load a dict of images (around 85 in all) and I don't want the javascript to attempt to display the images until I am sure that all of the images are loaded js $(document).ready(function () { $.ajax( { type: "GET", url: "/common/load-common-data/", cache: false, success: function (context) { images = context.images; setTimeout(() => { displayImages(images) }, 750); } } ); } This is unsatisfactory because the 750 ms delay is arbitrary and might not be sufficient in specific cases I have seen attempts to solve this, but they rely on loading the images individually whereas for various reasons I need to select the images in my view and upload them as a dict. -
TypeError: create_user() missing 1 required positional argument: 'password'
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # User Related Models class cUserManager(BaseUserManager): def create_user(self, email, username, password, **other): if not email or username or password: raise ValueError('All fields must not be blank') email = self.normalize_email(email) user = self.model(email=email, password=password, **other) user.set_password(password) user.save() return user def create_superuser(self, email, password, **other): other.setdefault('is_staff', True) other.setdefault('is_superuser', True) other.setdefault('is_active', True) return self.create_user(email, password, **other) class cUser(AbstractBaseUser): username = models.CharField(max_length=64, unique=True) email = models.EmailField(max_length=64, unique=True) password = models.CharField(max_length=128) # superuser fields is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = cUserManager() No idea what I'm doing wrong, I am clearly setting the password.. or am I? When I was searching for solutions it seems to that people don't make a password field in the user model, so maybe I'm overriding it and that's the reason for the error? -
I cannot add products into my cart View template
I am trying to add a product into my cart , but the product is not being able to add . AffProduct Model is the model where all the details of the product is being stored. Whenever I click on the 'Add To Cart' button the pages are being rendered and all the css and html elements being also renderd , but the product is not being added. Models.py class AffProduct(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='foo') product_title = models.CharField(max_length=255) uid = models.IntegerField(primary_key=True) specification = models.CharField(max_length=255) sale_price = models.IntegerField() discount = models.IntegerField() img1 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") img2 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") promote_method = models.TextChoices terms_conditions = models.CharField(max_length=255, null=True) promote_method = models.CharField( max_length=20, choices=promote_choices, default='PPC' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) This is my CartAdd View: @login_required @require_POST def CartAdd(request, uid): cart = Cart(request) product = get_object_or_404(AffProduct, uid=uid) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('CartDetail') This is my CartAddProductForm from django import forms from .models import Order PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int, label="quantity") update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) The template where i have been trying to render {% block content %} <h1>Your … -
RECEIVING DATA FROM X3 CONCOX GPS DEVICE USING PYTHON
I have a project where I'm trying to receive data from X3 GPS device using python socket. And so far i have managed to create listening script with both port number and IP address configured. s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) host = '192.XX.XX.XX' port = 1234 s.bind((host,port)) s.listen() print(f'listening ...') while True: conn, address = s.accept() print(f'connection from {address} has been establish') And i also configured the IP and the port number to the device via SMS. BUT I can't get it to connect. I need a help to connect the device first before starting receiving login packets or if there are better solutions for the same issue using python. Thank you in advance -
Document Complaint not getting aved after editing in django
I have two pages that help my users view and edit the complaints that they register. There are two types of complaints they can register. One is a written and the other is through a document. When the user tries to edit a written complaint, the edits get saved in the model but when i followed the same logic to edit my document complaints, the users can view them but on editing and saving, the edits are not getting saved, what's wrong? models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber @property def totalcomplaints(self): return Complaint.objects.count() class DocComplaint(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) event_date = models.DateField(null=True, blank=False) document = models.FileField(upload_to='static/documents', blank=False, null=True) def __str__(self): return str(self.event_date) forms.py: class EditComplaintForm(ModelForm): class Meta: model = Complaint fields = ['reportnumber', 'event_type', 'eventdate', … -
How can I copy data of field in other field which is located in other app with different name django
I have two models and In first app there is field name current_bill and in Second app there is field name is previous_bill I want to copy data of current_bill in previous_bill How can I copy it ? meter_detail/models.py Meter(models.Model): current_bill=MoneyField(max_digits=10, decimal_places=2, null=False, blank=True, default_currency='INR') bill_detail/models.py Bill(models.Model): previous_bill=MoneyField(max_digits=10, decimal_places=2,default_currency='INR') I want copy of value which I enter in current_bill and save in Model Bill I tried this def save(self, *args, **kwargs): self.previous_outstanding = self.current_outstanding.previous_outstanding super(BillDetailModel, self).save(*args, **kwargs) But Its not working please give me solution for copy field