Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Manipulating data from a form to model django
I am quite new to django and having trouble manipulating data from a form before it reaches the table (model). Html: <p><label for="id_1">Choice 1:</label> <select name="choice_1" id="id_1"> <option value="1">Apple</option> <option value="2">Orange</option> </select></p> <p><label for="id_2">Choice 2:</label> <select name="Choice_2" id="id_2"> <option value="1">Cat</option> <option value="2">Dog</option> </select></p> <p><label for="id_3">Choice 3:</label> <select name="Choice_3" id="id_3"> <option value="1">Italy</option> <option value="2">France</option> </select></p> The results of this form are currently being sent to the table like: | ID | Choice 1 | Choice 2 | Choice 3 | ---- ---------- ---------- ---------- | 1 | Apple | Cat | Italy | ---- ---------- ---------- ---------- I would like it to be sent as: | ID | Choice | Preference | ---- ---------- ------------ | 1 | Choice 1 | Apple | | 1 | Choice 2 | Cat | | 1 | Choice 3 | Italy | ---- ---------- ------------ So if my model is: class user_choice(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.CharField(max_length=30) preference = models.CharField(max_length=30) My form: class SubmitChoiceForm(forms.ModelForm): choice_1 = forms.ChoiceField(choices=choice1, required=False) choice_2 = forms.ChoiceField(choices=choice2, required=False) choice_3 = forms.ChoiceField(choices=choice3, required=False) class Meta: model = user_choice fields = ( ) My View: def post(self, request): form = SubmitChoiceForm(request.POST) if form.is_valid(): tip = form.save(commit= False) tip.user = request.user … -
Django user registration with phone and password
i am creating custom user model in django using abstract base user class, i want to create user with only two fields "phone and password " and name being the optional field , which i have set in my models .py that blank =true. i have created a rest api for user registration using my custom user model, but every time i try to create new user with phone and password it gives me below error:- IntegrityError at /api/users/ UNIQUE constraint failed: accounts_user.name Request Method: POST Request URL: http://127.0.0.1:8000/api/users/ Django Version: 3.0.1 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: accounts_user.name Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 396 Python Executable: /usr/local/opt/python/bin/python3.7 Python Version: 3.7.6 Python Path: ['/Users/raghav/milkbasketdemo/milkbasketdemo', '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages'] Please help where i am going wrong , i have searched and tried changing code number of times but nothing is working for me. please find the below code of models.py class UserManager(BaseUserManager): def create_user(self,phone, password=None,is_staff=False,is_admin=False,is_active=True): if phone is None: raise TypeError('Users must have a phonenumber.') user = self.model(phone=phone) user.set_password(password) user.staff=is_staff user.admin=is_admin user.active=is_active user.save(using=self._db) return user def create_staffuser(self, phone, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( phone, password=password, … -
little bit confuse in dgetting absolute url in django
#project url from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include import products urlpatterns = [ path('admin/', admin.site.urls), path('', include('products.urls')), url(r'^product/(?P<title>[\w-]+)/$', products.views.single,name='single') ] # app url from django.urls import path, include import products from . import views urlpatterns = [ path('', views.home, name='home'), ] #model class products(models.Model): title = models.CharField(max_length=120) desc = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2, default=29.99) sales_price = models.DecimalField(max_digits=10, decimal_places=2, blank=False, null=False, default=0) slug = models.SlugField(unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) update = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __str__(self): return self.title def get_price(self): return self.price def get_absolute_url(self): return reverse("single", kwargs={"title": self.title}) #views def home(request): product = products.objects.all() template = 'home.html' context = {'product': product} return render(request, template, context) def single(request,title): try: product = products.objects.get(title=title) template = 'products.html' context = {'product': product} return render(request, template, context) except: raise Http404 plz view my code .. i m littlebit confuse in absolute url.. it returns title of the product after clicking some link but it doesnt give me the title if i change produc to other. for eg:http:/127.0.0.1:8000/product/T-shirt/ gives title but wheni hit http:/127.0.0.1:8000/productS/T-shirtgives eroror -
How to clear all data from an app in Django?
I want to remove all data from all models defined in a single Django app. The number of models might change in the app, hence I don't want to hard code model names. It would be great if it might be done using manage.py command, however I was not able to find one. The manage.py flush command is not suitable, because it only allows to clear data from all apps. -
Django:How to setup static files in django project
I created a simple project in Django but static files(CSS) not working. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.portfolio), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) HTML file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static 'portfolio.css' %}"> </head> <body> <h1>hello world</h1> </body> </html> picture of the project directory blog is app and my_site is a project. -
Django cannot find static file on proxy pass
I have managed to make my Django app work from a VPS location, but now it does not load one of the static files which is requested by the app template. The application path is 'http://dev.apps.gdceur.eecloud.dynamic.nsn-net.net/tacdb/' static files config in settings.py: STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "mysite/static") # Site name. SITE_NAME = basename(DJANGO_ROOT) # Absolute filesystem path to the top-level project folder. SITE_ROOT = dirname(DJANGO_ROOT) STATICFILES_DIRS = (os.path.join(BASE_DIR, "mysite", "/static"),) The javascript request in the html file: {% block javascript %} <script src="{% static '/js/books.js' %}"></script> {% endblock %} the html file is located /tacdb/mysite/tacdashboard/templates/items/item_list.html the request for the static file is http://dev.apps.gdceur.eecloud.dynamic.nsn-net.net/static/js/books.js I use a proxy pass to in Apache for this app. If I run the app directly on the port using runserver, everything works fine. Any ideeas what is going wrong? P.S. this problem appeared when i added location to the proxypass. Thanks a lot! -
Form wont load in the django app
Code below for Django app. I am not sure why the forms wont load up in the "http://localhost:8000/.../new/" HTML page. Only the label "New Post" shows up in the web page. The form is missing. #models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() #forms.py from django import forms from blog.models import Post from django.forms import ModelForm class PostForm(ModelForm): class Meta: model = Post fields = ('title', 'body') #views.py from django.shortcuts import render from .models import Post from .forms import PostForm def post_new(request): thisform = PostForm() return render(request, "post_edit.html", {'thisform': thisform}) #post_edit.html {% extends "base.html" %} {% load static %} {% static 'images' as base_url %} {% block content %} <h2>New post</h2> <form method="POST" >{% csrf_token %} {{ thisform.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} #base.html <li class="nav-item"> <a class="nav-link" href="{% url 'post_new' %}">Add Post</a> </li> #blog/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("new/", views.post_new, name="post_new"), ] -
Displaying an image from a model in a Django template
I'm trying to access an image from a model in my template: In my template, I have: {% for server in servers %} <div class="hs-item set-bg" data-setbg="{{ server.image.url }}"> <div class="hs-text"> <div class="container"> <h2>The Best <span>Games</span> Out There</h2> <p>Lorem ipsum.</p> <a href="#" class="site-btn">Read More</a> </div> </div> </div> {% endfor %} And my models look like this: class Server(models.Model): Name = models.CharField(max_length=100) IP = models.CharField(max_length=50) Port = models.IntegerField() Image = models.ImageField(default='default.jpg', upload_to='server_pics') def __str__(self): return str(self.Name) if self.Name else '' I've added this to my settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And this to my urls.py: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But it doesn't display the image, and I don't get an error in the console... Not sure what I'm doing wrong here -
referencing field from different model from a function field
I have a Game model and an ActiveGame model. I want to track the games in progress which will have a start_time (current time) and end_time(start time - Game.duration) This is my model (redacted for easy read): class Game(models.Model): title = models.CharField(max_length=255,null=False, blank=False) tiempo = models.DurationField(null=True, blank=True,default="00:60:00") def get_end_time(): return datetime.now() + timedelta(1d) --> here I want to retrieve Game.tiempo class ActiveGame(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField(default=timezone.now) end_time = models.DateTimeField(default=get_end_time) I defined the start_time default in a separate function as recommended and works fine with hardcoded values but I want to retrieve that information from Game model. I have tried many variants of: def get_end_time(self): return datetime.now() + timedelta(self.Game.tiempo) end_time = models.DateTimeField(default=get_end_time(self)) I can't figure out how a field that calls a function can gather information of other model that has already a relationship with a foreign key -
Django: ViewSets not accepting login required, rending SessionAuthentication useless
I am having issues using the DRF SessionAuthentication with views defined as ModelViewSets. The "LoginRequiredMixin" works fine in generics views, but I really don't like those as they require me to define all the urls manually and set them in the proper order. Very tedious when ViewSets allow you to define routes way more neatly. I have tried using the "@login_required" decorator following Django's doc authentication login(), but it doesn't accept it. Have tried specifying the authentication_class SessionAuthentication in my ViewSet but to no avail, following those posts: JWT required login login required Current FooBar_views.py file. The only way I have here so far to make sure a user is authenticated, is to check his JWT provided in the headers of his http request. foobar_vews.py with ViewSets # @login_required not being accepted when imported class FooBarViewSet(viewsets.ModelViewSet): """ Foo Bar ViewSet calling various serializers depending on request type (GET, PUT etc.) """ # Trying to filter FooBars list by status: Exluding unwanted ones queryset = FooBar.objects.exclude(status__name = 'SOLD').exclude(status__name = 'DELETED').order_by('id').reverse() # mapping serializer into the action serializer_classes = { 'list': FooBarIndexSerializer, 'retrieve': FooBarDetailsSerializer, 'create': FooBarCreateSerializer, } # Your default serializer default_serializer_class = FooBarIndexSerializer def get_serializer_class(self): """ Method to detect request type … -
TypeError: __str__ returned non-string (type int) Django
i'm trying to do a GET request, but i get this error: TypeError: str returned non-string (type int) I do not know what I'm doing wrong. Here's my code: in my models.py class Prueba(models.Model): id_prueba = models.AutoField(primary_key=True) nombre = models.CharField(max_length=255, blank=False, null=False) descripcion = models.TextField(max_length=255, blank=True, null=True) fecha_creacion = models.DateTimeField(default=datetime.now) id_cliente = models.ForeignKey(Cliente, related_name='clientes', on_delete=models.CASCADE) id_atentusiano = models.ForeignKey(Atentusiano, related_name='atentusianos', on_delete=models.CASCADE) id_carga = models.ForeignKey(Carga, related_name='cargas', on_delete=models.CASCADE) id_estado = models.ForeignKey(EstadoPrueba, related_name='estados', on_delete=models.CASCADE) id_costo = models.ForeignKey(Costo, related_name='costos', on_delete=models.CASCADE) class Meta: verbose_name = 'Prueba' verbose_name_plural = 'Pruebas' ordering = ['nombre'] def __str__(self): return self.nombre i tried with return str(self.nombre) but I keep getting the same error. In all other tables and models I have no problem. Help me please. -
How to star Tailwind CSS inside Django?
I'm starting to use Tailwind CSS. I've found django-tailwind to make the integration of tailwind as an app. I've followed all steps to install it on Windows 10, and it gave me no errors. https://github.com/timonweb/django-tailwind Then I reach step 7: Now, go and start tailwind in dev mode: python manage.py tailwind start But when running: python manage.py tailwind start To start tailwind in dev mode, I get: (ministerios_elim) PS D:\web_proyects\ministerios_elim> python manage.py tailwind start > django_tailwind@ start D:\web_proyects\ministerios_elim\theme\static_src > watch "npm run build-postcss" ./src > Watching ./src > django_tailwind@ build-postcss D:\web_proyects\ministerios_elim\theme\static_src > postcss --config . --map false --output ../static/css/styles.min.css ./src/styles.scss Terminal doesn't allow me to type anything else, it is just like the process is still running: What should I do? Should I enter some command? I've never worked with node before. I tried to look into the code of the library, to figure out what exactly python manage.py tailwind start does. https://github.com/timonweb/django-tailwind/blob/master/tailwind/management/commands/tailwind.py But couldn't find it. -
how to pass the id of a model that is related to other model with a foreign key in the url of delete view in django framework
I have models alumni, graduation, and graduation project class Alumni(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.user) class Graduation(models.Model): faculty = models.CharField(max_length=120) degree = models.CharField(max_length=120) yearOfGraduation = models.CharField(max_length=120) groupNumber = models.CharField(max_length=120) alumni = models.ForeignKey(Alumni, on_delete=models.CASCADE, related_name='graduation') def __str__(self): return str(self.faculty) class GraduationProject(models.Model): title = models.CharField(max_length=120) description = models.TextField() mark = models.IntegerField(blank=True, null=True) gitLink = models.CharField(max_length=120) graduation = models.OneToOneField( Graduation, on_delete=models.CASCADE, primary_key=True, related_name='projects') def __str__(self): return str(self.title) and I made the update view and the delete view of the graduation and graduation project class GraduationUpdateView(UpdateView): model = Graduation template_name = "graduation_edit.html" fields = '__all__' class GraduationDeleteView(DeleteView): model = Graduation template_name = "graduation_delete.html" success_url = reverse_lazy('AlumniList') class GraduationProjectUpdateView(UpdateView): model = GraduationProject template_name = "graduation_project_edit.html" fields = '__all__' class GraduationProjectDeleteView(DeleteView): model = GraduationProject template_name = "graduation_project_delete.html" context_object_name = "project" success_url = reverse_lazy('AlumniList') and in my urls I wrote them this way path('/<int:pk>/graduation/edit/', GraduationUpdateView.as_view(), name='editGraduation'), path('/<int:pk>/graduation/delete/', GraduationDeleteView.as_view(), name='deleteGraduation'), path('/<int:pk>/graduation/project/edit', GraduationProjectUpdateView.as_view(), name='editProjGraduation'), path('/<int:pk>/graduation/project/delete', GraduationDeleteView.as_view(), name='deleteProjGraduation'), and in my templates when I pass the id of the user I don't know how to pass also the id of the specific project and the specific graduation, it deletes the all graduation instead of the graduation project, here is how I wrote it <a href="{% url 'editGraduation' … -
django export to csv only exports data from current page
I am trying to export a django Listview to csv. I created a view for a ListView, which has a custom get_queryset() function to create the filtered result. The Listview itself uses pagination for displaying the data. For the export i created a subclass, inheriting the Listview, with a custom url and a csv template file. The Listview and the export process itself works pretty fine, but i do not get the complete queryset in the csv, but only the data present on the first page of the paginated Listview. Any suggestions what i am missing? -
Django ManyToMany Relationship and Auto Add
I have two classes Post and Category. They work fine. However, when I add a post belongs some categories, I also want those categories should insert posts that i added. Models.py: class Category(models.Model): title = models.CharField(max_length=40, verbose_name='Category') posts_of_category = models.ManyToManyField('Post',related_name="+",auto_created=True) def __str__(self): return self.title class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE, verbose_name='Author') title = models.CharField(max_length=60) content = models.TextField(verbose_name='Content') category= models.ManyToManyField('Category', verbose_name='Category') date = models.DateField(verbose_name='Date', auto_now_add=True) post_img= models.ImageField() def __str__(self): return self.title And please see image : Screenshoot -
Is there a way to convert the uploaded excel file to CSV using django pre_save signal?
I would like to know if it is possible to convert the user selected excel file to CSV using django pre_save signals. Suppose a user uploads 'test.xlsx', I would like to convert that file automatically using the pre_save signal. Once the user uploads the file, it should actually be 'test.csv' in my FileField. -
Django MySQL throws an error, Library not loaded: /usr/local/opt/mysql@5.6/lib/libmysqlclient.18.dylib
Yes, this seems like a common error. But something else is wrong with my environment. I have upgraded from MySQL 5.6 version to 5.7. I can access mysql5.7 by typing mysql into the console. I have updated the DYLD_LIBRARY_PATH to reflect new 5.7 location git:(parent-child) ✗ echo $DYLD_LIBRARY_PATH /usr/local/opt/mysql@5.7/lib/: But the error for reason still says it is trying to load from 5.6 version. Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/vineeth/envs/automize2.0/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module> import MySQLdb as Database File "/Users/vineeth/envs/automize2.0/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/vineeth/envs/automize2.0/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: /usr/local/opt/mysql@5.6/lib/libmysqlclient.18.dylib Referenced from: /Users/vineeth/envs/automize2.0/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: image not found Notice the error says it still is trying locate /usr/local/opt/mysql@5.6/lib/libmysqlclient.18.dylib I have reinstalled almost everything since this error came. Tried several solutions Python mysqldb: Library not loaded: libmysqlclient.18.dylib rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib Nothing seems to change its reference. How do I make it refer to the newer one which is in /usr/local/opt/mysql@5.7/lib/ Help is welcome. Been struggling since a day. -
SMTPSenderRefused at /password-reset/
I'm having this error, I'm using Ubuntu Linux os here I made env variable at a home section named ".bash_profile" in which I saved my Gmail and pass. Now the problem is when I'm calling them in settings.py file they don't work but instead of it if I try to put email and pass there, it works fine and I get the reset email. Things that I've already tried are- List item The same name of both the variables from the env variable and in settings.py I'm not using 2FA so I allowed the less secure app. Tried to use 2FA and followed the different process. Mail id in Django user and this user is the same. Already looked for the different answers on stack overflow and other sites. code are as follows settings.py """ Django settings for blog_page project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key … -
How to access users socialaccount email within django
I am currently trying to access google users email using the allauth libraries in django. I have had no trouble getting common @gmail domains emails but I am currently trying to login through a .edu based domain and cannot get the email from the request in views through request.user.email I can see in the social accounts section of the django admin site that the users with this different domains email is within the extra_data section, is there anyway to access this extra_data in the social account and extract the email and then assign the users email to their account within the django application? Sorry, if this isn't asked in the best possible way I'm fairly new to coding and very new to django. -
Error when creating super user in Django custom user model
Django: 3.0.5 Python: 3.7.3 I am rather new to Django's framework and I have been trying to create a custom user model so that the default username is an email. However, I cannot seem to create a superuser. I keep getting this error after calling py manage.py createsuperuser: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\User\Dev\tryDjango\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\User\Dev\tryDjango\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\Dev\tryDjango\lib\site-packages\django\core\management\base.py", line 320, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\User\Dev\tryDjango\lib\site-packages\django\core\management\base.py", line 294, in create_parser self.add_arguments(parser) File "C:\Users\User\Dev\tryDjango\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 55, in add_arguments field = self.UserModel._meta.get_field(field_name) File "C:\Users\User\Dev\tryDjango\lib\site-packages\django\db\models\options.py", line 583, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: User has no field named '' Below is the codes for my custom user model, I have also placed AUTH_USER_MODEL = 'accounts.User' in my settings.py. class UserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an Email address") if not password: raise ValueError("Users must have a Password") user = self.model( email=self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password=None): user = self.create_user( email, password=password ) user.staff = True user.save(using=self._db) return user def … -
Apache, Django and wsgi, No module named 'encodings'
I've looked through many stack overflow questions with the same issues, but none of them solved my issue. I'm trying to deploy Django on AWS - Ubuntu 18.04 using Apache and WSGI. When running my website with Django's servers on port 8000, everything works fine. Then when I attempt to run on apache I get the following error in my logs. Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations Command line: '/usr/sbin/apache2' (2)No such file or directory: mod_wsgi: Unable to stat Python home /var/www/html/projects/venv Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' As it says clearly mod_wsgi and Python 3 are configured. I am using a virtual environment. My project is located at: /var/www/html/project/venv/mysite My Apache conf file is configured as: <Directory /var/www/html/projects/venv/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite python-path=/var/www/html/projects/venv/mysite python-home =/var/www/html/projects/venv WSGIProcessGroup mysite WSGIScriptAlias / /var/www/html/projects/venv/mysite/mysite/wsgi.py Alias /static /var/www/html/projects/venv/mysite/polls/static <Directory /var/www/html/projects/venv/mysite/polls/static> Require all granted </Directory> I'm not sure where to go from here. I don't fully understand what the error means. I have Python installed in … -
Custom path parameter parsing drf-yasg and Django
I'm trying to force dry-yasg to properly parse parameters from path. Let's say we have path('users/<int:user_id>/', whatever.as_view(...)) In swagger docs it is not treated as int, but string instead I have used swagger_auto_schema(manual_parameters = [ openapi.Parameter( name, openapi.IN_PATH, description=desc, type=openapi.TYPE_INTEGER, required=True ) ] but it's pretty annoying. I could not find a function/method/class responsible for parsing that. Is there a simple method to change behaviour of this parser based on path, so that if int occurs then openapi.TYPE_INTEGER will be returned instead of string? -
I cant view my form inputs in the django database
iam a learner in django. i have created my first form, but when i input data i dont see it in my database but see in in my shell. I have rechecked my code but it seem fine, yet still it wont save in my code in the database. Please help me out here.Thanks. <pre> from django.db import models # Create your models here. class Login(models.Model): first_name = models.CharField(max_length=200) second_name = models.CharField(max_length=200) email = models.EmailField() password = models.CharField(max_length=200) <pre>`from django.http import HttpResponse from django.shortcuts import render from .models import Login from .forms import login_form # Create your views here. def homeview(request): return HttpResponse("<h1>Hello There</h1>") def login_view(request): form = login_form(request.POST or None) if form.is_valid: form.save context ={ "form":form } return render(request, "login.html", context) <pre># html code {% block content %} <form action="" method="GET">{% csrf_token %} {{form.as_p}} <input type="submit" value="Login"/> </form> {% endblock %} <pre># form code from django import forms from .models import Login # This is the form code. class login_form(forms.ModelForm): class Meta: model = Login fields = [ "first_name", "second_name", "email", "password" ] -
Opening AdminAction in new tab, Django
I have an AdminAction that generates pdf and I would like to open it in new tab. How do I do that? So far I have used a redirect from that AdminAction to a url to a view function, but I can't seem to connect the view function(url) to some . -
Why are some inputs not rendering in this Django ModelForm?
I just started learning Django and have the following issue. I created a form to update a table in my DB and it has two fields that are ForeignKeys in the model. This two fields are not showing up (brand and model) in the template, they have labels but there is not an input to it, while the other two have their labels and inputs. Here is my code models.py class Computer(models.Model): serialNo = models.CharField(max_length=128, unique=True) description = models.CharField(max_length=255, null=True) brand = models.ForeignKey(Cat_Brand, null= True, on_delete=models.CASCADE, blank = True) model = models.ForeignKey(Cat_Model, null= True, on_delete=models.CASCADE) class Cat_Brand(models.Model): name = models.CharField(max_length=128, null=False) is_active = models.BooleanField(default=True) def __str__(self): return self.nombre class Cat_Model(models.Model): name = models.CharField(max_length=128, null=False) is_active = models.BooleanField(default=True) def __str__(self): return self.nombre forms.py class ComputerForm(ModelForm): class Meta: model = Computer fields =['serialNo', 'description', 'brand', 'model'] views.py def add_computer(request): form =ComputerForm() if request.method == "POST": form = ComputerForm(request.POST) if form_bien.is_valid(): form.save() return redirect("home") return render(request, '/add_computer.html', {'form':form}) The html template: <form method="POST" id="add_form" action="{% url 'add_computer' %}">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Add"> </form> Thanks!