Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django send data to Database: NOT NULL constraint failed: sms_post.author_id
I am new to django, I migrated my models, the database is working fine, i can see the data that I added by the manage.py shell. But I cant add Data from my webApp. When I wrote text on the fields and press the submit button it gave me this error NOT NULL constraint failed: sms_post.author_id Thanks for helping.. models.py files from django.db import models from django.contrib.auth.models import User THE_GENDER = [ ("Monsieur", "Monsieur"), ("Madame", "Madame") ] class Post(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) gender = models.CharField(max_length=8, choices=THE_GENDER) number = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name forms.py files from django import forms from .models import Post from crispy_forms.helper import FormHelper class post_form(forms.ModelForm): def __init__(self, *args, **kwargs): super(post_form, self).__init__(*args, **kwargs) self.helper = FormHelper(self) class Meta: model = Post fields = ["name", "email", "gender", "number"] views.py files from django.shortcuts import render from django.http import HttpResponse from .forms import post_form from django.contrib.auth.decorators import login_required @login_required def home(request): form = post_form(request.POST or None) if form.is_valid(): form.save() context = { "form": form } return render(request, "sms/home.html", context) -
why nginX server error (500) for django application?
this is the my settings.py file 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 used in production secret! SECRET_KEY = 't8%5^$plkjtbt6bm3zngoh*5-8(e#xb_sw)9kd&!_=67)#49mk' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app1.apps.App1Config', ] 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', ] ROOT_URLCONF = 'main_jntu.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'main_jntu.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') this is my gunicorn.conf 2020-02-12 16:59:53 +0000] … -
How to authenticate multiple users while login and register user in django
I am trying to build multi vendor e-commerce using django rest-framework. I stuck at how to authenticate multi-users like i have customers and sellers . i have successfully created API's for sellers but i am unable to give roles to uses. (Basically we are building mobile app and web) my models are: from django.db import models from django.contrib.auth.models import User from django.db import models # Create your models here. class SellerProfile(models.Model): user = models.OneToOneField( User, blank=True, null=True, on_delete=models.SET_DEFAULT, default=None) mobileNo = models.CharField(max_length=40, default=None) cnic = models.CharField(max_length=30, default=None) city = models.CharField(max_length=30, default=None) address = models.CharField(max_length=30, default=None) state = models.CharField(max_length=30, default=None) shop_name = models.CharField(max_length=30, default=None) def __str__(self): return self.user.username class ClientProfile(models.Model): user = models.OneToOneField(User, models.SET_DEFAULT, default=None) def __str__(self): return self.user.username and my serializers : from profiles.models import SellerProfile, ClientProfile from rest_framework import serializers, status # from models import * from django.contrib.auth.models import User from django.contrib.auth.hashers import make_password class UserSerializer(serializers.ModelSerializer): password = serializers.CharField( write_only=True, required=True, help_text='password', style={'input_type': 'password', 'placeholder': 'Password'} ) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password') def create(self, validated_data): user = super().create(validated_data) user.set_password(validated_data['password']) user.save() return user # def __str__(self): # return self.user class ClientSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = ClientProfile fields = ['user'] def … -
Access denied to S3 with CORS for Django on Heroku
I am serving the static files of my Django App (deployed to Heroku) via an S3 bucket. Pushing the files to S3 through the Heroku build works fine, the files end up in the bucket as expected. To access the files, I set "Block Public Access" to off and set the CORS configuration as follows: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>http://{{my app}}.herokuapp.com</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> However, I keep running into 403 Errors when checking the request in via the Chrome dev tools in my app. According to the request (see below), it does seem like there is no Origin header present in my request. Is that what's causing the error? I assumed the Origin header would be send automatically, but how do I set it manually? Also, I already tried setting AllowedOrigin to *, but no success either. The denied request's header: Accept: text/css,*/*;q=0.1 Accept-Encoding: gzip, deflate, br Accept-Language: de-DE,de;q=0.9,en-DE;q=0.8,en;q=0.7,en-US;q=0.6 Cache-Control: no-cache Connection: keep-alive DNT: 1 Host: magellan-static.s3.amazonaws.com Pragma: no-cache Referer: http://{{my app}}.herokuapp.com/ Sec-Fetch-Mode: no-cors Sec-Fetch-Site: cross-site User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36 The only way access works is setting the following Bucket policy: { "Version": "2012-10-17", "Statement": [ { … -
Dynamically generating Modal Forms
I have a list of objects in a view that display basic details. For each object, there is a button to create a model. That model has a foreignkey field that should be assigned to the associated object in the list, which requires prepopulating that (hidden) form field. objectList.html <div class="modal fade" tabindex="-1" role="dialog" id="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"> </div> </div> </div> {% for profile in object_list %} {{ profile.name}} {{ profile.description }} <button type="button" class="btn btn-primary" id="create-request">Send a request to {{ profile.name }}</button> {% endfor %} <script src="{% static 'js/jquery.bootstrap.modal.forms.js' %}"></script> <script type="text/javascript"> $(document).ready(function() { $("#create-request").modalForm({ formURL: "{% url 'create_servicerequest' %}" }); }); </script> My modal form <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Send Service Request</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% for field in form %} <div class="form-group{% if field.errors %} invalid{% endif %}"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> {{ field }} {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> {% endfor %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="submit-btn btn btn-primary">Send</button> </div> </form> views.py from bootstrap_modal_forms.generic import BSModalCreateView class ServiceRequestCreate(BSModalCreateView): template_name = 'objectList.html' form_class = ServiceRequestForm … -
django tables2 display sort arrows on header
I'm using django tables2, and I think it would be useful to have up and down arrows on header columns to indicate the current sorting order, especially when the default sort is on a column other than the first. Tried playing with CSS but no luck, any suggestions or examples on how to do this? -
How to add a dynamic content in PHP or Django?
I'm working on content uploading stuff with Django, and I was unsure how to add a dynamic row just like ACF in Wordpress, and how to store them in MYSQL database table. This is exactly what I want to do. As user wants to add more body, they can click add row button, and it will generate another feature body block to let user add more contents. I could have just done it with one single WYSIWYG editor, but I just want all the contents to have same format for consistency, so I thought it would be better way to have a fixed format contents. Also, how would I store those data into a table? As user put more contents, it will have multiple heading, images and texts. Do I just store all of them in one column ? Any help would be much appreciated. -
How do I prevent django from erroring out when a field doesn't exist in the schema?
I want to be able to mark a field as unused and therefore prevent django from erroring out when the corresponding column in the database schema doesn't exist. I want to do this because there is no reason why deploying unused code should crash a site. Something like class SomeObject(Model): some_field = models.CharField(unused=True) SomeObject.objects.all()[0].id # this line should not fail Right now it gives django.db.utils:OperationalError: (1054, "Unknown column 'someobject.some_field' in 'field list'") -
List with checked checkboxes in Django
So, i want to get the checked checkboxes items ids as a list and show them on another page. But when i get to that specific page i get the value 'None' instead of the list of ids. What could go wrong? I tried some different versions from another questions already posted on the site, but the result was the same. Here is the code: models.py: from django.db import models class afirmatii(models.Model): text = models.CharField(max_length = 250) def __str__(self): return self.text views.py: def exam(request): if request.method == 'POST': checks = request.POST.get('selected[]') request.session['checks2'] = checks context = { 'title' : 'Title1', 'aff': afirmatii.objects.order_by('id') } return render(request, 'pages/exam.html', context) def result(request): checks = request.session.get('checks2') context = { 'title' : 'Title2', 'checks': checks } return render(request, 'pages/result.html', context) exam.html: {% extends "./base.html" %} {% block content %} <div class="text-break"> <form action="{% url 'result' %}" method="POST"> {% csrf_token %} {% for q in aff %} <div class="border mb-3 rounded-sm bg-light p-2"> <div class="custom-control custom-checkbox checkbox-info"> <input type="checkbox" class="custom-control-input" id="{{ q.id }}" name = "selected[]"> <label class="custom-control-label" for="{{ q.id }}" name = 'selected[]'> {{ q.text }} </label> </div> </div> {% endfor %} <button type="submit" class="btn btn-md btn-outline-info">Next</button> </form> </div> {% endblock content %} result.html: {% … -
update existing model in DB
Hi every one I have an issue I want to update a specific model in the db like I want the user to change their phone number and picture...etc specific one not all the model and I am unable to do that in views.py, below is my code, can help pls? models.py # Create your models here. PHONE_REGEX = '^[0-9]*$' class Profile(AbstractUser): phone_number = models.CharField( max_length=14, help_text='Optional', blank=True, validators=[ RegexValidator( regex=PHONE_REGEX, message= 'phone number must be only digit and from 10 to 14 digits only', code='invalid-phone number'), MinLengthValidator(10) ]) picture = models.ImageField(upload_to='upload/', blank=True, default=False) email = models.EmailField(max_length=254, unique=True, help_text='Required, pls enter a valid Email') forms.py class Change_pic_form(forms.ModelForm): class Meta: model = Profile fields = ('picture', ) -
Django name 'user' is not defined, when creating the first data in shell
I created a database And when i want to write the first data in the manage.py shell it not working. Thanks for helping I writted those 3 commands to migrate manage.py makemigrations manage.py sqlmigrate sms 0001 manage.py migrate All worked fine, after I made those commands to create the first 'data' in the database manage.py shell from sms.models import Post from django.contrib.auth.models import User post_1 = Post(name="testname", email="testemail", gender="Monsieur", number="23233", author=user) And it gave me this error: ValueError: Cannot assign "<class 'django.contrib.auth.models.User'>": "Post.author" must be a "User" instance. models.py files from django.db import models from django.contrib.auth.models import User THE_GENDER = [ ("Monsieur", "Monsieur"), ("Madame", "Madame") ] class Post(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) gender = models.CharField(max_length=8, choices=THE_GENDER) number = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name forms.py files from django import forms from .models import Post from crispy_forms.helper import FormHelper class post_form(forms.ModelForm): def __init__(self, *args, **kwargs): super(post_form, self).__init__(*args, **kwargs) self.helper = FormHelper(self) class Meta: model = Post fields = ["name", "email", "gender", "number"] views.py files from django.shortcuts import render from django.http import HttpResponse from .forms import post_form def home(request): form = post_form(request.POST or None) if form.is_valid(): form.save() context = { "form": form } return render(request, "sms/home.html", context) -
Add new elements in the "basket" in django oscar
I'm looking for a way to save products in the cart, but I didn't find much on google and there are no clear examples in the official documentation (https://django-oscar.readthedocs.io/en/2.0.4/ref/apps/basket.html). So does anyone know which libraries to import and how to save a product programmatically? I'm waiting for answers, thank you! -
django db and sqlite use different parameter style?
def getAppName(cursor, appId): cursor.execute("SELECT name FROM App WHERE id=?", (appId,)) return cursor.fetchone() I have a function getAppName, which will be called by raw sqlite cursor and django db cursor. https://docs.djangoproject.com/en/3.0/topics/db/sql/#connections-and-cursors states django db cursor requires "%s" style placeholder, while raw sqlite cursor requires ? style placeholder. How can my function be shared among django and regular applications? -
Scan Django project for all classes that inherit from Serializer
I am hoping to create a unit test that finds all the classes that inherit Serializer or ModelSerializer in my Django app, and validate properties on the Meta class. -
appengine/Django submit form using classes
I would like to create a registration from and have tried to follow the official documentation (https://cloud.google.com/appengine/docs/standard/python/getting-started/python-standard-env). Right now, all i would like to do is display the form data to another route, but i get the following error: File "/usr/lib/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__ rv = self.router.dispatch(request, response) File "/usr/lib/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher return route.handler_adapter(request, response) File "/usr/lib/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__ return handler.dispatch() File "/home/vicktree/Desktop/noah/web/noahs-app/handlers/noah_handler.py", line 329, in dispatch super(NoahSiteHandler, self).dispatch() File "/home/vicktree/Desktop/noah/web/noahs-app/handlers/noah_handler.py", line 130, in dispatch webapp2.RequestHandler.dispatch(self) File "/usr/lib/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 572, in dispatch return self.handle_exception(e, self.app.debug) File "/usr/lib/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch return method(*args, **kwargs) File "/home/vicktree/Desktop/noah/web/noahs-app/handlers/site_handlers.py", line 1071, in post user_name = self.request.form['user_name'] File "/usr/lib/google-cloud-sdk/platform/google_appengine/lib/webob-1.1.1/webob/request.py", line 1238, in __getattr__ raise AttributeError(attr) AttributeError: form My routes are the following: #Sign-in registration Route(r'/signin/registration', 'handlers.site_handlers.UserRegistration', name='registration'), #Sign-in Noah registration submit Route(r'/signin/submitted', 'handlers.site_handlers.UserRegistrationSubmit', name='registration_submit'), My Class Logic is below: class UserRegistrationSubmit(SiteHandler): template_filename = 'registration_submit.html' def post(self): user_name = self.request.form['user_name'] password = self.request.form['password'] self.render_template(values={'user_name':user_name, 'password':password}) class UserRegistration(SiteHandler): # email = request.form['email'] template_filename = 'registration.html' def get(self): self.render_template() My HTML template is below: /registration.html <div class="alpha-content grid-line"> <head> <title>Submit a form</title> <link rel="stylesheet" type="text/css" href="/static/style.css"> </head> <body> <div id="container"> <div class="pagetitle"> <h1>Submit a form</h1> </div> <div id="main"> <form method="post" action="{{ url_for('registration_submit') … -
Exclude option in select that's already choosen by user
Is it possible to exclude options that is already choosed by user and stored in a table? This is the tables from teh models.py class Fruit(models.Model): name = models.CharField(max_length=250, unique=True, blank=False, null=False) sort= models.ForeignKey('FruitSort', on_delete=models.SET_NULL, null=True, blank=False) def __str__(self): return '%s (%s)' % (self.name, self.sort.name) class UserFruit(models.Model): Comment = models.CharField(max_length=55) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) fruit = models.ForeignKey('Fruit', on_delete=models.CASCADE) class Meta: unique_together = (("user", "fruit",),) This is the forms.py that generate my form. class UserFruit(forms.ModelForm): class Meta: model = UserFruit fields = ('comment', 'fruit') def __init__(self, *args, **kwargs): super(UserFruit, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control form-style-alt' self.fields['comment'].widget.attrs['placeholder'] = 'comment' self.fields['fruit'].empty_label = 'Please, choose fruit' Now the views.py class Fruit(generic.CreateView): form_class = UserFruit template_name = 'fruit.html' def get(self, request, *args, **kwargs): form = self.form_class(instance=UserFruit.objects.filter(user=request.user).first()) fruit = UserFruit.objects.filter(user=request.user) return render(request, self.template_name, {'form': form, 'fruit': fruit}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return redirect('fruit') And finally the template. <h3>Add a juicy fruit</h3> <form method="post"> {% csrf_token %} <div class="form-group"> <div> <span class="text-danger">{{ error }}</span> </div> {{ form.fruit }} {{ form.comment }} <button class="btn" type="submit"> Save</button> </div> </form> I want to exclude, or disable, fruits that the user already have added. … -
How to create a pdf output file in a chosen directory with Hardcopy in Django?
I would like to automatically save the result in a pdf file in a chosen directory. I use the django-hardcopy module. Currently, I can display the pdf with a url. Thank you for your ideas. Here is the view: from django.conf import settings from hardcopy.views import PDFViewMixin, PNGViewMixin class pdf_hardcopy(PDFViewMixin, TemplateView): download_attachment = True template_name = 'project/pdf_hardcopy.html' def get_filename(self): return "my_file.pdf" def get_context_data(self, *args, **kwargs): context = super(pdf_hardcopy, self).get_context_data(*args, **kwargs) id = self.kwargs['pk'] dossier_media = str(settings.MEDIA_ROOT) GetDataTeam = Datas.objects.filter(id=id) context["GetDataTeam"] = GetDataTeam return context My url: path('pdf_hardcopy/<int:pk>/', views.pdf_hardcopy.as_view(), name='pdf_hardcopy'), -
Django use Different Serializer based on parameter
I have a APIView that provides my model instances. I want to use different serializers based on url parameters, beacause I want to serve different fields based on parameter. I didn't want to use if else check for all situations, so I used a function that provide serializer from serializer objects dict based on type key. Is there a good solution? Does anyone have a better suggestion? Also what are you thinking about use different endpoints instead of this method. Here is the code: urls.py from django.urls import path from .views import MySerializerTestView urlpatterns = [ path('<slug:type>', MySerializerTestView.as_view()), ] models.py from django.db import models class MyModel(models.Model): field_first = models.CharField(max_length=10) field_second = models.CharField(max_length=10) field_third = models.CharField(max_length=10) views.py from .models import MyModel from rest_framework.response import Response from rest_framework.views import APIView from .serializers import MyFirstSerializer,MySecondSerializer,MyThirdSerializer class MySerializerTestView(APIView): def get(self, request, **kwargs): my_data = MyModel.objects.all() serializer = self.get_serializer(self.kwargs['type'],my_data) return Response(serializer.data) def get_serializer(self,type,data): my_serializers = { 'first':MyFirstSerializer(data,many=True), 'second':MySecondSerializer(data,many=True), 'third':MyThirdSerializer(data,many=True), } return my_serializers[type] serializers.py from .models import MyModel from rest_framework import serializers class MyFirstSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ['field_first'] class MySecondSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ['field_second'] class MyThirdSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ['field_third'] -
Django: select template from data in settings
I am trying to understand the process whereby a Django template might be selected based on data in the settings file. So, as an example if I have: SOCIAL_AUTH_FACEBOOK_KEY = "my_fb_key" I would like the template selection in urls.py to do this: url('login/', auth_views.LoginView.as_view(template_name='choose_signup.html'), name='login') But if the FB key value is empty/null I’d like it to do this: url('login/', auth_views.LoginView.as_view(template_name='really_login.html'), name='login') I tried setting a variable in urls.py like this: if SOCIAL_AUTH_FACEBOOK_KEY == "" : mytemplatename = "really_login.html" else: mytemplatename = "choose_signup.html" … url('login/', auth_views.LoginView.as_view(template_name=mytemplatename), name='login') But this produces an error in terminal (manage.py runserver) NameError: name 'SOCIAL_AUTH_FACEBOOK_KEY' is not defined Am I just trying to do this the wrong way? -
How to change the root directory of the apache server for Django project
I'm trying to run my Django project on the server using Apache2, the server is ubuntu VPS, the project runs normally using runserver command, but I can't do it normally using apache, as it gives me this page: And of course, the default document directory for apache2 is var/www/html, but I want to use my own directory. So here are my files : the active config file <VirtualHost *:80> ServerName my_domain.com ServerAlias localhost Alias /static /path/to/my/project/static/ WSGIScriptAlias / /path/to/my/project/wsgi.py <Directory /path/to/my/project/> Order deny,allow Allow from all </Directory> DocumentRoot /path/to/my/project/ ErrorLog /path/to/my/project/error.log CustomLog /path/to/my/project/custom.log combined </VirtualHost> apache2.conf <Directory /> Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Require all granted </Directory> <Directory /usr/share> AllowOverride None Require all granted </Directory> <Directory /path/to/my/project/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> What's wrong with those files ? -
Django: can't inspectdb database tables to file
I have a database with around 25 tables and I would like to automatically generate the model file for my python project. For developing the project I am using PyCharm with a MariaDB as RDMS. The basic settings for the database have been done. In the next step I switch to the manage.py console to run the first command: inspectdb This is working fine. Each table will be listed in the output of the console window. Now I want to write the output in a file. Therefore I use the following command: inspectdb > models.py This ends up in an Error: Unable to inspect table '>' # The error was: (1146, "Table 'mydatabase.>' doesn't exist") # Unable to inspect table 'models.py' # The error was: (1146, "Table 'mydatabase.models.py' doesn't exist") Process finished with exit code 0 The command is according to the documentation 'python manage.py inspectdb > model.py'. But in this case the '>' symbol will be intepreted as table, or a tablename has to be given. In a second case, I try to export only one table: inspectdb users > models.py this ends up with the following output: class Users(models.Model): name = models.CharField(max_length=400) username = models.CharField(max_length=150) email = models.CharField(max_length=100) … -
How to insert Rich text box data using ModelForm in Djnago?
I've been trying to insert data into a database using a rich text field in djnago using django rich text field as it stand ive been able to have the field working on my form no problem but when i try and link it to my model using ModelFrom with all the other coloums i have no luck. This from is on a panel completely seprate to the admin panel in which it works perfectly fine. my model is set up to accept the form. class Vulnerability(models.Model): title = models.CharField(max_length=200, null=True) CVSS = models.DecimalField(max_digits=2, decimal_places=1, null=True) summary = RichTextField(blank=True) remediation = RichTextField(blank=True) impact = RichTextField(blank=True) References = RichTextField(blank=True) CVE = models.CharField(max_length=30, null=True) Software = models.CharField(max_length=100, null=True) method = RichTextField(blank=True) Tags = models.CharField(null=True, max_length=200) my forms.py is set up for that field to use the correct widget (this could be where the issue lies) i'm not entirely sure how to set up the rich text field in this fashion and i cannot find it in the documentation. class vulnform(ModelForm): class Meta: model = Vulnerability fields = ['Tags', 'CVSS', 'CVE', 'Software', 'title','summary'] widgets = { 'title': TextInput(attrs={'class': 'form-control'}), 'CVE': TextInput(attrs={'class': 'form-control'}), 'Software': TextInput(attrs={'class': 'form-control'}), 'Tags': TextInput(attrs={'class': 'form-control'}), 'CVSS': NumberInput(attrs={'class': 'form-control','max':10,'min':0}), 'summary' : … -
SSO authentification using Apache, DJANGO, REST and React
I'm trying to build a SSO authentication from Active Directory using DJANGO, REST and React but I don't find any solution over the internet. Right now I succeeded to implement SSO authentication only in a basic PHP project. For do that I installed on Apache sspi_module and added to Apache httpd.conf this lines: <Location> AuthName "LAN" AuthType SSPI SSPIDomain "exemple" SSPIAuth on require valid-user </Location> It is possible to make SSO using this technologies (DJANGO, REST, REACT) together? -
How to use django logging handlers behind gunicorn?
I'm running a django app behind gunicorn and nginx and the django app is configured with a logger that uses several different handlers. I was surprised to find out that when I run the gunicorn (instead of runserver). The logging handlers I configured in settings.py don't work. Am I missing something here or is this supposed to happen? If so, then how can I force gunicorn to use the handlers and logging config I have in the django app? -
Filtering by title inside the category(many-to-many)
I have a page where I can choose the category of my item, then it takes me to a different template and display all the items with that category. What needs to be made, so I can filter these results further, by lets say a title? views.py thats the function that filters my items by category and takes my to search.html template def category_view(request, category_id): item_list = Item.objects.filter(category__pk=category_id) return render(request, "search.html", {'item_list': item_list}) search.html <div class="offset-md-1 col-md-2"> <h2>Content Filter</h2> <br> <form method="GET" action="."> <div class="form-row"> <div class="form-group col-12"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="q" placeholder="Brand.."> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> </div> Below that there's just a list that displays the results views.py I tried doing it this way, but I get an error "Page not found (404)" "The current path, bike-category/, didn't match any of these. " def SearchView(request): item_list = Item.objects.all() query = request.GET.get('q') if query: item_list = Item.objects.filter(title__icontains=query) context = { 'item_list': item_list } return render(request, "search.html", context) urls: urlpatterns = [ path('bikes/', BikeView, name='bikes'), path('', HomeView, name='home'), path('search/', SearchView, name='search'), path('bike-category/<category_id>', category_view, name='category') ]