Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Forbidden (CSRF token missing or incorrect.): /accounts/login while making post request through postman
I am trying to login to my user model in django using postman views.py from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from useraccount.serializer import UserSerializer from useraccount.models import User class UserViewSet(ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() urls.py from django.urls import path,include from rest_framework.routers import DefaultRouter from useraccount.views import UserCreateViewSet from django.contrib.auth.views import LoginView user_router = DefaultRouter(trailing_slash=False) user_router.register('user',UserCreateViewSet) user_router.register('signup',UserCreateViewSet) urlpatterns = [ path('',include(user_router.urls)), path('login',LoginView.as_view()), ] when trying using postman providing the username and password i am getting Forbidden (CSRF token missing or incorrect.): /accounts/login i am using default auth.view to login like LoginView i am not using any kind of authentication method like basicauth,tokenauth or session auth while working with django rest framework please tell me if while dealing with rest framework i have to use one of the above three method of auth or if not necessary then how to deal with this problem in postman -
Creating a List of forgein keys in django model
I'm trying to make 2 models in Django that are interconnected one called pathways and one called courses. I wrote a Json file, that I was hoping to use load data on, where the tables are set up like this courses: "code": 1964, #primary key "name": "Documentary in the 21st Century", "category": "IHSS", and pathways: "id": 1, #primary key "name": "Arts", "inquiries": [ 1080, 1300, 1170, 1700 ] As you can see I want the model pathways to contain a list of foreign keys pointing to several different courses, but I'm new to Django and can't find anything helpful online. -
Filtering many-to-many in materialized view in Django?
I'm building a Django application which requires creating and filtering a materialized view. I'm having trouble understanding what's the best way to create the materialized view. As an example, I have two tables related with a many-to-many relationship. class Company(models.Model): name = models.CharField(max_length=255) ... class Person(models.Model): name = models.CharField(max_length=255) age = models.PositiveIntegerField() ... places_worked_at = models.ManyToManyField(Company) I'm going to be grouping by persons and would like to implement a materialized view following something like the model below. However, I'm stuck and unsure about how to not only create the materialized view, but how I would store the multiple company ids and names that a person might have in the model. class PersonCompanyMV(models.Model): person_id = models.IntegerField() person_name = models.CharField(max_length=255) person_age = models.PositiveIntegerField() company_ids = ??? company_names = ??? class Meta: managed = False db_table = 'person_company_mv' I'd imagine there's a simple way to implement something like this that allows for easily filtering like PersonCompanyMV.objects.filter(company_id=1)? Any help or links to documentation would be appreciated. -
Django - I don't manage to pass a dataframe or dictionary from views.py to template home.html
Struggling already 5 days with this, appreciate all the help on this . I want to learn how to pull data from database (sqllite) , do some python stuff and pass the result in a dataframe or dictionary from views.py to html template. I'm building django ecommerce webshop with bootstrap template (starting from djecommerce project) . The model 'Item' is a table of products with item.price, item.description, item.etc... in the 'home.html' products cards are constructed with a for loop '{% for item in object_list%} -> card. In this problem , users should search for a product (example 'bike helmet') , after which we pull all the items (Item.objects.all()) , do some python stuff and it should return a dataframe/dictionary/whatever so that I can loop it through in the template. Currently I transform the primary keys back into a list and then do Item.objects.filter(pk=[list of id's]) but I really want to learn to do it properly. I tried so many variations on whatever I have found on the internet so forgive me the current solution below. Thanks already for the feedback and support. I'm sure I'm missing something 'easy' and not understanding it right.. VIEWS.PY ''' class HomeView(ListView): model = Item … -
I just need to redirect vote to details,every things work fine except the last line of vote
strong text[enter image description here][1] [1]: https://i.stack.imgur.com/z1OAJ.jpgemphasized text -
Updating extending user form
I have a CustomUserModel within my models.py class UserManager(BaseUserManager): def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have email address") user_obj = self.model(email = self.normalize_email(email)) if not password: raise ValueError("Users must have a password") user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,password=None): user = self.create_user(email, password=password,is_staff=True) return user def create_superuser(self, email, password=None): user = self.create_user(email, password=password, is_staff=True, is_admin=True) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255,unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' # email and password are required by default REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active class Customer(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) TITLE = ( ('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Miss', 'Miss'), ('Ms', 'Ms'), ('Dr', 'Dr'), ('Sir', 'Sir'), ('Madam', 'Madam'), ) user = models.OneToOneField(User,on_delete=models.CASCADE) title = models.CharField(max_length=200, null=True, choices=TITLE) first_name = models.CharField(max_length=200, null=True) middle_name = models.CharField(max_length=200, blank=True,default='') last_name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) country = CountryField() birth_year = models.CharField(max_length=4, null=True) gender … -
How to create folder by coding in django view on AWS?
I'm very new with AWS and I have a django application which is been deployed to AWS. I have to create a folder for each user and save their machine learning models in these folders. When i try to get home path and create the folders in there, i get an error such as [Errno 13] Permission denied: '/home/wsgi'. How can i fix this? -
Django 3 error: No installed apps with label 'app_name'
I am currently learning how to use Django 3 (and Python 3.8) and I am following a tutorial to create a simple blog. I am getting a good grasp of the basic concepts so far but I am stuck at creating a migrations file. When I enter the python manage.py makemigrations blog command into Windows Powershell, I get the error message: No installed app with label 'blog'. I have searched high and lo for an answer but I am still scratching my head. I am wondering if you lovely people would be able to offer any advice on the matter. Here's 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__))) print("BASE_DIR = ", BASE_DIR) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # 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', 'blog', ] 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 = 'django_project.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', … -
what should i do if my css is not working while i am using django framework?
in main html document: {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{{STATIC_URL}}sgbit/style.css" media="screen" > <title>sgbit</title> </head> <body> {% block content %}{% endblock %} </body> </html> in settings.py file: STATIC_URL = '/static/' STATIC os.path.join(BASE_DIR , 'static'), ] im trying basic background color change to confirm css is working on my document, but nothing i try seems to work. ive watched a lot of youtube videos and also read the documents several times. can you please tell me the issues in my code. thank you. -
Dependent/Chained Drop down List is not working in modal
I am trying to use dependant/chained dropdown list in Django with the help of ajax (https://cutt.ly/MyVQE74) like if i select a company then only then that company department will show up in the modal. it worked in main page for the search function but not working in the modal part while posting data. model_part class Item(models.Model): item_name = models.CharField(max_length=255, blank =True) description = models.CharField(max_length=255, blank=True, null=True) company = models.ForeignKey(Company, on_delete = models.CASCADE) department = models.ForeignKey(Department, on_delete = models.CASCADE) employee = models.ForeignKey(Employee, on_delete = models.CASCADE) view_part def save_item_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True items = Item.objects.all() data['html_item_list'] = render_to_string('item/includes/partial_item_list.html', { 'items': items }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string( template_name, context, request=request) return JsonResponse(data) def item_create(request): if request.method == 'POST': form = ItemForm(request.POST) else: form = ItemForm() return save_item_form(request, form, 'item/includes/partial_item_create.html') def load_department(request): company_id = request.GET.get('company') departments= Department.objects.filter(company_id=company_id).order_by('name') context={'departments':departments} return render(request,'item/department_drop_down.html',context) def load_employees(request): department_id =request.GET.get('department') employees = Employee.objects.filter(department_id=department_id).order_by('name') context={'employees':employees} return render(request,'item/employee_drop_down.html',context) Templates view (using modal): name: partial_create_form.html <form method="post" action="{% url 'item_create' %}" class="js-item-create-form" id="itemForm" data-departments-url="{% url 'ajax_load_departments'%}" data-employees-url="{% url 'ajax_load_employees'%}" > {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 … -
static file locate issue on cpanel
my project is working fine on local but on live server(godaddy) its not getting static folder. urls are just admin/ [name='homepage'] login/ [name='login'] ^media\/(?P<path>.*)$ url for static not even located here . my settings.py static settings are STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] which are working on local perfectly . and location for static folder is here in image , just a static folder placed. -
Django project celery and django-filter causing errors
I had a working django project, but I started getting errors with celery after I added django-filter to my requirements file. I'm using python 3.7 and here's the list of installed packages w/ versions: Django-3.0.7 amqp-2.6.0 asgiref-3.2.7 billiard-3.6.3.0 celery-4.4.4 certifi-2020.4.5.1 chardet-3.0.4 django-bootstrap3-12.1.0 django-celery-results-1.2.1 django-filter-2.2.0 djangorestframework-3.11.0 idna-2.9 importlib-metadata-1.6.0 kombu-4.6.10 ovirt-engine-sdk-python-4.4.3 psycopg2-2.8.5 pycurl-7.43.0.5 python-gitlab-2.2.0 pytz-2020.1 redis-3.5.3 requests-2.23.0 six-1.15.0 sqlparse-0.3.1 urllib3-1.25.9 vine-1.3.0 zipp-3.1.0 I decided to remove my code that uses filtering and just left the pip install for the package, and I still saw the same errors. Below is a pertinent snippet, but I can add the whole trace if necessary. celery-beat_1 | [2020-06-04 18:11:33,145: CRITICAL/MainProcess] beat raised exception <class 'ModuleNotFoundError'>: ModuleNotFoundError("No module named 'future'") celery-beat_1 | Traceback (most recent call last): celery-beat_1 | File "/usr/local/lib/python3.7/site-packages/kombu/utils/objects.py", line 42, in __get__ celery-beat_1 | return obj.__dict__[self.__name__] celery-beat_1 | KeyError: 'scheduler' celery-beat_1 | celery-beat_1 | During handling of the above exception, another exception occurred: celery-beat_1 | celery-beat_1 | Traceback (most recent call last): celery-beat_1 | File "/usr/local/lib/python3.7/site-packages/kombu/utils/objects.py", line 42, in __get__ celery-beat_1 | return obj.__dict__[self.__name__] celery-beat_1 | KeyError: 'backend' . . . celery-beat_1 | [2020-06-04 18:11:33,161: WARNING/MainProcess] File "/usr/local/lib/python3.7/site-packages/celery/backends/base.py", line 10, in <module> celery-beat_1 | [2020-06-04 18:11:33,161: WARNING/MainProcess] from future.utils import raise_with_traceback celery-beat_1 | [2020-06-04 … -
How do I load YAML seed data for a many-to-many field?
I'm using Django 2.2 and Python 3.7. I have the below model. Notice the "ManyToMany" addresses field ... class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() In my seed file, I have sturctured the data like below. The "1" in the "addresses" column, is the primary key of an address that already exists in the database (MySql 8) ... - model: directory.coop pk: 1 fields: name: "1871" types: - ['Coworking Space'] addresses: - [ 1 ] enabled: True phone: email: web_site: "http://www.1871.com/" However, when I try and load the seed data, it dies with an "["'[1]' value must be an integer."]: (directory.coop:pk=1) field_value was '[1]'" error. Below is teh complete trace. 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 "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/davea/Documents/workspace/chicommons/maps/web/directory/management/commands/docker_init_db_data.py", line 13, in handle call_command('loaddata', 'directory/fixtures/seed_data.yaml') File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 148, in call_command return command.execute(*args, **defaults) File … -
How to apply different css styles to two different form elements on the same page?
I am trying to create a web page with a search bar that has it's own styling at the top and then a form later on in the page using django and crispy forms. Currently, the styling for my search bar applies to the styling for my form, and I don't want that. I would like to use bootstrap crispy forms to style the form and my own custom css to style the search bar. (The search bar is coded as a form with input.) I have tried reordering the links in the head of my html, bootstrap first, search bar second, and the other way around, and it didn't affect anything rather than screw up the positioning of my search bar. I have tried wrapping both forms in divs with seperate ids and seperate classes, and it also didn't work. I have tried giving an id to my custom search bar form. I am aware of CSS Specificity. I'm not sure how to make it happen so that I can completely separate the two. Help is appreciated. relevant html: <head> ... <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'assets/css/main.css' %}" /> … -
POST request to Django Model Formset with Vuejs front-end
I am using Django to build a back-end of my project and Vuejs to build the front-end. I have defined my models in Django and have used Django forms to save data to the models. For a single form, I just pass a JSON object in the body of the POST request. This works perfectly fine. But now I need to save multiple records at the same time. I found that Django model formsets can do this. However, I am not able to figure out how to format the POST request. The Django documentation assumes that I'll be using Django templates (which is quite annoying), and therefore says nothing about the format of the request itself. The application is an API documentation tool and I need to allow the user to define the params of the API. As of now, I have the following: from django.forms import modelformset_factory from docs.models import ApiParams ParamsFormSet = modelformset_factory(ApiParams, exclude=('param_id',)) def create_params(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) formset = ParamsFormSet(body) instaces = formset.save() return HttpResponse(instances) I called this API with the following data: [ { "api": 2, "param_name": "param1", "param_type": "string", "param_required": true, "param_sample": "param" }, { "api": 2, "param_name": "param2", "param_type": "numeric", … -
Fieldsets don't do anything in admin django
I'm learning Django and found that we can use fieldsets to customise the way admin creation form looks like. Here is the code I'am using: class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ('email', 'age', 'is_staff', 'is_active',) list_filter = ('email', 'age', 'is_staff', 'is_active',) fieldsets = ( ('Advanced options', { 'classes': ('wide',), 'fields': ('email', 'age', 'is_staff', 'is_active',), }), ) admin.site.register(CustomUser, CustomUserAdmin) Here is the result: As you can see this "fieldsets" does nothing for this creation page. And if I completely remove this "fieldsets" nothing will change. What I did wrong here? I want my fieldsets work. Thank you! -
Best way to deploy small Django local website
I have used lock down in UK to develop a website as a front end to my CCTV and home automation systems. It uses Django, Celery (beat and workers), ffmpeg, channels and Redis. I have built it in a virtual environment on a 4g Pi4. I need to host locally as the Pi controls hardware directly. It was hard work but it all works well “in development”. Given Daphne can act as a server, I decided that I would simply use my development code directly as a production version by daemonising with systemd. I thought I had done all the hard work developing the code. I now find that deploying to production causes even more headaches. I have paused as I am no longer confident I am going in the right direction. I just want a simple set up that works on a Pi4. I want to reboot reliably. I want to be able to easily see which services have crashed, if any. I would like to be able to easily examine logs. I would like to be able to easily update Django code and update the production. What are your recommendations for locally hosted small but reasonably complex production … -
Django Ajax request returns no HttpResponse
Hi I am currently trying to improve my django project by adding ajax functionality to avoid the page from being reloaded everytime I like or comment a post of my blog. First I have added the functionality to give likes and it worked very well! However, after I have added the similar functionality for my comments, I am getting the following error for both (like and commenting function): When I like a post: The view feed.views.post_like didn't return an HttpResponse object. It returned None instead. When I create a comment: The view feed.views.comment_create didn't return an HttpResponse object. It returned None instead. I have added my jquery code in my base.html file, the upper part is for likes, the lower for creating comments: <script type="text/JavaScript"> // JQuery Event Handler $(document).ready(function(event) { $(document).on('click', '#like', function(event){ event.preventDefault(); // Primary Key from form is the value of the button! var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url 'post-likes' %}', data: {'post_id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: 'json', success: function(response){ $('#like-section').html(response['form']); console.log($('#like-section').html(response['form'])); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); $(document).on('submit', '.comment-form', function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), dataType: 'json', success: function(response) { $('#comment-section').html(response['form']); console.log($('#comment-section').html(response['form'])); }, … -
Serve static folder in Django
from django.urls import path from django.views.generic import TemplateView from server import api urlpatterns = [ path('admin/', admin.site.urls), path('api/', api.site.urls), path('index.html', TemplateView.as_view(template_name='index.html')) ] So I am currently serving path('index.html', TemplateView.as_view(template_name='index.html')). I instead would like to serve all html files in my template folder without having to specify each one. I have my react frontend being output to my template folder. I would like to serve that entire folder rather than having to explicitly declare each path. So for example my folder: templates/ index.html second.html auth/ login.html register.html I want all those to be served matching the file/folder name so: index.html = /index.html second.html = /second.html login.html = /auth/login.html register.html /auth/register.html How am I able to just serve the entire folder without explicitly declaring each file and that path? -
Django , handling file field( mp3 files)
My Django Rest Framework app have mp3 file field as mentioned in the below model. I upload mp3 files from admin side. When I send GET request for mp3 files in frontend , it downloads in browser without issues. but shows some error in terminal. AttributeError: 'NoneType' object has no attribute 'split' Should I use any parser to retrieve audio files from server ? MODELS.PY from django.db import models class Music(models.Model): ... track = models.FileField(upload_to='tracks') -
Cannot resolve keyword 'is_active' into field (Django custom user model)
I am using a custom user model: class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", unique=True, max_length=255) first_name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) active = models.BooleanField(default=True) #can they login? staff = models.BooleanField(default=False) #staff user non superuser admin = models.BooleanField(default=False) #superuser date_joined = models.DateTimeField(auto_now_add=True) And a view for giving users the possibility of resetting the password: urls: from django.contrib.auth import views as auth_views [...] path('password_forgotten/', auth_views.PasswordResetView.as_view(template_name='registration/password_forgotten_form.html'), name='password_forgotten_form'), Template <form method="POST" class="form-signin">{% csrf_token %} <h1 class="h3 mb-3 font-weight-normal">Reset password</h1> <input name="email" class="form-control" placeholder="Email address" type="email" id="id_email" required="true"> <button class="btn btn-lg btn-primary btn-block" type="submit">Send reset email</button> </form> With Django 3, I get Cannot resolve keyword 'is_active' into field (Django custom user model) when I hit submit. The curious thing is that if I add a is_active field to my user model it gets ignored by my migrations. Adding a slightly different field name, like is_activeT, works. Is is_active a protected field, or something like that? How can I solve my issue? A property won't do it. I'm aware of this: https://code.djangoproject.com/ticket/22192 . But then, Django just ignores if I add a is_active field, even if I add the AddField function directly in my migrations file; it'll be silently deleted in the next … -
Async calls not working from sync code in Django channels
I am working on an app that uses Django channels. My client is a flutter mobile application. So it needs to send token along the request. I am using restframework_jwt for authentication. In the consumers.py, I am trying to decode the token and get the user out of it. I tried two different ways but each shows a different behavior. First I tried this way: token_header = dict(self.scope['headers'])[b'authorization'].decode().split() token = token_header[1] result = jwt.decode(token, settings.SECRET_KEY) username = result['username'] user = self.get_obj(username) whereas get_obj() is defined below as: @database_sync_to_async def get_obj(self, user): return User.objects.channel_get(user) now the issue is that when I print user, returned from get_obj(), it returns this : "<coroutine object SyncToAsync.__call__ at 0x0000015447FE21C8>" where is it not returning user instead and what am I missing? The second way I tried was : token_header = dict(self.scope['headers'])[b'authorization'].decode().split() payload = {'token': token_header[1]} valid_data = await sync_to_async(VerifyJSONWebTokenSerializer().validate)(payload) and it should return : {'token': <token>, 'user': <user_obj>} but instead it returns that same payload. Can anyone tell me where am I going wrong? -
how do I fix (key error) when registration?
I try to create a user registration when a user is signing up he has to moves to the last section which called "complete register". I thought that mission is done by session I need to know if using a session is true in this case or not. if using a session is good how can I save the data from the first form because I get every time the key error? I'm sure the save method in complete_register function is wrong but I have no any idea how can I continue to complete this mission. views.py from django.shortcuts import render, redirect from .forms import RegistrationForm, CompleteRegisterForm from importlib import import_module from django.conf import settings def register(request): if request.method == "POST": user_form = RegistrationForm(request.POST) if user_form.is_valid(): user_form.save(commit=False) SessionStore = import_module(settings.SESSION_ENGINE).SessionStore user_session = SessionStore() user_session['continue_form'] = user_form.clean() # user_session.create() return redirect("account:complete-register") else: error_msg = "something went wrong" return render(request, "account/registration.html", {"user_form": user_form, "error_msg": error_msg}) else: user_form = RegistrationForm() return render(request, "account/registration.html", {"user_form": user_form}) def complete_register(request): if request.method == "POST": # get the rest of data by session user_session = request.session complete_form = CompleteRegisterForm(request.POST) if complete_form.is_valid(): form = user_session['continue_form'].save() complete_form.save() return redirect("music:albums") else: error_msg = "something went wrong" context = {"complete": complete_form, … -
css is not connecting to html in python django
css is not connecting to html in python django. here is my templates/index.html file content <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}BareTalk{% endblock %}</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> </head> <body> <header> <input type="text" id="search-question" placeholder=" Search"> <img src="search.png" id="search-img"> </header> <br> <br> {% for q in question_list %} <div id="question-log"> <p>Rating: {{ q.rating }}</p> <p id="title">{{ q.title }}</p> <p>{{ body }}</p> </div> {% endfor %} <script src="script.js"></script> </body> </html> and this is my templates tree templates (folder) f (folder) index.html style.css the html is working, but css in not :( -
django arrayfield saving a array item containing comma
I have a django model that has a postgres array field ArrayField(blank=True, default=list, base_field=CICharField(max_length=200, blank=True)) There is also a corresponding admin page for this model where I can update field this in the regular case, but If for example I want to save the field as ['foo,bar', 'baz'] this is not possible since django seems to be splitting always by comma. I tried saving with "foo,bar",baz thinking csv rules but that didn't work out either. Is there any workaround to achive this in django admin ?