Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django-multiselect field in postman?
I am using pip module MultiSelectField Here is my model SALES_CHANNEL = [ ('retailer', 'Retailer'), ('wholesaler', 'Wholesaler'), ('consumer', 'Consumer'), ('distributor', 'Distributor'), ('online', 'Online') ] class ProductModel(basemodel.BaseModel): name = models.CharField(max_length=200) mrp = models.DecimalField( max_digits=10, decimal_places=2, null=True, blank=True ) selling_price = models.DecimalField( max_digits=10, decimal_places=2, null=True, blank=True ) upc = models.CharField(max_length=30, null=True, blank=True) dimensions = models.CharField(max_length=200, null=True, blank=True) weight = models.CharField(max_length=200, null=True, blank=True) sku = models.CharField(max_length=200, unique=True) product_type = models.CharField( max_length=30, choices=PRODUCT_TYPE, default='goods' ) sales_channel = MultiSelectField( choices=SALES_CHANNEL, null=True, blank=True ) While creating a product with postman, my request body is: { "name": "first unit", "sku": "first sales chann", "sales_channel":["retailer", "wholesaler"] } But on serializer.is_valid(), I get this error: "sales_channel": [ "\"['retailer', 'wholesaler']\" is not a valid choice." ], How can I post data on postman for multiselectfield? -
Django ArrayField Query issue
My model structure is as below - class DataModel(models.Model): gid = models.AutoField(primary_key=True) last_updated_time = models.DateTimeField(auto_now=True) imp_id = models.CharField(max_length=254, blank=True, null=True) members = ArrayField(models.TextField(null=True, blank=True)) The member data is stored in below format - "{"{'Memberno': '1', 'first_name': 'John', 'last_name': 'Dow', 'education_type': '','FamilyMembers': []}"}" How do I filter for first_name similar to 'John'? My filter query that I tried was - models.DataModel.objects.exclude(members__icontains='{}') But this was for exclude. Can somebody please help me filter for first_name? -
Can't login to django with cusom user but for super it work fine
I custom the default user by using AbstractBaseUser and BaseUserManager and also i creat a backend.py which handles authentication Email but it doesn't work, however superuser is work fine Thanks -
Get a django queryset that includes data from 5 linked models
I have 5 models that are linked with foreign keys like this: Section (Registration.section) ^ 1 | v ∞ Registration < ∞ --- 1 > Event (Registration.event) ^ ∞ | v 1 User (Registration.user, Profile.user) ^ 1 | v 1 Profile From these linked models, I am trying to display the data in a table like this: | ID | Other Profile fields | Section1 | Section2 | SectionN | |---------------|-------------------------|------------------------------|-----------------------------|----------| | User.username | e.g. User.profile.grade | Registration.objects.get( | Registration.objects.get( | | section=Section1, | section=Section1, | | user=user_from_this_row | user=user_from_this_row | | ).event | ).event | Where every user has a distinct row. What I can't figure out how to do efficiently is get the Registration(s) for each Section. I CAN do this by manually manipulating the data in python with dictionaries and loops etc, but this is so inefficient that my server times out before it can complete the process if the User list is too large. What queryset structure to I need to create to be able to output the data like this in a template? Each section will only have one registration object per user: class Registration(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) section = … -
AWS Elastic Beanstalk: WSGI path incorrect?
I'm attempting to deploy my first application to EB and am following along with this turorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html Unfortunately, I'm still getting a 502 error when deploying the final app. I'm confused because I've followed the directions to the tee. I'm getting the following error ImportError: Failed to find application, did you mean 'ebdjango/wsgi:application'? I'm not sure what this means. Per the instructions, I edited the django.config file to include this text: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango/wsgi.py This appears to match my file structure: - ebdjango -.ebextensions - django.config - .elasticbeanstalk - ebdjango - settings.py - urls.py - wsgi.py - manage.py - requirements.txt So the config file is set up correctly, right? I'm running Python 3.7 and Django 2.2. I know that EB searches for application.py, and I thought the config file is supposed to point the server towards my custom app? What am I missing here? EDIT: I'm also getting this error: ModuleNotFoundError: No module named 'ebdjango/wsgi' Is something off about my file structure? -
Implementing chat in Django application
I am a beginner in Django and I am trying to implement chatting in my Django app. I got 3 questions on how to approach this. 1. I see that people recommend to do this using Django Channels but what are the downsides to just using a database? 2. The tutorials on Channels seem to be on how to create a chat room. However I actually want the chat to be not in rooms but rather between users (I am using the default User model btw). Can anyone recommend a tutorial on how to do that? 3. In the official Django documentation JS is used too but I am not too familiar with it. So how much JS do I need to know to implement the chat? -
Capture web camera image and upload database using django
I am working on a form where in I am taking the user details like Name, email phone etc. In the same form once all the data is provided, user needs to click on Take photo button, camera gets initiated and I am able to capture the image and display in img tag in the html. Once this all is done, User needs to click on save button. All of these data including the image needs to get saved in the database/models created in backend. I have set my media and static file locations correctly. I am stuck in saving the image. I tried lot of options, but of no help. my model to save data - models.py class UserDetails(models.Model): User_name = models.CharField(max_length= 300) User_phone = models.BigIntegerField() User_address = models.TextField() User_pic = models.FileField(upload_to='documents/%Y/%m/%d') My HTML form {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-md-8"> <div id="accordion" role="tablist"> <form method="POST" action="/usersave/" enctype="multipart/form-data"> {% csrf_token %} .... <div class="card-body"> <div class="row"> <div class="col-md-4 ml-auto mr-auto"> <div class="form-group"> <video id="video" autoplay ></video> <canvas id="canvas"></canvas> </div> <button id="startbutton1" class="btn btn-outline-secondary btn-sm">Take Photo</button> <script src="{% static "assets/js/capture.js" %}"></script> </div> ..... <div class="img pull-center" > <img … -
ModuleNotFoundError: No module named 'learning_logsdjango'
I'm trying to run this command: python manage.py makemigrations learning_logs; but, I get the error: 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\Admin\Desktop\learning_log\ll_env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Admin\Desktop\learning_log\ll_env\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\Admin\Desktop\learning_log\ll_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\Desktop\learning_log\ll_env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Admin\Desktop\learning_log\ll_env\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'learning_logsdjango' These are the additions I've made to these two files; I'm using the Crash Course Python book by Eric Matthes--currently on page 386. models.py from django.db import models class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text settings.py --snip-- INSTALLED_APPS = [ # My apps 'learning_logs' … -
Python Django App Design change on deploy to server
I recently uploaded my Django App to the server (Digital Ocean). The functionality is okay as in my local project on my computer, but the design (css style) of the Admin Interface has changed drastically in a lot of elements of the change_list and change_form templates. I‘ve checked and made sure that the templates of my local Django and Suit files are the same as they of the server, but it is still not the same design. Does anyone has experience with that? -
Django user registration form not showing properly
I am making a Django project where there are two types of users customer and restaurant. Both can register separately. Everything is running fine except that I cannot add CSS class to password field and there are warning showing around password field which I don't how they are coming. Models.py class User(AbstractUser): is_customer = models.BooleanField(default=False) is_restaurant = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) food_pref = models.CharField(max_length=10, default='veg') class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) Forms.py soryy for bad code pasting.Just for clarification class 'CustomerSignupform' is parent class. class CustomerSignUpForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) food_pref = forms.CharField(required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_customer = True user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.food_pref = self.cleaned_data.get('food_pref') user.save() customer = Customer.objects.create(user=user) customer.food_pref = self.cleaned_data.get('food_pref') customer.save() return user def __init__(self, *args, **kwargs): super(CustomerSignUpForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'class': 'form-control', "name": "username"}) self.fields['first_name'].widget.attrs.update({ 'class': 'form-control', "name": "username"}) self.fields['last_name'].widget.attrs.update({ 'class': 'form-control', "name": "username"}) self.fields['food_pref'].widget.attrs.update({ 'class': 'form-control', "name": "food_pref"}) Views.py class customer_register(CreateView): model = User form_class = CustomerSignUpForm template_name = 'login/customer_register.html' def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/') Register User View So I have got similar problem for restaurant registration. … -
¿Why do I get a MultiValueDictKeyError in a POST request?
I'm currently learning in Django, and in this fetch request, I always get the same error: topup.html let data = new FormData(); data.append('amount', document.getElementById('amount').value); data.append('csrfmiddlewaretoken', "{{ csrf_token }}"); var response = fetch('{% url "secret" %}', { method: 'POST', body: data, credentials: 'same-origin', }) views.py def secret(request): amount = request.POST["amount"] error: Django Error I would really appreciate some help. Thanks! -
Django form content lost when redirecting using login_required
I have problem similar to this one: Django form data lost on making login required on post I want answer to be added if user is logged in otherwise redirect user to login page, let him login and then add his answer. My problem is that I lose content of the form when redirecting to login page. These are my views: def question(request, question_id): question = get_object_or_404(Question, pk=question_id) form = AnswerForm() return render(request, 'questions/question.html', {'question': question, 'form' : form},) @login_required def answer(request, question_id): question = get_object_or_404(Question, pk=question_id) form = AnswerForm(request.POST) if request.method == 'POST' else AnswerForm() if form.is_valid(): answer = form.save(commit=False) answer.author = request.user answer.question = question answer.save() return HttpResponseRedirect(reverse('question', args=(question.id,))) Form: <form method="POST" action="{% url 'answer' question.id %}"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Odpowiedz"> </form> Form in login template: <form method="post" action="{% url 'login' %}"> {% csrf_token %} {{ form.as_p }} <input type="hidden" name="next" value="{{request.GET.next}}" /> <input type="submit" value="login" /> </form> I don't know if something more than url can be passed by using next. -
Django - update ForeignKey when new object is created
I am trying to update my Foreign Key when the image is added to the database, just simply to tag the image if height is greater then width and vice versa. To do so I am trying to override the save method but I dont know how to do it exactly. models: from PIL import Image class PhotoDimensionsCategory(models.Model): photo_dim_category = models.CharField(max_length=250) class ImageInGallery(models.Model): image = models.ImageField(upload_to='photos/') gallery_dim = models.ForeignKey(PhotoDimensionsCategory, on_delete=models.CASCADE) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) on_height = PhotoDimensionsCategory.objects.get(photo_dim_category='on_height') on_width = PhotoDimensionsCategory.objects.get(photo_dim_category='on_width') is_new = not self.pk if img.height > img.width and is_new: # set the gallery_dim to on_height else # set the gallery_dim to on_width I tried few things, but it ended in errors. Any ideas. Thanks. -
Utilizing JQuery, AJAX and Django to have a form with chained dropdowns and add/delete form row functionality
As the title suggests i am building a template that utilizes a formset. The form has dropdown menus and it's options are loaded with ajax from a database table. As the user selects an option from first dropdown the second dropdown populates it's options from database using ajax. Total of 5 dropdowns that are linked. Everything works smoothly to this point with the django part and javascript part. I have also implemented a add/delete form functionality following a tutorial on the internet and the page successfully adds/removes forms as needed. However, when a new form is added the dependent dropdown functionality is not working for the new form. I realize this is due to the fact that the javascript code that triggers to populate the dropdown menus is listening for the change in form elements with specific id's. As a solutions (a bad one) i have duplicated the javascript codes that populate the menus and changed the id's form the form elements the code listens to since the django form management change the id following a pattern. It did not work and the form is showing strange behavior. When a new form is added, the selection from the dropdown menu … -
Reverse for 'project_detail' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['projects//int:pk/$']
I'm trying to make a simple portofolio app using django but I'm keep getting this error. I looked everywhere on google but nothing helps. I'm basically trying to link the Read more button(in project_index.html) to the project_details.html page using {% url 'project_detail' pk=project.pk %} Views.py: from django.shortcuts import render from projects.models import Project # Create your views here. def project_index(request): projects = Project.objects.all() context = {"projects": projects} return render(request, "project_index.html", context) def project_detail(request, pk): project = Project.objects.get(pk=pk) context = {"project": project} return render(request, "project_detail.html", context) Urls.py: from django.urls import path from projects import views urlpatterns = [ path("", views.project_index, name="project_index"), path("/int:pk/", views.project_detail, name="project_detail"), ] models.py: from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path="/img") project_index.html: {% extends "base.html" %} {% load static %} {% block page_content %} <h1>Projects</h1> <div class="row"> {% for project in projects %} <div class="col-md-4"> <div class="card mb-2"> <img class="card-img-top" src="{% static project.image %}"> <div class="card-body"> <h5 class="card-title">{{ project.title }}</h5> <p class="card-text">{{ project.description }}</p> **<a href="{% url 'project_detail' pk=project.pk %}"** class="btn btn-primary">Read More</a> </div> </div> </div> {% endfor %} </div> {% endblock %} project_detail.html: {% extends "base.html" %} {% load static %} {% … -
Override result serializer celery chord
I am using Celery chords to structure parallel AI processing of large document page content. Because this is a single use function with no public signature, I am pickling the objects to distribute and reaggregate. The task to process a single page is successfully reading the arguments and performing needed function. It fails however trying to return results to queue for subsequent aggregation. Does anyone know of a way to specify a result_serializer for a single task called via Chord? chord generation--- callback = processPageResults.subtask(kwargs={'cdd_id' : cdoc.cdd_id,'user_id':user.id},options={'serializer':'pickle'}) res = chord([processPage.s(useBold, docPages[i]).set(serializer='pickle') for i in range(0, len(docPages))], callback)() called task --- @shared_task(serializer='pickle',result_serializer='pickle',bind=True, max_retries=20) def processPage(self, *args): useBold = args[0] page= args[1] page.processWords(useBold) return page error --- kombu.exceptions.EncodeError: Object of type DocumentPage is not JSON serializable -
Moving a django postgres database to a new server leads to InconsistentMigrationHistory
I have an database dump file of my PostgreSQL database that was created by pg_dump. I transfer this file to a new server. I also transferred all the relevant models.py files to this never server. I used the following command to load in all the data on the new server. gunzip -c dump_file | psql -p port db_name db_user I configured Django to access this database and I can query the data using manage.py shell_plus. For eaxmple, I can run Images.objects.all().count()which returns the correct number, i.e. the same number of image objects as were present on the old server. Considering this is a different server, it does not contain any of the original migration files. I used ./manage.py makemigrations to create the migrations files. This appears to work properly and migration files are created for each of my installed_apps. Next, I run ./manage.py migrate. This leads to the following error: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration shapes.0001_initial is applied before its dependency bsdfs.0002_auto_20200527_1647 on database 'default'. All the answer on SO say to simply uncomment shapes from the installed_apps list, but this does not work because this leads to the following error when I'm importing it in the models.py. The models are extrmely big, … -
How can save session of shopping cart data after logout, so the user can find them when login again in Django?
I am working on e-commerce website using Django, I'm working on the shopping cart it's implemented using sessions and it's currently working fine, except one problem when the authenticated user logout from website, and login again , all data on cart lost. How can save session of shopping cart data after logout, so the user can find them when login again? my cart app files are: 1) cart.py from decimal import Decimal from django.conf import settings from shop.models import Product from coupons.models import Coupons class Cart(object): """docstring for Cart""" def __init__(self, request): """initalize the cart""" self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart self.coupon_id = self.session.get('coupon_id') def add(self,product,quantity=1,update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity':0,'price':str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def remove(self,product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def get_total_price(self): return sum(Decimal(item['price']) * … -
Django Reverse for 'document' with keyword arguments {'title':'computer science'} not found. 1 pattern tried
i getting a NoReverseMatch exception but i can't see my mistake. Urls file: url(r'^Demo$', views.demo, name='demo'), url(r'^Demo/(?P<title>[\w-]+)/$', views.demo_document, name='demo_document'), url(r'^Document_list$', views.document_list, name='document_list'), Template: {% for demotext in demotexts %} <li><a href="{% url 'keywordExtraction:demo_document' title=demotext.title %}">{{ demotext.title }}</a></li> {% endfor %} Views: def demo(request): demotexts = DemoText.objects.all().order_by('date') return render(request, 'keywordExtraction/demo.html', {'demotexts': demotexts}) def demo_document(request, title): demotext = DemoText.objects.get(title=title) demotexts = DemoText.objects.all().order_by('date') return render(request, 'keywordExtraction/demo.html', {'demotext': demotext, 'demotexts': demotexts}) Message: Reverse for 'demo_document' with keyword arguments '{'title': 'Computer Science'}' not found. 1 pattern(s) tried: ['KeywordExtraction/Demo/(?P[\w-]+)/$'] /views.py in demo return render(request, 'keywordExtraction/demo.html', {'demotexts': demotexts}) Local vars Variable Value demotexts <QuerySet [<DemoText: DemoText object (4)>, <DemoText: DemoText object (5)>]> request <WSGIRequest: GET '/KeywordExtraction/Demo'> -
How to control JWT access token based on regular payment status
I'm trying to start a subscription service for my django API. I want to control access to the API with JWT token depending on the payment of customers. If customers pay a fixed price regularly once a month, they can keep using the API. But if they fail to pay, they lose the access next month. What is the best way to implement this behavior? I come up with the following options, but I'm not sure if these are proper or not. -Issue an access token without expiration. The API itself checks the payment status and stops the service if not paid. -Issue a new access token with 1 month expiration every time the customer pay for it. The customer has to update token once a month to keep using the API, and then this is troublesome. Please let me know if there are any better ways. -
How do I convince JsonResponse to serialize a custom class?
I'm using Django 3.0.6 with Python 3.7. My views/controllers return a JsonResponse, like that: return JsonResponse({ 'My IP string': champion.ip_string, 'Chiefdom full name': chiefdom.FullName(), 'Chiefdom': chiefdom, # This will raise an exception }) I would like to upgrade the Chiefdom class to behave nicely with JsonResponse. The most obvious way to do that to me would be to override a method that JsonResponse is going to call to serialise this (I guess? It has to, come on…), but… I haven't been able to find any information at all regarding that. The whole point of this question is NOT modifying the VIEW. Only modify the Chiefdom class itself, in a way that then JsonResponse suddenly decides that "oh well now it is indeed serialisable". I could only find information that involves modifying the view itself, or stuff even more convoluted. There's tons and tons of irrelevant information, and if what I'm searching for is there somewhere, it was buried under piles of other stuff. -
Django/Bootrap Displaying Contacts from a Company
I have spent a few hours trying to solve this issue. Let me know if you have any ideas. Issue: I have defined two models. One for Contacts and one for Company. I can create one contact and company separately. How can I display the contacts from one company. For example, if I`ve got contact1, contact2 working for CompanyA, I would like to be able to see them listed under the companyA profile. Contacts models.py class Contact(models.Model): name = models.CharField(max_length=250) views.py def create_contact(request): form = ContactForm(request.POST or None, request.FILES or None) if form.is_valid(): contact = form.save(commit=False) contact.save() return render(request, 'contacts/detail.html', {'contact': contact}) context = { "form": form, } return render(request, 'contacts/create_contact.html', context) Company models.py class Company(models.Model): name = models.CharField(max_length=250) views.py def create_company(request): form = CompanyForm(request.POST or None, request.FILES or None) if form.is_valid(): company = form.save(commit=False) company.user = request.user company.company_logo = request.FILES['company_logo'] file_type = company.company_logo.url.split('.')[-1] file_type = file_type.lower() if file_type not in IMAGE_FILE_TYPES: context = { 'company': company, 'form': form, 'error_message': 'Image file must be PNG, JPG, or JPEG', } return render(request, 'company/create_company.html', context) company.save() return render(request, 'company/company_detail.html', {'company': company}) context = { "form": form, } return render(request, 'company/create_company.html', context) Company_detail.html <table id="dtBasicExample" class="table table-striped table-hover"> <thead> <tr> <th>#</th> <th>Name</th> </tr> … -
Django allauth not sending emails with Postmark
I'm using Django allauth for user registration. I have followed Postmarks instructions to set Django up so that emails will be sent from Postmark. However, I am not receiving any emails in my inbox. I'll use user registration as an example below. When I click on Register I get the following message in my terminal: 127.0.0.1 - - [27/May/2020 16:38:23] "POST /accounts/signup/ HTTP/1.1" 302 - 127.0.0.1 - - [27/May/2020 16:38:23] "GET /accounts/confirm-email/ HTTP/1.1" 200 - My settings.py: EMAIL_HOST = 'smtp.postmarkapp.com' EMAIL_HOST_USER = I USED THE API KEY FROM POSTMARKS 'SERVER API TOKEN' EMAIL_HOST_PASSWORD = I USED THE API KEY FROM POSTMARKS 'SERVER API TOKEN' EMAIL_PORT = 587 EMAIL_USE_TLS = True My HTML: {% extends 'coreapp/base.html' %} {% load staticfiles %} {% block content %}{% load i18n %} <div class="sign-up-page"> <div class="col-lg-8 offset-lg-2 accounts-page"> <div class="custom-card"> <h1>{% trans "Please register" %}</h1> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {% for field in form %} {{ field }} {% endfor %} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button class="accounts-register-button" type="submit">{% trans "REGISTER" %}</button> </form> </div> <div class="social-buttons-box"> {% include "socialaccount/snippets/provider_list.html" with process="login" %} </div> <div class="sign-in-message"> <p>{% blocktrans … -
Django, let user build his own table and data structure
got an hard question maybe, can't find anything apparently on google, still searching for it. In any case i'm trying to build up a form with about 40 fields. - 20 of these fields are simple CharText fields - 10 of these fields are simple DateTime fields - 10 remaining fields are my dilemma. For these last 10 field id like to let the user who's compiling the form, the possibility to: - decide the structure of the table ( like: 3 columns. 'col1' 'col2' 'col3' or 5 columns if he needs to); - after adding the columns that he needs, he may also add new entries to the previous table. I'll post the model base structure. ( blank lines after '=' means that i don't know how to fill ) I need to let the user build his own structure. I may build the columns myself, but it's better to let him create them by choosing their own structure. class Incarico(models.Model): #id = models.AutoField(primary_key=True) nr_sinistro = models.CharField(max_length=50, default=None) nr_polizza = models.CharField(max_length=50, default=None) appuntamento_danno = models.CharField(max_length=50, default=None) note_pubbliche = models.CharField(max_length=50, default=None) note_private = models.CharField(max_length=50, default=None) sinistro = models.DateField(default=None) incarico = models.DateField(default=None) perizia = models.CharField(max_length=50, default=None) pl = models.CharField(max_length=50, default=None) codifiche … -
Error in AsyncConsumer in Django channels
I used a tutorial for creating a video chat app. But when i run the code it gives me error and it's not so clear to know what is exactly making the problem. Error: WebSocket CONNECT /ws/videochat/ [127.0.0.1:38466] Exception inside application: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 172, in __get__ rel_obj = self.field.get_cached_value(instance) File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/fields/mixins.py", line 13, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'callee' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/home/nimda/Desktop/videotest/vcp/chat/consumers.py", line 156, in websocket_receive f"videochat_{videothread.callee.id}", File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 186, in __get__ rel_obj = self.get_object(instance) File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 153, in get_object return qs.get(self.field.get_reverse_related_filter(instance)) File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/query.py", line 411, in get num = len(clone) File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/query.py", line 258, in __len__ self._fetch_all() File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/nimda/Desktop/videotest/test/lib/python3.6/site-packages/django/db/models/query.py", line 57, …