Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
fix RelatedObjectDoesNotExist at /agents/ error in django
i am creating a django CRM website but i a have a problem once i want relate the User to an organisation. model.py class User(AbstractUser): pass class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE)# every USER has one profile def __str__(self): return self.user.username class Agent(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE)# every agent has one user organisation = models.ForeignKey(UserProfile,on_delete=models.CASCADE) def __str__(self): return self.user.email # create signal to listen to event in order to create a profile user once a new user is created. def post_user_created_signal(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user = instance) post_save.connect(post_user_created_signal,sender=User) views.py class AgentCreateView(LoginRequiredMixin, generic.CreateView) template_name = "agent_create.html" form_class = AgentModelForm def get_success_url(self): return reverse("agents:agent-list") def form_valid(self, form): agent = form.save(commit=False) agent.organisation = self.request.user.userprofile agent.save() return super(AgentCreateView, self).form_valid(form) once the user try to create an agent this error below is displayed. RelatedObjectDoesNotExist at /agents/ User has no userprofile. Request Method: GET Request URL: http://127.0.0.1:8000/agents/ Django Version: 4.0.6 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no userprofile. Exception Location: C:\Users\LT GM\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\related_descriptors.py, line 461, in get Python Executable: C:\Users\LT GM\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.4 Python Path: ['F:\DJANGO', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\win32', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\win32\lib', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\Pythonwin'] Server time: Sun, 17 Jul 2022 18:54:40 +0000 -
Django LoginView won't log in user
I have an app that is just meant to authenticate a user with Django's generic authentication views. The problem is that I can't log in a user even with the correct username and password. I keep getting an incorrect username or password error. The email and password are always simple such as, "email@email.com" and "123" as password so there's no way I'm messing up the spelling. I'm using Django's built in LoginView, a custom User model, and a custom AuthenticationForm. I've done this project before pretty much the same way with no issues but I can't find the difference between this project and my older project. This is my code. Thank you for your time. Views from .models import MyUser from .forms import MyUserLogin class Login(LoginView): template_name='loginapp/login.html' authentication_form=MyUserLogin success_url='/loginapp/home models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser class MyUser(AbstractBaseUser): fname=models.CharField(max_length=30) lname=models.CharField(max_length=30) email=models.EmailField(max_length=100, unique=True) phone=models.CharField(max_length=12) password=models.CharField(max_length=200) USERNAME_FIELD='email' forms.py from django.forms import ModelForm from django.contrib.auth.forms import AuthenticationForm from django.forms.widgets import TextInput from .models import MyUser class MyUserLogin(AuthenticationForm): class Meta: model=MyUser fields=['email', 'password'] ... login.html ... <div> <form method='post'> {% csrf_token %} <ul> <li><p>Email</p></li> <li>{{form.username}}</li><br> <!-- using "Email" as the label instead of "Username" --> <li>{{form.password.label}}</li> <li>{{form.password}}</li> </ul> <input type='submit' name='submit' class='submit' … -
How to properly implement Django form session wizard
I've been attempting to construct a multi-step form using the Django session wizard for hours, but I keep getting the error, AttributeError: 'function' object has no property 'as_view'. I'm not sure why this mistake occurred. Any ideas? views from django.shortcuts import render from formtools.wizard.views import SessionWizardView from .forms import WithdrawForm1, WithdrawForm2 class WithdrawWizard(SessionWizardView): template_name = 'withdraw.html' form_list = [WithdrawForm1, WithdrawForm2] def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] return render(self.request, 'done.html', {'data': form_data}) forms from django import forms from .models import Investment, Withdraw from .models import WithdrawStepOne, WithdrawStepTwo class WithdrawForm1(forms.ModelForm): class Meta: model = WithdrawStepOne fields = ['investment_id',] class WithdrawForm2(forms.ModelForm): class Meta: model = WithdrawStepTwo fields = [ 'proof_of_address', 'user_pic' ] urls from django.urls import path from .forms import WithdrawForm1, WithdrawForm2 from . import views urlpatterns = [ path('withdraw/', views.WithdrawWizard.as_view(), name='withdraw'), ] -
404 and 500 Errors in JSON
I am trying to fetch data from the JSON that I made but am receiving the following errors: network.js:26 POST http://127.0.0.1:8000/edit/2 404 (Not Found) network.js:18 GET http://127.0.0.1:8000/edit/2 500 (Internal Server Error) I want to fetch the objects from my Django models so that I can allow the user to edit a post which they had previously made through a Django form when the user presses the edit button. models.py class User(AbstractUser): followers = models.ManyToManyField("self", related_name="users_followers", symmetrical=False) following = models.ManyToManyField("self", related_name ="who_user_is_following", symmetrical=False) def serialize(self): return{ "followers": self.followers, "following": self.following } class Post(models.Model): post = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE, default="") likes = models.IntegerField(default=0) date_and_time = models.DateTimeField(auto_now_add=True) def serialize(self): return{ "id": self.id, "post": self.post, "user": self.user, "likes": self.likes, "date_and_time": self.date_and_time } views.py def edit(request, post_id): if request.method == "POST": edited_post = request.POST.get('post') try: post = Post.objects.get(pk=post_id) post.post = edited_post post.save() except: return JsonResponse({"error": "Editing the post did not work."}, status=404) if request.method == "GET": return JsonResponse(post.serialize()) else: return JsonResponse({"error": "Need a GET request."}, status=404) javascript document.addEventListener('DOMContentLoaded', function(){ const editButtons = document.querySelectorAll('.edit_button'); for (const button of editButtons) { id = button.value; button.addEventListener('click', () => edit_email(id)); } }); function edit_email(id){ console.log("edit button is clicked") console.log(id) document.querySelector('#post_itself').style.display = 'none'; document.querySelector('#date_and_time').style.display = 'none'; document.querySelector('#likes').style.display = … -
Django Rest Framework doesn't correctly changes requests text to json
I got below code: from django.contrib.auth import authenticate from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): print(request.data) username = request.data.get("username") password = request.data.get("password") if username is None or password is None: return Response({"error": "Please provide both username and password"}, status=HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if not user: return Response({"error": "Invalid Credentials"}, status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) return Response({"token": token.key}, status=HTTP_200_OK) When I am sending below request at http://localhost:80/api/user/login { "password":"#%RFzv@2BLYM&#jNh6o@46*74f38SV4q", "username":"kamil1234" } I am getting as a request.data below values: <QueryDict: {'_content_type': ['application/json'], '_content': ['{\r\n "password":"#%RFzv@2BLYM&#jNh6o@46*74f38SV4q",\r\n "username":"kamil1234",\r\n}']}> I am not sure what I am doing wrong in here. Since when I use curl everything works correctly. curl --location --request POST 'http://localhost:80/api/user/login' \ --header 'Content-Type: application/json' \ --data-raw '{ "password": "#%RFzv@2BLYM&#jNh6o@46*74f38SV4q", "username": "kamil1234" }' Thank you in advance for the help. -
Django-Allauth equivalent for Django Ninja?
I am developing a REST API for web application in Django Ninja and one of our project's assumptions is possibility of using Google SSO for authentication. Is there any equivalent of Django-Allauth for Django-Ninja? I haven't found anything similar and to be honest I have no idea on how to process that in Django Ninja. Thanks in advance. Kind regards -
Uploading image from aiogram bot in BytesIO format to Django ImageField using aiohttp post method
I'm receiving an image from aiogram bot and I'm saving it in BytesIO format to be able to send to my REST API with post method of aiohttp ClientSession. However, when I try to do that with the following code: import io import aiohttp from aiohttp import FormData # inside aiogram message handler image_in_bytes_io = io.BytesIO() await message.photo[-1].download(destination_file=image_in_bytes_io) formdata = FormData() formdata.add_field(name="image", value=image_in_bytes_io.read()) async with aiohttp.ClientSession() as session: async with session.post(url, data=formdata) as response: print(response.status) print(await response.read()) I'm getting status: 400 and error message: 'File extension \xe2\x80\x9c\xe2\x80\x9d is not allowed.' from my REST API. Can you show where I'm making a mistake? If this solution is wrong, can you show the correct way of uploading an image from aiogram bot to ImageField that is in REST API endpoint? Thanks :) -
MYSQL 0.0.2 package is not installing when running pip install -r requirements.txt
I am trying to install the 'mysql' package ( Version 0.0.2) , using pip install -r requirements.txt But I am facing the following error: Collecting mysql==0.0.2 Using cached mysql-0.0.2.tar.gz (1.9 kB) Preparing metadata (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/pwiwdipw/virtualenv/ITC/3.6/bin/python3.6_bin -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-sbgj4igk/mysql_4feada7a9dca4cc6b8bf0981676447ec/setup.py'"'"'; __file__='"'"'/tmp/pip-install-sbgj4igk/mysql_4feada7a9dca4cc6b8bf0981676447ec/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup;setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-yaqwy2z8 cwd: /tmp/pip-install-sbgj4igk/mysql_4feada7a9dca4cc6b8bf0981676447ec/ Complete output (28 lines): WARNING: `mysql` is a virtual package. Please use `%s` as a dependency directly. running egg_info creating /tmp/pip-pip-egg-info-yaqwy2z8/mysql.egg-info writing /tmp/pip-pip-egg-info-yaqwy2z8/mysql.egg-info/PKG-INFO Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-sbgj4igk/mysql_4feada7a9dca4cc6b8bf0981676447ec/setup.py", line 42, in <module> url="https://github.com/valhallasw/virtual-mysql-pypi-package", File "/home/pwiwdipw/virtualenv/ITC/3.6/lib/python3.6/site-packages/setuptools/__init__.py", line 153, in setup return distutils.core.setup(**attrs) File "/opt/alt/python36/lib64/python3.6/distutils/core.py", line 148, in setup dist.run_commands() File "/opt/alt/python36/lib64/python3.6/distutils/dist.py", line 955, in run_commands self.run_command(cmd) File "/opt/alt/python36/lib64/python3.6/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/home/pwiwdipw/virtualenv/ITC/3.6/lib/python3.6/site-packages/setuptools/command/egg_info.py", line 292, in run writer(self, ep.name, os.path.join(self.egg_info, ep.name)) File "/home/pwiwdipw/virtualenv/ITC/3.6/lib/python3.6/site-packages/setuptools/command/egg_info.py", line 656, in write_pkg_info metadata.write_pkg_info(cmd.egg_info) File "/opt/alt/python36/lib64/python3.6/distutils/dist.py", line 1106, in write_pkg_info self.write_pkg_file(pkg_info) File "/home/pwiwdipw/virtualenv/ITC/3.6/lib/python3.6/site-packages/setuptools/dist.py", line 188, in write_pkg_file license = rfc822_escape(self.get_license()) File "/opt/alt/python36/lib64/python3.6/distutils/util.py", line 474, in rfc822_escape lines = header.split('\n') AttributeError: 'list' object has no attribute 'split' ---------------------------------------- WARNING: Discarding … -
In Django, how to temporatily store consecutive user inputs in the backend within 60s?
I am having trouble storing user inputs temporarily in Django backend (like 60 seconds for a game. Once the game is over, it should delete all user input records). To make it clear: I want to develop a website game using python and Django as backend languages, where it takes user input (one word as one input) and counts how many words a user can give in 60 seconds. The website should remain the same after each submission, but the game records each user input in the backend and counts on it while the game is still running. I think that I should use a session in Django but I'm still not sure about how should I approach this problem. As the picture shows, the input box can only take 1 word for each submission, and continue taking user inputs until the timer ends. So, how should I save these temporary user inputs using Django? -
Why does a non required field in a serializer serialize the field?
Say I have a serialiser like class DumbSerializer(serializers.Serializer): field_one = serializers.CharField(required=False, allow_null=True) And I do something like asdf = DumbSerializer(data={}) asdf.is_valid() >>> True asdf.data >>> {'field_one': None} asdf.validated_data >>> OrderedDict() Why is the serialization of {} represented as {'field_one': None} and not {}, given that field_one is not a required field? The python internal representation is an empty dict as I would expect -
Django error: null value in column of relation violates not-null constraint
I have a simple Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE, null=True) description = models.TextField() MEETING_PLACES = [ ('Zoom', 'Zoom'), ('WhatsApp Call', 'WhatsApp Call'), ('Skype', 'Skype'), ('Other', 'Other'), ] meeting_place = models.CharField( choices=MEETING_PLACES, max_length=255 ) other_meeting_place = models.CharField(max_length=255, verbose_name='Other', blank=True, null=True) My focus was having the other_meeting_place input only be visible when ('Other', 'Other'), was selected. The html in my templates: <select name="meeting_place" id="meetingPlace" required=""> <option value="" selected="">---------</option> <option value="Zoom">Zoom</option> <option value="WhatsApp Call">WhatsApp Call</option> <option value="Skype">Skype</option> <option value="Other">Other</option> </select> <input type="text" name="other_meeting_place" id="other" maxlength="255" style="display: none;"> Using javascript: let meetingPlace = document.getElementById('meetingPlace') let other = document.getElementById('other') other.style.display = 'none' meetingPlace.onchange = () => { if (meetingPlace.options[meetingPlace.selectedIndex].text === 'Other') { other.style.display = 'block' } else if (meetingPlace.options[meetingPlace.selectedIndex].text !== 'Other') { other.style.display = 'none' } } Now when I submit to create a new group I get this error in the terminal: return self.cursor.execute(sql, params) django.db.utils.IntegrityError: null value in column "other_choice" of relation "chaburah_chaburah" violates not-null constraint I made migrations and migrated and didn't see an error, only when I try and create a Group. I've seen a people answer questions regarding not-null constraints, but there's a lot of answers to choose from and I couldn't find one that applied to … -
How to add and configure VSCode launch.json in Django project already containing docker-compose and dockerfile
I have a Django project with the following folder configuration: Apache Backend (git submodule) django_backend apis (contains urls.py, views.py, etc) django_backend manage.py docker dockerfile dockerfile-dev local dockerfile Frontend (git submodule) docker-compose.yml docker-compose.deploy.yml docker-compose.dev.yml It doesn't have a launch.json file to debug it, and I want to add a launch.json file to be able to debug it using VSCode and attach it to the running container. How should I configure the launch file? -
How can I get my Django server to reload when I change the HTML in dev mode without clicking the refresh button?
I'm working on a Django project. Right now (if you're the dev) you can make changes to the HTML pretty easily. i'm not having any issues with that, i just want to know how to get the server to reload when the HTML changes. here's the github. https://github.com/jeffcrockett86/django-unchained -
Getting error in django-import-export | ValueError: Field 'id' expected a number but got ''
I am using Django-import-export for importing data but facing an error given below. code for Django-import-export is given below: class MemberResource(resources.ModelResource): Brand=Field() class Meta: model = model fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') export_order=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') def dehydrate_Brand(self, obj): return str(obj.Brand.title) class modelAdmin(ImportExportModelAdmin): resource_class = MemberResource list_display=['id','title','Model_code','Chipset','chipset_description','Brand','categories'] search_fields = ['title','Model_code','Chipset',] fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat') admin.site.register(model,modelAdmin) I am getting below error Line number: 1 - Field 'id' expected a number but got ''. 2, f9, sd, gf, kjkj, images/sample_3pahsfV.jfif, 1, 1 Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\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\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'Brand' During the handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields_init_.py", line 1988, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 707, in import_row diff = self.get_diff_class()(self, original, new) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 241, in init self.left = self._export_resource_fields(resource, instance) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in _export_resource_fields return [resource.export_field(f, instance) if instance else "" for f in resource.get_user_visible_fields()] File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in return [resource.export_field(f, instance) if instance else "" for f in resource.get_user_visible_fields()] File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 919, … -
AssertionError: No templates used to render the response
I solved the problem while writing this question but I wanted to post it so maybe someone needs this answer Hello my friends. i am new to django testing. while i'm testing my views i faced this error in some views. This is my views.py: def all_programs(request): programs = Program.objects.all() return render(request, 'orders/all_programs.html', {'programs': programs}) def checkout(request, slug): if request.method == 'POST': # get data from form and save it program = get_object_or_404(Program, slug=slug) dates = ProgramDate.objects.filter(program=program) return render(request, 'orders/checkout.html', {'program': program, 'dates': dates}) This is urls.py: from django.urls import path from django.views.generic import RedirectView from .views import * app_name = 'orders' urlpatterns = [ path('', RedirectView.as_view(url='https://www.another-website.net')), path('tests/', all_programs, name='all_programs'), path('checkout/<str:slug>/', checkout, name='checkout'), path('checkout/return_page/', ReturnPage.as_view(), name='return_page'), ] And this is test_views.py: from django.test import TestCase from django.shortcuts import reverse class TestViews(TestCase): def test_all_programs(self): response = self.client.get(reverse('orders:all_programs')) self.assertTemplateUsed(response, 'orders/all_programs.html') def test_checkout(self): # error id here response = self.client.get(reverse('orders:all_programs', kwargs={'slug': 'test'})) # I tried this # response = self.client.get('http://127.0.0.1:8000/checkout/test/') #and this self.assertTemplateUsed(response, 'orders/checkout.html') -
When I use django seed, is it possible to create the next value of the dictionary by referencing the value inside the dictionary?
I am working on creating virtual data using django_seed. What if I randomly scatter the "check_in" date and try to create a random "check_out" date based on the previously generated "check_in" date? The "check_out" date must be after the "check_in" date. … import random from datetime import datetime, timedelta from django.core.management.base import BaseCommand from django_seed import Seed from reservations import models as reservation_models from users import models as user_models from rooms import models as room_models SEED_NAME = "reservations" class Command(BaseCommand): help = "This command creates {SEED_NAME}" def add_arguments(self, parser): parser.add_argument( "--number", default=2, type=int, help="How many {SEED_NAME}?" ) def handle(self, *args, **options): number = options.get("number") seeder = Seed.seeder() users = user_models.User.objects.all() rooms = room_models.Room.objects.all() seeder.add_entity( reservation_models.Reservation, number, { "status": lambda x: random.choice( ["pending", "confirmed", "canceled"] ), "check_in": lambda x: datetime.now(), "check_out": lambda x: datetime.now() + timedelta(days=random.randint(3, 25)), "guest": lambda x: random.choice(users), "room": lambda x: random.choice(rooms) }, ) seeder.execute() self.stdout.write(self.style.SUCCESS(f"{number} {SEED_NAME} created!")) -
Cannot load translation catalog for Django I18n on Google App Engine Standard
I've set up I18n for my Python3 Django4.0 app and it runs locally without problems. When I deploy it to GAE standard the translated text isn't shown. The active language changes, but the text does not change. The catalog files exist, but it looks like they are not being loaded. I am aware that GAE-standard only allows access to tmp/ directory. Could this be the reason? Are there particular cache requirements? Any advice or examples would be super useful. -
Swich to light or dark mode on Django?
How can I make a button that when pressed would change my css href between light.css and dark.css I want it without using JavaScript. -
Why this ERROR occurred " ModuleNotFoundError: No module named 'django.ulrs' "?
I was working with Django in urls.py I added a new path that would relate the urls.py in the app to the main urls.py. when I was about to run the server this error occurred and I don't know what is the problem ModuleNotFoundError: No module named 'django.ulrs' and I am pretty sure that Django has a module name django.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('ticketing/', include('Ticketing.urls')) ] -
How do I extend an <li> element?
I have a nav under a header and I want the nav-links to change color and for a white background to be added when hovered over. However, when I hover over the links the white background only shows around the link instead of extending to the most available space as the links are displayed in flex where justify-content: space-around. There are 4 links so I want each link to take up a quarter of the page. How do I do this? HTML: <nav> <ul class="nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}">Active Listings</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}">Categories</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}">Watchlist</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}">Create Listing</a> </li> </ul> </nav> CSS: nav { background-color: var(--purple); color: #fff; } .nav-link { color: #fff; } li { width: auto; } li:hover { color: var(--purple); background-color: #fff; text-decoration: none; border-radius: 5px; } .nav { display: flex; justify-content: space-around; align-items: center; } -
Limiting API request in django rest framework
I am new to Django | DRF and trying to create a DRF coupon system for course purchases , how can i limit the coupon validity on the basis of number of user used it or some specific time span for ex. only first 50 users can use the code or it will be valid only for next week. (I haven't write the code for it yet that's why i am not able to give you all some insights) I've read a bit of throttling but if i am not wrong it only limits on the basis of rate Any reference will be really helpful. Thanks ! -
forms fields returning None
I have form, of which travel_date and max_amt fields returning none after submitting the form from template code for ref: forms.py class GetQuery(forms.Form): origin = forms.CharField(max_length=30, widget=forms.TextInput( attrs={'type': 'text', 'id': 'org', 'name': 'origin', 'placeholder': 'origin code'})) destination = forms.CharField(max_length=30, widget=forms.TextInput( attrs={'type': 'text', 'id': 'dst', 'name': 'destination', 'placeholder': 'destination code'})) travel_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date', 'name': 'date'})) max_amt = forms.CharField(max_length=6, widget=forms.NumberInput( attrs={'type': 'number', 'id': 'amt', 'name': 'amount', 'placeholder': 'Enter Price Range'})) Views.py def home(request): if request.method == "POST": origin, destination, date, amount = request.POST.get('origin'), request.POST.get('destination'), request.POST.get('date'), request.POST.get('amount') print(origin, destination, date, amount) IC = AC.objects.all().order_by('-pk') form = GetQuery return render(request, 'index.html', context={'IC':IC, 'form': form}) template <form name="TravelQuery" method="post" novalidate="novalidate"> {% csrf_token %} <div class="row"> <div class="col-6"> {{ form.origin|as_crispy_field }} </div> <div class="col-6"> {{ form.destination|as_crispy_field }} </div> <div class="col-6"> {{ form.max_amt|as_crispy_field }} </div> </div> {{ form.travel_date|as_crispy_field }} <div class="col-md-12 text-right"> <button type="submit" value="submit" class="btn btn-primary primary-btn text-uppercase">Send Message</button> </div> </form> getting values for origin and destination but not for travel_date and max_amt. -
django-import-export | issue in importing data to database | ValueError: Field 'id' expected a number but got ''
I am using Django-import-export for importing data but facing an error given below. Code settings i tried to import data to postgresql database by django-import-export class MemberResource(resources.ModelResource): Brand=Field() class Meta: model = model fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') export_order=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') def dehydrate_Brand(self, obj): return str(obj.Brand.title) class modelAdmin(ImportExportModelAdmin): resource_class = MemberResource list_display=['id','title','Model_code','Chipset','chipset_description','Brand','categories'] search_fields = ['title','Model_code','Chipset',] fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat') admin.site.register(model,modelAdmin) and got below error also attached the image where i exported the data from app and then edited the same and tried to import and stuck with below error. [Line number: 1 - Field 'id' expected a number but got ''. 2, f9, sd, gf, kjkj, images/sample_3pahsfV.jfif, 1, 1 Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\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\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache\[cache_name\] KeyError: 'Brand' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\_init_.py", line 1988, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 707, in import_row diff = self.get_diff_class()(self, original, new) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 241, in _init_ self.left = self._export_resource_fields(resource, instance) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in _export_resource_fields return \[resource.export_field(f, … -
submit multiple forms in django using custom html form
I have custom forms in the page suprated across the page here is my first form <form name="profile_image" class="edit-phto" method="POST" enctype="multipart/form-data"> <i class="fa fa-camera-retro"></i> <label class="fileContainer"> Edit Display Photo <input name="profile_image" value="" type="file" /> </label> </form> for profile picture and i have another form for cover picture <form name="cover_image" class="edit-phto" enctype="multipart/form-data"> <i class="fa fa-camera-retro"></i> <label class="fileContainer"> Edit Cover Photo <input name="cover_image" type="file" /> </label> </form> and another form for data :) <form method="post" id="infoform" enctype="multipart/form-data"> {% csrf_token %} . . . . <div class="submit-btns"> <button type="button" class="mtr-btn"><span>Cancel</span></button> <button type="submit" class="mtr-btn" name="update"><span> Update</span></button> </div> and i have a form for search <div class="searched"> <form method="post" class="form-search"> <input type="text" placeholder="Search Friend"> <button data-ripple><i class="ti-search"></i></button> </form> </div> i just want to submit the 2 images forms and info forms when i click update button is there a way to do sachthing in django without using form.as_p and stuff like that -
Best Django Analytic service or how do i implement a good analytic dashboard
Im new to Django and im trying to build a analytic dashboard for my Django e-commerce project that tracks income, expenses and popular items(items with high demand) and I've been surfing but I cant find how to do it. If anyone has any service that they recommend or any tips on how to implement it ill appreciate it