Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django UserCreationForm custom fields
I am trying to create form for user registration and add some custom fields. For doing that, I've subclassed UserCretionForm and added fields as shown in django documentation. Then I've created function-based view and template based on this form. Now, I can successfully create user and this user is added to admin panel as expected. Problem is that, I can't add class and style for this form's fields. Widgets are not working except for username field. I'm adding my scripts here for illustrating my problem more accurately: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=32, help_text='First name') last_name = forms.CharField(max_length=32, help_text='Last name') email = forms.EmailField(max_length=64, help_text='Enter a valid email address') class Meta(UserCreationForm.Meta): model = User # I've tried both of these 'fields' declaration, result is the same # fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',) widgets = { 'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'}), 'first_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), 'last_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}), 'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'}), 'password1': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'}), 'password2': forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password Again'}), } views.py from django.contrib.auth import login, authenticate from django.contrib.auth.views … -
perform raw SQL in django
In our project I am going to create a page with a textbox where we type raw SQL code and I want this code run and returns result to me and show it below the code. As I do not have much experience I would be grateful if someone tells me how to do that exactly. -
Django - PostgresSql and Sequences
We are using Python 3.5, Django 1.10 and PostgreSql 9.6 DB We needed some Auto-increment field for one of the object (Item), and couldn't achieve that using DB auto increment, since there is another dependency for the incrementation. The field should be incremented for Item per Project (each Project can contain multiple items). We decided to use django-sequences package that basically creates another table (we're using the same DB as our models), and increments the field whenever asked to by locking the DB and increment the highest value according to relevant parameter (in our case the Project id). Seems like it works. The problem occurs when there are multiple requests in parallel. Seems like the DB gets locked and we're starting to get 504 after few requests. Any idea on why it happens and what could solve that? This is the django-sequences use: if instance.identifier < 0: with transaction.atomic(): instance.identifier = get_next_value( 'project__' + str(instance.project.id) + '__item__identifier', initial_value=1, nowait=False ) -
Django puts my password in browser url field
I have the following view class: class LoginView(View): form_class = LoginForm template_name = 'workoutcal/login.html' def post(self, request): form = self.form_class(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(email = email, password = password) if user is not None: if user.is_active: login(request, user) return calendar(request) else: return render(request, self.template_name, {'form':form}) else: form['custom_error_message'] = 'Invalid user' return render(request, self.template_name, {'form':form}) def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form':form}) And this template: login.html {% extends "workout/base.html" %} {% block logoutwidget %}{% endblock %} {% block content %} <form action="/workoutcal/login/"> {% include "workoutcal/form_disp_errors.html" %} <input type="submit" value="Log in"> </form> {% endblock %} form_disp_errors.html {% csrf_token %} {{ form.custom_error_message }} {{ form.non_field_errors }} {% for field in form.visible_fields %} <div class="row"> <div class="col-xs-2"> {{ field.label_tag }} </div> <div class="col-xs-2"> {{ field }} </div> <div class="col-xs-3"> {{ field.errors }} </div> </div> {% endfor %} When I go to workoutcal/login, type in an incorrect username and password (user doesn't exist), the page goes to workoutcal/login again, but with this url: http://localhost:8000/workoutcal/login/?csrfmiddlewaretoken=ZywQUh7gnNfaHi8FcA3be4ynLB7SpGgwdJ0UxGzUuRYp0G0Y9LQ9e24Jx8Q1OD3Y&email=myemail%40hotmail.com&password=MYPASSWORD As you can see in the end of the link, the password is displayed. This is obviously not good. However, I can't understand why it happens. Any ideas? -
Django Facebook APP
I am a newbie in Django .I wish to develop a Django application that can post an app result to Facebook. I want to get the likes and shares that the post get. I am developing the app in Django Version 1.11, using Python 3.4 and database MySQL(mysqlclient). Please share some document that is not outdated or guide me with steps. Thanks -
Django Wagtail Menus not showing all menu items
I am using wagtail cms for making my blog. So I have installed wagtail menus inside my django project. I followed the official documentation for creating a top level menu but it showing the single item which I created in wagtail admin. Settings.py INSTALLED_APPS = [ 'bootstrap3', 'blog', 'home', 'search', 'wagtail.wagtailforms', 'wagtail.wagtailredirects', 'wagtail.wagtailembeds', 'wagtail.wagtailsites', 'wagtail.wagtailusers', 'wagtail.wagtailsnippets', 'wagtail.wagtaildocs', 'wagtail.wagtailimages', 'wagtail.wagtailsearch', 'wagtail.wagtailadmin', 'wagtail.wagtailcore', 'wagtail.contrib.modeladmin', # Don't repeat if it's there already 'wagtailmenus', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Middleware: MIDDLEWARE = [ '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', 'django.middleware.security.SecurityMiddleware', 'wagtail.wagtailcore.middleware.SiteMiddleware', 'wagtail.wagtailredirects.middleware.RedirectMiddleware', ] contextprocessors: 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'wagtail.contrib.settings.context_processors.settings', 'wagtailmenus.context_processors.wagtailmenus', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', ], I included this code in base.html to include the mainmenu. {% wagtailuserbar %} {% load menu_tags %} {% main_menu max_levels=3 show_multiple_levels=True apply_active_classes=True %} Then I created 3 pages in admin and tried to link the menus.The main and the flat menu option is there for creating the menu.I used main menu and created some menu items using the pages I created but I am getting only Home menu which I created the first.The other menu items are not visible. -
Django default model field value
suppose I have a Django object of this type: class Some(Model): some_value = CharField(max_length=20) and after a while (and a few objects later) I understood I'd like to save the created time for each new object, so I add the following field: created = FloatField(default=time.time) Let's suppose now I have a few old object which were created without the "created" field. When I query them, they receive the default time.time, even though it's suppose to be None. How can I get a different value for all the old objects? I only want new objects to be created with this default, and say all old objects without this field to be None, or some other known value. Setting null=True doesn't make a difference. Thanks! -
I tried in different ways to update row through Django views but it's not working
I want to assign a variable from outside query to password in update query. Is it possible to assign otpgen to password? otpgen="123221" conn=sqlite3.connect(path) cursor=conn.cursor() cursor.execute("UPDATE user SET password=12 WHERE email = %s", [email]) -
Call post_save after many to many fields are saved in database
I have model class UserPermission(models.Model): user = models.OneToOneField(User) user_type = models.ManyToManyField(UserType) persona = models.ManyToManyField(Persona) And post save signal @receiver(post_save, sender=UserPermission) def post_save_user_permissions(sender, instance, **kwargs) """ Depending on selected UserType and Persona for a user, Update some other model """ pass I want all updated values of both the m2m fields in post save signal. but issue here is post save signal is getting called before m2m fields saved into db. I could have used m2m_changed signal, but there are two m2m fields and I can't associate or link these two signals Is there anyway to call post_save once all m2m fields in model are saved into db. -
Paginator does not work
Paginator does not work.I wrote views.py from .models import POST from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render def top(request): item = POST.objects.order_by('-created_at') page = _get_page(item, request.GET.get('page')) return render(request, 'top.html',{'item':item,"page":page}) def _get_page(list_, page_no, count=1): paginator = Paginator(list_, count) try: page = paginator.page(page_no) except (EmptyPage, PageNotAnInteger): page = paginator.page(1) return page in top.html <div> {% for i in item %} <div> <h2>{{ i.title }}</h2> <p>{{ i.index }}</p> </div> {% endfor %} </div> <div> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Previous</a> {% endif %} {% for num in page.paginator.page_range %} {% if page.number == num %} <span>{{ num }}</span> {% else %} <a href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if page.has_next %} <a href="?page={{ page.next_page_number }}">Next</a> {% endif %} </div> When I access top.html,all item is shown in browser.I think I wrote one item was shown in one page(browser) in this part page = paginator.page(page_no) ,but no error happens so I really cannot understand what is wrong.How should I fix this? -
extending a url to another in django
I have a django application where by I can create a category and from the category I can select a subcategory before selecting a post. I have also created slugs for both the category , subcategory and the post and this works fine. what I now want to do but could not achieve is to make the subcategory slug continous on d product that is if the slug is http://127.0.0.1:8000/house/ before clicking on a post, I want the url to look like this after clicking on a post under house http://127.0.0.1:8000/house/duplex. below is my model for my sub category Models.py class SubCategory(models.Model): category = models.ForeignKey(Category, related_name='property', on_delete=models.CASCADE) name = models.CharField(max_length=400,db_index=True) slug = models.SlugField(max_length=400,db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'subcategory' verbose_name_plural = 'subcategories' def __str__(self): return self.name def get_absolute_url(self): return reverse('subcategory:property_list_by_subcategory', args=[self.slug]) View def index(request, subcategory_slug=None, category_slug=None): subcategory = None subcategories = SubCategory.objects.all() properties = Property.objects.filter(available=True) if subcategory_slug: subcategory = get_object_or_404(SubCategory, slug=subcategory_slug) properties = properties.filter(subcategory=subcategory)HttpResponseRedirect(reverse('category:property_list_by_category')) context = { 'subcategory': subcategory, 'subcategories': subcategories, 'properties': properties } template = 'subcategory/index.html' return render(request, template, context) additional codes would be supplied on request. -
Django-rest-framework multiple url arguments
How do i map the "example object" to the url: website.com/api/<user>/<slug>. I'm getting this invalid literal for int() with base 10: 'username' error. so i understand that i need to use the user id in-order to map to the object, this is because I am able to map to the object if i use the user_id (integer) (url: website.com/api/<user_id>/<slug>) instead of just the user/username (string). Is there a way to override the default when mapping to the object from user_id (integer) to another field like user (string)? Also i don't understand why passing the user instead of user_id in the def get_object in (Api View) does not fix this problem. Url urlpatterns = [ url(r'^api/(?P<user>\w+)/(?P<slug>[\w-]+)/$', ExampleDetailAPIView.as_view(), name='example'), ] Api View class ExampleDetailAPIView(RetrieveAPIView): queryset = Example.objects.all() serializer_class = ExampleDetailSerializer def get_object(self): user = self.kwargs.get('user') slug = self.kwargs.get('slug') return Example.objects.get(user=user, slug=slug) def get_serilizer_context(self, *args, **kwargs): return {'request': self.request} Serializer class ExampleDetailSerializer(HyperlinkedModelSerializer): url = serializers.SerializerMethodField() class Meta: model = Example fields = [ 'url', ] def get_url(self, obj): request = self.context.get('request') return obj.get_api_url(request=request) Model class Example(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) example_name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, blank=True) class Meta: unique_together = ('user', 'slug') def get_api_url(self, request=None): return api_reverse('example-api:example', kwargs={'user': self.user.username, 'slug': self.slug}, request=request) … -
Use email to login in Django 1.11, I use cookiecutter-django with allauth
I started using cookiecutter-django because it seems so much advanced than just django-admin to start my project. So I created an eCommerce website and it requires only email to log in not the username. So, I tried to follow the docs and changes my settings.py like this: ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' AUTH_USER_MODEL = 'accounts.User' LOGIN_REDIRECT_URL = 'users:redirect' LOGIN_URL = 'account_login' Here is my accounts.User model: from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) class UserManager(BaseUserManager): def create_user(self, email, full_name, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") if not full_name: raise ValueError("Users must have a fullname") user_obj = self.model( email = self.normalize_email(email), full_name = full_name ) 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, full_name, password=None): user = self.create_user( email, full_name, password=password, is_staff=True ) return user def create_superuser(self, email, full_name, password=None): user = self.create_user( email, full_name, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD … -
Nginx requested headers are not getting set in django response headers
project environment details are - angular2 :frontend - django :webservice api - Proxy webserver: Nginx 1.12.2 - application server : gunicorn My application is deployed in ubuntu vm over azure platform. I am facing problem to get response headers which are being set in request headers. My nginx project config under sites-available is as- server { listen 80; listen [::]:80; listen 443 ssl default_server; listen [::]:443; server_name test-api.mydjangoapp.net www.test-api.mydjangoapp.net; underscores_in_headers on; location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_set_header Host $http_host; proxy_buffering off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/puser//run/gunicorn.sock; proxy_redirect off; } } In django settings I have configured 'corsheaders' and allowed headers, CORS_REPLACE_HTTPS_REFERER = True CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'X-Content-Type-Options', 'X-Frame-Options', 'Access-Control-Allow-Methods', 'Content-Type', 'Access-Control-Allow-Origin', 'Access-Control-Allow-Credentials', 'supports_credentials', 'Access-Control-Allow-Headers', 'nosniff', 'Cache-control', 'no-cache', 'no-store', 'Pragma', 'Expires', 'Set-Cookie', 'X-XSS-Protection', ) CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) Earlier when I used Azure app service where [webserver- IIS 10 and application server: ufastcgi] all headers were used to set in response. But On nginx it is not working. Current Request and response details are as- Response Headers for POST: Access-Control-Allow-Credentials:true Access-Control-Allow-Origin:http://test-webapp.myangularapp.net Connection:keep-alive Content-Type:application/json Date:Mon, … -
Why google has so many urls in just for search bar page?
While making django bookmark app, I realize that google searchbar page has so many urls. Like, no https://www.google.co.kr, https://www.google.co.kr/?gfe_rd=cr&dcr=0&ei=et5JWq2NNoz02QS3vKH4DA, https://www.google.co.kr/?gfe_rd=cr&dcr=0&ei=jd5JWrCTI4z02QS3vKH4DA It's different at ?gfe_rd=cr&dcr=0&ei=et5JWq2NNoz02QS3vKH4DA and ?gfe_rd=cr&dcr=0&ei=jd5JWrCTI4z02QS3vKH4DA. Questions: Why these are different? Is there good way to determine that 2 urls are pointing the same pages on django server? or using other python packages? -
How to login in django with https/ssl at deploy server
I have django project. It works well on my Mac.But it's not work well on GCP(Ubuntu 17). When I try login from login page. I cant login and authorize. I return same login page. No thing happen. Just reload same page. This site uses Nginx with uWSGI I'm thinking this problem comes from https/ssl settings. If you know how to solve this problem, please let me know. This is my code: urls.py from django.conf.urls import url from django.contrib.auth.views import login, logout_then_login from django.urls import reverse_lazy from . import views from django.contrib.auth import views as auth_views app_name = 'invo' urlpatterns = [ # Login Logout url(r'^login/$', login, {'template_name': 'invo/login.html'}, name='login'), url(r'^logout/$', logout_then_login, name='logout'), ] nginx setting # the upstream component nginx needs to connect to upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 443 ssl; ssl_certificate /etc/letsencrypt/live/tekis.biz/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/tekis.biz/privkey.pem; # the domain name it will serve for server_name tekis.biz; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to … -
Django 2.0 Password Validation
By default in Django 2.0 we get AUTH_PASSWORD_VALIDATORS option with UserAttributeSimilarityValidator MinimumLengthValidator CommonPasswordValidator NumericPasswordValidator So is there any easy way to add extra VALIDATORS like minimum 1 uppercase, 1 symbol, 1 digit, etc. ? In python i can check Using regex import re userPass = 'HelloWorld*123' if re.search('[A-Z]', userPass)!=None and re.search('[0-9]', userPass)!=None and re.search('[^A-Za-z0-9]', userPass)!=None: print 'Strong Password' -
Mysql error while starting Django on eclipse
Hi i'm new to Django framework and want to connect MariaDB. So I added the code below on settings.py DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'django.db.backends.mysql', 'NAME': 'findworknear', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '' } } However, whenever I tried to run server, all I could see were several lines of error messages. I tried some tips found on stackoverflow. (sudo pip install python-mysql, sudo pip install mysqlclient). But none of them worked. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x103ed91e0> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Django-2.0-py3.6.egg/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", … -
In Django how to decrypt the session id in database and in cookie with my SECRET_KEY?
I created one Django application with below settings - (for cookie base session) SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' Then I got a session id sessionid=.eJxrYJk6gwECaqdo9PDGJ5aWZMSXFqcWxWemTOlhMjSY0iOEJJiUmJydmgeU0UzJSsxLz9dLzs8rKcpM0gMp0YPKFuv55qek5jjB1PIjGZCRWJwxpUfDMNUk1STJ1MLc0tLczDLNyMg0ydDQzDTJzCjZ0jg50SLR3NDc3DzReEqpHgBcETf7:1eVt50:xtWtUp9mwcxusxtg6fZB_tHzlYw With another setting (for database-backed sesisons) SESSION_ENGINE = 'django.contrib.sessions.backends.db' SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' I got below encrypted string in database: gzc9c9nwwraqhbdsk9xg935ypkqp7ecs|MmExZWI0NjZjYzIwNDYyZDhjNWVmODJlNmMwNjI0ZmJmMjQ4MTljNDp7Il9hdXRoX3VzZXJfaWQiOiIxMCIsIl9hdXRoX3VzZXJfYmFja2VuZCI6ImRqYW5nby5jb250cmliLmF1dGguYmFja2VuZHMuTW9kZWxCYWNrZW5kIiwiX2F1dGhfdXNlcl9oYXNoIjoiMWU0ZTRiNTg3OTk3NjlmMjI1YjExNjViNjJjOTNjYThhNzE3NzdhMyIsImxhc3RfbG9naW4iOjIyMjJ9 I want to know what is inside both the encrypted strings. How can I decrypt both? Which encryption algorithm django uses for encryption? Where can I set the encryption algorithms? It will be great, if anyone can give me a sample code. -
Implementing Django Form without Model
This is a continuation from last question here Coding mental block with specific Django task The answer was: A pure django solution would be: create a form with three integer fields (say, num1, num2 and result) in your view, populate num1 and num2 with the numbers to be added render the form in your template (num1 and num2 fields should be read only) the user enters the answer in the result field and submits the form in your view, determine whether num1 + num2 == result redirect to a success page if the answer is correct, otherwise redisplay the form However, as I am working through the steps, my form was not being rendered properly. views.py def post_question(request): form = QuestionForm(request.POST) if form.is_valid(): question = Question(question_text = form.cleaned_data['question_text'], MY_FIELD = form.cleaned_data['MY_FIELD'], exam = form.cleaned_data['exam']) question.save() return HttpResponseRedirect('/numbers/') forms.py class MyForm(forms.Form): a = forms.CharField(max_length=20) mat = forms.CharField(max_length=200) html file <form action="{% url 'form_handle' %}" method="POST">{% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> When I load the page all I see is a submit button. As pictured Can someone please advise me where I had gone wrong? -
Django Error Message
I have a case. Once the form is submitted, it has to make a query. If the query exists, it has to send an error message. If the query does not exist, it has to save the data. I have written view as below and it works. But the only issue is that the error message goes like a success message. I have tried placing the query before validating the form, still, it's same. How could I resolve this? def permissionFormView(request): r_form = forms.RoleForm() p_form = forms.PermissionForm() if request.method == 'POST': p_form = forms.PermissionForm(request.POST) if p_form.is_valid(): role = p_form.cleaned_data['role_name'] feature = p_form.cleaned_data['feature'] if models.PermissionModel.objects.filter(role_name=role,feature=feature).exists(): messages.error(request, 'Permission exists.') else: p_form.save() messages.success(request, 'Permission added successfully.') return render(request, 'company_profile.html', {'r_form': r_form, 'p_form': p_form}) return render(request,'company_profile.html',{'r_form':r_form,'p_form':p_form}) Client Side Form Code: <form action="{% url 'permission_form' %}" novalidate method="POST"> {% csrf_token %} <div class="row"> <div class="col"> <label for="r_name"><small><strong>{{ p_form.role_name.label }}</strong></small></label> <p>{{p_form.role_name}}</p> {% for error in p_form.role_name.errors %} <p><small class="alert-danger">{{ error }}</small></p> {% endfor %} </div> <div class="col"> <label for="r_feature"><small><strong>{{ p_form.feature.label }}</strong></small></label> <p>{{p_form.feature}}</p> {% for error in p_form.feature.errors %} <p><small class="alert-danger">{{ error }}</small></p> {% endfor %} </div> <div class="col"> <label for="permission"><small><strong>{{ p_form.permission.label }}</strong></small></label> <p><input type="checkbox" class="form-control" id="permission" name="permission" {% if r_form.role_name.value is not None %} value="{{ p_form.permission.value … -
Makefile for Running Django Backend and React Frontend
I am working on a project which is developed by Django REST Framework and served by React app. There is a partition between the back end and front end. The structure of the path is: Root ├── backend ├── frontend ├── makefile ├── readme.md ├── requirements.pip └── venv Currently, I run the project by opening two different terminals. Then I start the django server first and then start the react app. In terminal 1, I start the django server: cd backend python manage.py runserver In terminal 2, I start the react app: cd frontend npm start So, it is quite irritating to redo these commands each time to run the project. Recently, I have heard about makefile. I think this will reduce the number of commands to start the project. I have created the following makefile: run: python backend/manage.py runserver cd frontend npm start When I write make run it successfully starts the Django server but it does not start the React application. What am I missing here? Can I run the both commands in a single command using make? -
force-download with Django and Vue
I was trying use vue to download file from server when I director visit my backends API, it work well,and I can unzip my file normal. but when I try to download file by axios response, the file can not unzip,and also if I don't set link.download, the filename does not correct.like that here is my vue's api export function packMaterials (context, thesisId, filename) { context.$axios({ method: 'get', headers: getAuthHeader(), url: PACK_URL + thesisId }) .then(function (response) { console.log(response) let blob = new Blob([response.data], { type: 'application/force-download' }) let link = document.createElement('a') link.href = window.URL.createObjectURL(blob) link.download = filename link.click() }) .catch(function (error) { console.log(error) }) } here is my Django API if os.path.exists(file_path): # 返回file with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/force-download") response['Content-Disposition'] = "attachment; filename={}".format(escape_uri_path(filename)) return response and here is the response data in console. English not my native language, so if my description not clearly, you can contact me with lc960127@gmail.com I will send more detail. Thanks -
OperationalError at /app/top/ no such column: app_post.category_id
I got an error,OperationalError at /app/top/ no such column: app_post.category_id . I wrote codes in views.py from .models import POST from django.shortcuts import render def top(request): contents = POST.objects.order_by('-created_at') render(request, 'top.html', {'contents': contents} in models.py from django.db import models class Category(models.Model): name = models.CharField("CategoryName", max_length=100) def __str__(self): return self.name class POST(models.Model): title = models.CharField(max_length=100) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="Category") def __str__(self): return self.title First I made POST model and next I did Category model ,then I connected them by using ForeignKey.I think this process causes this error so I run command python manage.py flush --database=default and delete all migration file.However same error happens.I deleted db so I think it solve the error, but I am wrong.How should I fix this?What should I do to fix this? -
Python Django multiprocessing Error: "AttributeError: Can't pickle local object 'Command.handle.<locals>.f'"
I'm using python 3.6 django 1.11 windows10 and trying to send email using multiprocessing. recipients are connected to database(django model) and email contents form is html(by django get_template), also used get_connection to send multi-email. What I'm trying is to use multiprocessing to accelerate sending rate. My code is here from django.core.management.base import BaseCommand from django.core.mail import get_connection, EmailMessage from django.template.loader import get_template from multiprocessing import Pool from sending.models import Subscriber class Command(BaseCommand): def handle(self, *args, **options): connection = get_connection() recipients = [i.email for i in Subscriber.objects.all()] num = Subscriber.objects.count() subject = 'Multiprocessing trying 1' body = get_template('Newsletter20171229.html').render() from_email = 'info@modoodoc.com' def send(i): msg = EmailMessage(subject, body, from_email, [recipients[i]]) msg.content_subtype = 'html' print("Sending email to: " + recipients[i] + " No: " + str(i)) connection.send_messages([msg]) print("Complete.") pool = Pool(processes=2) pool.map(send, range(0, num)) print("Mail have just sent. The program is going to end.") connection.close() And I've got an error like this. File "c:\python36-32\Lib\multiprocessing\connection.py", line 206, in send self._send_bytes(_ForkingPickler.dumps(obj)) File "c:\python36-32\Lib\multiprocessing\reduction.py", line 51, in dumps cls(buf, protocol).dump(obj) AttributeError: Can't pickle local object 'Command.handle.<locals>.f' How to fix this? Thank you.