Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django foreign relations regarding form and multiple file upload
i have a Patient model, which can contain many files uploaded by the staff ( test results of all sorts ) , what happens is that the form for adding a new patient and uploading files to that patient cannot go through because the file feed is initially empty, but it cannot be empty.. here is the code //models.py class Patient(models.Model): name = models.CharField(max_length=200, blank=True) created_at = models.DateTimeField(auto_now=True) tests = models.CharField(max_length=200,blank=True) feed = models.ForeignKey('Feed', on_delete=models.CASCADE, blank=True) def __str__(self): return self.name class FeedFile(models.Model): files = models.FileField(upload_to="documents/%Y/%m/%d") def __str__(self): return self.files class Feed(models.Model): name = 'files' files=models.ManyToManyField(FeedFile, blank=True) def __str__(self): return self.name //views.py class PatientCreate(CreateView): model = Patient fields = ['name'] //forms.py class NewPatientForm(ModelForm): files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Patient fields = '__all__' def __init__(self, *args, **kwargs): super(NewPatientForm, self).__init__(*args, **kwargs) self.fields['feed'].required = False as you can see in the last part i have even tried to define that the feed field can be empty, but still when filling out the new patient form it wont go through ( " this field is required") Thanks. -
Exception Value: invalid literal for int() with base 10: ''
when i try to Remove items from card is show me Exception Value: invalid literal for int() with base 10:,when i try to Remove items from card is show me Exception Value: invalid literal for int() with base 10:, when i try to Remove items from card is show me Exception Value:invalid literal for int() with base 10:,when i try to Remove items from card is show me Exception Value:invalid literal for int() with base 10:, carts/views.py from django.shortcuts import render,redirect from products.models import Product from .models import Cart def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) return render(request, "carts/home.html", {"cart": cart_obj}) def cart_update(request): product_id=request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user Product is gone") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) else: cart_obj.products.add(product_obj) #request.session['cart_items'] = cart_obj.products.count() #cart_obj.products.remove(product_obj) return redirect("cart:home") update-cart.html <form method="POST" action="{% url "cart:update" %}" class= "form "> {% csrf_token %} <input type="hidden" name="product_id" value="{{ product.id }}"/> {% if in_cart %} <button type="submit" class="btn btn-link btn-sm " style="padding: 0px; cursor: pointer">Remove?</button> {% else %} {% if product in cart.products.all %} In cart<button type="submit" class="btn-btn-link">Remove?</button> {% else %} <button type='submit' class='btn btn-success'>Add to cart</button> {% endif %} {% endif … -
django: uwsgi not running with supervisor
This is my uwsgi ini file, [uwsgi] chdir=/root/projects/cbapis/cbapis module=cbAPIs.wsgi:application env = DJANGO_SETTINGS_MODULE=cbAPIs.settings.production http=0.0.0.0:8002 workers=1 home=/root/projects/cbapis/cbapis/env This is the django wsgi file, import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cbAPIs.settings.production") application = get_wsgi_application() When I run server with uwsgi, it runs fine, uwsgi --ini cbapi_uwsgi_config.ini Below is my supervisor conf for this project, [program:djangocbapis] command=uwsgi --ini /root/cbapi_uwsgi_config.ini environment = DJ_DEV_SERVER_DB_NAME="****", DJ_DEV_SERVER_DB_USER="****", DJ_DEV_SERVER_DB_HOST="*****", DJ_DEV_SERVER_DB_PASSWORD="*****", autostart=true autorestart=true user=root priority=400 stderr_logfile=/var/app/cbapis/log/cbapis.log When I run this uwsgi server via supervisor, it does not run. I get the following error in the log file, --- no python application found, check your startup logs for errors --- I have similar supervisor and uwsgi configuration for my other django projects in the same server, which are running fine with supervisor and uwsgi. But I can't figure out why it cannot find python application while running with supervisor. So, please help me in this matter. -
Nginx Timeout not working for a long running process
I have one long running process at my server end and I want to increase nginx timeout. I have tried various parameters like proxy_read_timeout, proxy_connect_timeout, uwsg_read_timeout, fastcgi_read_timeout but nothing seems to work. It takes the default and times out in 60s. I'm using uwsgi+nginx and here are my configurations: uwsgi file : production.ini ` [uwsgi] chdir = /adlm/adlm_python/adlm module = adlm.wsgi master = true processes = 5 enable-threads = true threads = 40 thunder-lock = true uid = nginx gid = nginx shared-socket = 0.0.0.0:11888 socket-timeout = 300 http_timeout = 300 http = =0 vacuum = true max-requests = 1000 harakiri = 300 buffer-size = 32768` nginx.conf in /etc/nginx: `user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; include /etc/nginx/conf.d/*.conf;` server { listen 11443 ssl http2 default_server; listen [::]:11443 ssl http2 default_server; server_name dowaznp***.dowcloud.com; root /adlm/adlm/frontend/adlm/build; ssl_certificate "***"; ssl_certificate_key "***"; ssl_session_cache shared:SSL:1m; ssl_session_timeout 10m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; include /etc/nginx/default.d/*.conf; location / { } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } `}` … -
ImportError: cannot import name 'Employee'
First, let me start by letting you know that I'm creating a time attendance and payroll software. I have multiple models with Employee at the center of the entire architecture. Different apps have different models each storing different kind of settings(LeaveSettings, ShiftSetttings, etc ). These models are a foreign key in the Employee model. I also have some hidden models to store arbitrary data like Balances, etc. Employee is also imported and used as a foreign key in all of these models. Eg: LeaveSettings and LeaveBalance are in an app called leavemanagement. Employee imports LeaveSettings and has a LeaveSettings Foreign Key LeaveBalance imports Employee and uses it as a foreign key. This is the error i get: File "E:\OnTime\mysite\leavemanagement\models\__init__.py", line 4, in <module> from leavemanagement.models.model_leavebalance import LeaveBalance File "E:\OnTime\mysite\leavemanagement\models\model_leavebalance.py", line 3, in <module> from master.models.model_employee import Employee File "E:\OnTime\mysite\master\models\__init__.py", line 4, in <module> from master.models.model_employee import Employee File "E:\OnTime\mysite\master\models\model_employee.py", line 9, in <module> from payroll.models.model_months import Months File "E:\OnTime\mysite\payroll\models\__init__.py", line 6, in <module> from payroll.models.model_reimbursmentdetail import Reimbursement File "E:\OnTime\mysite\payroll\models\model_reimbursmentdetail.py", line 1, in <module> from master.models.model_employee import Employee ImportError: cannot import name 'Employee' -
Open remote page as modal view in bootstrap
I thought this is very simple think to do, but I can't found it on internet. How could I open outside page ( like https://google.com/ ) as a modal view? I don't want to: Open page in new tab Open page in new popup window like: onClick="MyWindow=window.open('http://www.google.com','MyWindow',width=600,height=300) Open my own pre-prepared page as described here Is there a way to do this? It should be reight? -
NoReverseMatch at /signup/
Reverse for 'activate' with keyword arguments '{'uidb64': b'Mw', 'token': '4vb-698f794fd74543e1258f'}' not found. 1 pattern(s) tried: ['activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] templates/account_activation_email.html {% autoescape off %} Hi {{ user.username }}, Please click on the link below to confirm your registration: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} It seems to be working fine on my localhost url; but when it's deplyed in heroku. it throws this error. views.py def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) return redirect('home') else: return render(request, 'account_activation_invalid.html') urls.py url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', core_views.activate, name='activate'), -
adding unique key to many to many field in django
I have following models class SettingAttributes(Core): attribute_name = models.CharField(max_length=100) description = models.CharField(max_length=100) setting_type = models.CharField(max_length=10, choices=SETTING_TYPES) class Meta: app_label = 'core' and class SettingAttrValue(Core): attribute_value = models.CharField(max_length=200) attribute_type = models.CharField(max_length=200) attribute = models.ForeignKey(SettingAttributes) user = models.ManyToManyField(User) avaliases = models.TextField() attriblob = models.BinaryField(default=None, blank=True, null=True) class Meta: app_label = 'core' I want to add unique_together on SettingAttrValue and User. If i do this in meta class of second model django is giving me error like 'unique_together' refers to a ManyToManyField 'user', but ManyToManyFields are not permitted in 'unique_together'. -
Trying to deploy Django app to Heroku - "Internal Server Error"
I've been trying for hours now to deploy to Heroku and all I have to show for it is a big white page that says "Internal Server Error" (the site is hosted here: https://iffapp.herokuapp.com/). I'm using django-cookiecutter and followed their guide exactly (http://cookiecutter-django.readthedocs.io/en/latest/deployment-on-heroku.html). Everything went well enough, but there's no app. When I run heroku run python manage.py check --deploy, this is what I get: Running python manage.py check --deploy on ⬢ iffapp... up, run.5052 (Hobby) System check identified no issues (0 silenced). MacBook-Pro:iffapp Starbuck$ git push heroku master Counting objects: 5, done. Delta compression using up to 4 threads. Compressing objects: 100% (5/5), done. Writing objects: 100% (5/5), 442 bytes | 442.00 KiB/s, done. Total 5 (delta 4), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing pip remote: -----> Installing requirements with pip remote: remote: -----> $ python manage.py collectstatic --noinput remote: Found another file with the destination path 'admin/css/changelists.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. remote: Found another file with the destination path … -
Django has no Attribute 'HiddenInput'
I am getting the error module 'django.forms.forms' has no attribute 'HiddenInput' on the following code: from django.forms import ModelForm, forms from comments.models import Comment class CommentForm(ModelForm): class Meta: model = Comment fields = ['video', 'text'] widgets = {'video': forms.HiddenInput(), 'text': forms.TextArea()} Does anyone know what could be causing this? I looked it up in the documentation, and HiddenInput() should be valid (https://docs.djangoproject.com/en/2.0/ref/forms/widgets/). -
Making user account and login in django
I am new to django.I want develop a signup page page, in which I want add Name,email and password fields.If email already exists It should return error message.For that I have developed the following code.But It shows the error that *SyntaxError at / invalid syntax (views.py, line 19) and some more And here is my code forms.py* from django import forms from django.conf import settings from django.contrib.auth.models import User User=get_user_model class UserLoginForm(forms.Form): email=forms.EmailField(label='Email',max_length=254) password = forms.CharField(label='Password', widget=forms.PasswordInput()) def clean(self,*args,**kwargs): email=self.self.cleaned_data.get("email") password=self.cleaned_data.get("password") if email and password: user=authenticate(email=email,password=password) if not user: raise forms.ValidationError("This email id is not registered") if not user.check_password(password): raise forms.ValidationError("Incorrect password") return super(UserLoginForm,self).clean(*args,**kwargs) class RegistrationForm(forms.ModelForm): error_messages = { 'duplicate_emailid': "This email id is already exists.", 'duplicate_mobile': "This mobile no is already exists.", 'password_mismatch': "The two password fields didn't match.", 'too_short': "Passwords must be at least 6 characters long.", } username= forms.CharField(label='Username', max_length=30) email = forms.EmailField(label='Email address',max_length=254) mobile =forms.CharField(label='Mobile No',max_length=10) password = forms.CharField(label='Password', widget=forms.PasswordInput()) confirm_password = forms.CharField(label='Confirm Password', widget=forms.PasswordInput()) class Meta: model = User fields = ['username', 'email', 'mobile', 'password','confirm_password'] def username(self): username=self.cleaned_data.get("username") if username is None: msg="Plese Enter the User name" raise forms.ValidationError(msg) return username def clean_password(self): password = self.cleaned_data.get("password") if len(password) < 6: raise forms.ValidationError( self.error_messages['too_short'], ) return … -
Django template image.path.url does not work
I have a model with an ImageField called photo, but the html template gets an empty string when I use photo.path.url. This is the model: class Photograph(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT, related_name='photos_of_user') photo = models.ImageField() album = models.ForeignKey('Album', on_delete=models.CASCADE, related_name='photos_of_album') description = models.CharField(max_length=256) def __str__(self): return self.description This function returns the context I send to the template: def populate_with_album_content(self, album_pk): album = Album.objects.get(id=album_pk) photos = album.photos_of_album.all() return { 'album': album, 'photos': photos } And this is the html template: {% for photo in photos %} <div class="col-md-55"> <div class="thumbnail"> <div class="image view view-first"> <img style="width: 100%; display: block;" src="{{photo.photo.path.url}}" alt="image" /> <div class="mask"> <p>Your Text</p> <div class="tools tools-bottom"> <a href="#"><i class="fa fa-link"></i></a> <a href="#"><i class="fa fa-pencil"></i></a> <a href="#"><i class="fa fa-times"></i></a> </div> </div> </div> <div class="caption"> <p>{{ photo.description }}</p> </div> </div> </div> {% endfor %} I know urls are well configured because I can see the pictures in the admin page, but, when I view the resulting page source, I can see that src are equal to empty strings. -
Albums dont show information
I'm watching a tutorial on Django and I've been following along but I've noticed small differences between my Django and his, this all might be because I have the current patch and he has the 2016 version. The problem is that I've been trying to focus on the music app of the project. But whenever I create details of the album such as artist, album_name, genre I then save them in the shell. To then check I reopen the shell and type Album.objects.all() and get four unspecified objects. <QuerySet [<Album: Album object (1)>, <Album: Album object (2)>, <Album: Album object (3)>, <Album: Album object (4)>]> I wrote this line in the models.py file to no avail from django.db import models # RED pk 1 class Album(models.Model): artist = models.CharField(max_length=100) album_title = models.CharField(max_length=250) genre = models.CharField(max_length=50) album_logo = models.CharField(max_length=1000) def __str__(self): return self.album_title + ' - ' + self.artist # RED fk 1 class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) -
AttributeError: type object 'User' has no attribute 'name'
I’m new with graphene and I have this: from django.contrib.auth.models import User class UserType(DjangoObjectType): class Meta: model = User Basically, using Django’s User class is giving me this error, because before using the django User class, I was using my own User definition and it worked. Why using the User class from the django authentication framework is giving me the error mentioned in the title: File “/usr/local/lib/python3.6/site-packages/graphql/type/typemap.py”, line 60, in reducer if type.name in map: AttributeError: type object ‘User’ has no attribute ‘name’ Am I missing something? Regards PD: I’m using Django 2.0.4 -
How to use pillow in python to compress image
How can I get the image uploaded from the client side in django python views.py ,resize it using pillow and save it inside my database. Code Snipper needed..Please I will be very grateful -
Django how to GET value from template table?
I am trying to use values in a table that has been populated from a queryset to load their associated objects in a modal. Here is a snippet of the code that populates the table: {% for rec in accounts %} <tr> <td class="text-center"> <input type="button" data-toggle="modal" href="#accountModal" class="document-link btn btn-primary" value="{{rec.subscriber_fields.internal_id}}" > </td> <td>{{rec.accname}}</td> <td>{{rec.subscriber_fields.custom_1}}</td> <td>{{rec.acc_county}}</td> <td>{{rec.acc_state}}</td> <td>{{rec.subscriber_fields.custom_2}}</td> <td>{{rec.uploaded_on}}</td> </tr> {%endfor%} What I'm hoping to achieve is: click on the button and pass interna_id to the views.py use internal_id to get the object it's associated with instantiate the form in the modal with the object's info to edit How can this be done? It took me a while to realize that I can't GET/POST from a table like I would a form so I'm really stuck. I'm using function based views. TIA -
how do you send emails with django-amazon-ses
I have believe follow the setup instructions in django-amazon-ses https://pypi.python.org/pypi/django-amazon-ses/1.0.0 But how do I actually send emails using AWS SES with django-amazon-ses ? I only see signals (pre_send and post_send), but what is the method to actually send out the email ? Is there further configurations like subject, body, etc ? -
Toggle javascript debug in Django template
I am working on the javascript side of a Django project and my javascript functions output some text to the console so that I can debug more easily. My javascript files look like the following: (function(nameSpace, $, undefined ) { var debug = true; nameSpace.foo = function() { if (debug) { console.log('foo was there') } }; }(window.nameSpace = window.nameSpace || {}, jQuery )); I thought that it would be preferable to toggle off this output in production but I don't want to change each javascript file. So I thought I would create a context_processor to pass the value of settings.DEBUG to my base template. Now I have in my base.html: <html> <head> ... <script> var debug = {{ DEBUG }}; </script> </head> ... </html> and my javascript files have var debug = window.debug instead of a hardcoded boolean. Looking back into this I am wondering if this is safe. I presume someone could easily temper with the window.debug variable, which is fine as long as the console output doesn't leak security information like csrf tokens for example. I am not a security expert but I feel something a bit slippery here. Is my current idea safe? And if not how … -
Django Form - Select a valid choice. is not one of the available choices
Django Form - Select a valid choice. is not one of the available choices. Would anyone know where I'm going wrong? The problem occurs when in form validation. View def get(self, request): campo = get_object_or_404(campo, User_id=request.user.id) form = Form(request.POST, campo=campo) return render(request, 'create.html', {'form':form}) def post(self, request): form = Form(request.POST) if form.is_valid(): form.save() form = Form() return render(request, 'create.html', {'form':form, 'mensagem': 'Created.'}) else: form = form return render(request, 'create.html', {'form':form}) Model class Vist(models.Model): infObs = models.CharField(max_length=255) infData = models.DateField() Assoc = models.OneToOneField(Assoc, on_delete=models.CASCADE) Colab = models.ForeignKey(Colab, on_delete=models.CASCADE) Form class Form(forms.ModelForm): infObs = forms.CharField(label='Obs', max_length=255, required=False, widget=forms.Textarea(attrs={'placeholder': 'Obs', 'class': 'form-control'})) infData = forms.CharField(label='Data', widget=forms.TextInput(attrs={'placeholder': 'Data', 'class': 'single-daterange form-control'})) Assoc = forms.ModelChoiceField(queryset= None, widget=forms.Select(attrs={'placeholder': 'Assoc', 'class': 'form-control'})) Colab = forms.ModelChoiceField(queryset= None, widget=forms.Select(attrs={'placeholder': 'Colab', 'class': 'form-control'})) class Meta: model = Vist fields = ('infData','infObs', 'Assoc', 'Colab') def __init__(self, *args, **kwargs): self.campo = kwargs.pop('assoc', None) super(Form, self).__init__(*args, **kwargs) self.fields['Assoc'].queryset = Assoc.objects.filter(Assoc=self.campo) self.fields['Colab'].queryset = Colab.objects.filter(Colab=self.campo) -
django and ajax without jquery
I am trying to submit a form using ajax to django view but without jquery, and i am not able to get through few things. I am unable to send formData to django via ajax Also unable to check if the request is made via ajax or not (request.is_ajax()) I am using core Javascript for this functionality so any help will be appreciated. Views.py def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): if request.is_ajax(): # form is submited via ajax else: # error submitting the form via ajax else: return JsonResponse({'error':'There was an error'}) else: form = RegisterForm() context = { 'form' : form } return render(request, 'users/register.html', context) AJAX function _(e){ return document.getElementById(e); }; function getCookie(name){ var cookieValue = null; if(document.cookie){ var cookies = document.cookie.split(';'); for(var i = 0; i < cookies.length; i++){ cookie = cookies[i].trim(); if(cookie.substring(0, name.length + 1) == (name + '=')){ cookieValue = decodeURIComponent(cookie.substring(name.length+1)); break; }; }; }; return cookieValue; }; var btn = _('formBtn'); btn.addEventListener('click', function(e){ e.preventDefault(); var ajax = new XMLHttpRequest(); var fname = _('id_first_name').value; var lname = _('id_last_name').value; var email = _('id_email').value; var password = _('id_password').value; var csrfCookie = getCookie('csrftoken'); // formData not working ajax.onreadystatechange = function(){ if(this.readyState == 4 … -
Why to use {%url ....%} with slug?
I'm new in Django and making a simple blog to improve my skills. I couldn't understand the purpose of using {% url XXX %} with slug.More precisely; <a href ="{% url 'theview' post.slug%}"> As i know, url tag above will map the link to view function named 'theview'. And also there is a regular expression filter on url.py to catch clicked link and match it to the appropriate view function. Then why we use {%url%} although there is a filter to notice if the link is slug or not? Isn't it enough to create link like; <a href="{{post.slug}}"> -
django filter not working properly with custom added field
I have created a django admin view with list_display and custom created filter using list_filter in a Django project. Problem: filter is displaying fine for the 'All' selection but not for the values ('Yes', 'No'). It gives the following error when click the filter value. django.core.exceptions.FieldError: Cannot resolve keyword 'IsWithinRange' into field. Choices are: date_created, id, predicted_result, user_question Code as follows: class IsWithinRangeFilter(admin.SimpleListFilter): title = 'Is Within Range' parameter_name = 'IsWithinRange' def lookups(self, request, model_admin): return ( ('Yes', 'Yes'), ('No', 'No'), ) def queryset(self, request, queryset): value = self.value() logger.info('value :{}\n' .format(value)) if value == 'Yes': return queryset.filter(IsWithinRange='Yes') elif value == 'No': return queryset.filter(IsWithinRange='No') return queryset class CoreLogAdmin(admin.ModelAdmin): readonly_fields = ['date_created'] list_display = ('user_question', '_predicted_result', 'date_created', 'IsWithinRange') list_filter = (IsWithinRangeFilter,) #without this system works fine def IsWithinRange(self, row): """showing user questions only within score range (0.5~0.8)""" ... score = <some value extract from row and then cast it to float value> fscore = float(score) if fscore >= 0.5 and fscore < 0.8: return 'Yes' else: return 'No' ※without the filter it works fine. There are many questions relating to this kind of problems but neither of one worked for me -
Can't sync Elasticsearch-dsl with ManyToMany through object in Django
I'm working on a Django Rest Framework project. I use Elasticsearch through elasticsearch-dsl.py, django-elasticsearch-dsl-drf. I don't know why using Django signal in this way failed to sync elasticsearch and my QuestionSummary manytomany object: My models: class Summary(models.Model): url = models.CharField(max_length=255, unique=True) created_at = models.DateTimeField(auto_now_add=True) html_text = models.TextField(blank=True, unique=True) url_local_path = models.CharField(max_length=255) validated = models.BooleanField(default=False) cover_image = models.CharField(max_length=255) tag_category = models.ManyToManyField('TagCategory', default=[]) user_profiles = models.ManyToManyField('UserProfile', through='UserProfileSummary') questions = models.ManyToManyField('Question', through='QuestionSummary', through_fields=('summary', 'question'),) def __str__(self): return self.html_text class Meta: verbose_name_plural = "Summaries" @property def null_field_indexing(self): """null_field for indexing. Used in Elasticsearch indexing/tests of `isnull` functional filter. """ return None class Question(models.Model): title = models.CharField(max_length=255, unique=True) created_at = models.DateTimeField(auto_now_add=True) score = models.FloatField(default=0) def __str__(self): return self.title class QuestionSummary(models.Model): """Manytomany table""" # ToDo: field modified_by (and tracking the history) and created_by is_summary_author = models.BooleanField(default=False) is_question_author = models.BooleanField(default=False) last_modified_date = models.DateTimeField(auto_now_add=True) question = models.ForeignKey('Question', on_delete=models.CASCADE) summary = models.ForeignKey('Summary', on_delete=models.CASCADE) main_question = models.BooleanField(default=False) class Meta: verbose_name_plural = "Question summaries" def __str__(self): return "{} --- {}".format( self.question.title, self.summary.url ) Signal.py from django.db.models.signals import post_save, post_delete, m2m_changed from django.dispatch import receiver from django_elasticsearch_dsl.registries import registry __all__ = ( 'update_document', 'delete_document', ) @receiver(post_save) def update_document(sender, **kwargs): app_label = sender._meta.app_label model_name = sender._meta.model_name instance = kwargs['instance'] print("EDGAR app_label ", app_label) … -
Django doesn't render 404 page when passing to nginx
I want to show Django custom 404 page by nginx when passing url not exists. But It seems like the nginx simply show the 404 page without Django rendering. How could I fix it. Here are my Django and nginx setting. In myblog/urls.py urls.py handler404 = 'views.handler404' In myblog/views.py views.py def handler404(requests): return render(requests, '404.html', status=404) In templates/404.html templates/404.html {% extends "base.html" %} {% block content %} {# some 404 content #} {% endblock %} In nginx.conf nginx.conf location /404.html { alias /my/path/templates/404.html; } error_page 404 500 403 /404.html; uwsgi_intercept_errors on; And the 404 page show like this: (it's a sample) 404.page Thank you very much. -
Reject POST request if particular columns are not unique
How can I prevent a POST request from being saved if the following items: 'email', 'youtube_channel_username', 'youtube_channel_url', 'youtube_channel_title' already exist in the database? In effect, I want to add a validation step that ensures that what the user is trying to post is unique for the above-mentioned. Ideally the server should send back an error message to the user informing them that their request failed for whatsoever reason. Here is my code so far. I am not sure where to add this feature, so I would appreciate some help! serializers.py class CreatorSignupSerializer(serializers.Serializer): """ Create Creator profile """ first_name = serializers.CharField(required=True, write_only=True) last_name = serializers.CharField(required=True, write_only=True) email = serializers.CharField(required=True, write_only=True) youtube_channel_username = serializers.CharField(required=True, write_only=True) youtube_channel_url = serializers.CharField(required=True, write_only=True) youtube_channel_title = serializers.CharField(required=True, write_only=True) youtube_channel_description = serializers.CharField(required=True, write_only=True) photo = serializers.CharField(required=True, write_only=True) youtube_channel_start_date = serializers.CharField(required=True, write_only=True) keywords = serializers.CharField(required=True, write_only=True) no_of_subscribers = serializers.IntegerField(required=True, write_only=True) no_of_videos = serializers.IntegerField(required=True, write_only=True) no_of_views = serializers.IntegerField(required=True, write_only=True) no_of_likes = serializers.IntegerField(required=True, write_only=True) no_of_dislikes = serializers.IntegerField(required=True, write_only=True) location = serializers.CharField(required=True, write_only=True) avg_views = serializers.IntegerField(required=True, write_only=True) gender = serializers.IntegerField(required=True, write_only=True) password = serializers.CharField(required=True, write_only=True) class Meta: model = Creator fields = ( 'first_name', 'last_name', 'email', 'youtube_channel_username', 'youtube_channel_url', 'youtube_channel_title', 'youtube_channel_description', 'photo', 'youtube_channel_start_date', 'keywords', 'no_of_subscribers', 'no_of_videos', 'no_of_views', 'no_of_dislikes', 'no_of_likes' 'location', 'avg_views', 'gender', 'password', …