Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch error while trying to reverse url with Model Forms
I think the error has something to do with url pattern changes in django 2.0. Almost everything i found on Google uses old url patterns, so they're not helpful. ...models def get_absolute_url(self): return reverse('music:detail', kwargs={'pk':self.pk}) My urls: urlpatterns = [ #music/add/ path('add', views.AlbumCreate.as_view(), name="album-add") ] And this is the form, i don't think anything's wrong with it, because when i fill out the form itself and click submit, on the list page it shows that it's been submitted. <form action="", method="post"> -
Django edit form
I'm using Django v1.11.8 and Python 2.7.6 I got some question about edit form. Can someone explain me how to write correct edit form in Django? I'm working whole day and still got some problems... I saw lot of examples in Internet but i still do something wrong. My ModelForm looks like this: class UpdateVoteForm(ModelForm): class Meta: model = Vote fields = ['question', 'ans_a', 'ans_b', 'ans_c', 'ans_d', 'ans_e', 'ans_f', 'type', 'council', 'user', 'created_date', 'group'] view function: def update_vote_from(request, pk): vote_inst = get_object_or_404(Vote, pk = pk) if request.method == 'POST': form = UpdateVoteForm(request.POST, instance=vote_inst) if form.is_valid(): #vote_inst = form.save(commit=False) #vote_inst.created_date = datetime.date.today() form.save() return HttpResponseRedirect(reverse('voting-list')) else: form = UpdateVoteForm() return render(request, 'votes-form.html', {'form': form, 'vote_inst': vote_inst}) urls: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^votersList/$', views.VotersView.as_view(), name='voters-list'), url(r'^vote/create/$', views.add_vote_from, name='vote-create'), url(r'^vote/(?P<pk>\d+)/edit/$', views.update_vote_from, name='vote-update'), ] and template: {% extends "base_generic.html" %} {% block content %} <div class="containter"> <form action="" method="post"> {% csrf_token %} <label for="user">Właściciel: </label> <select id="user" name="user"> {% for user in vote_inst.user.all %} <option value="{{ user }}"{% if vote_inst.user == user %} selected{% endif %}>{{ user }}</option> {% endfor %} </select> <label for="user">Kto: </label> <input id="user" type="text" name="user" value="{{ vote_inst.user }}"> <label for="question">Pytanie: </label> <textarea id="question" name="question" style="height:70px" value="{{ vote_inst.question.value }}"></textarea> … -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Django 2.0 Migration
I'm having trouble with django. I'm starting a new project with only a single app, and when I'm adding one model, I can't migrate it. Error message when migrate (or makemigrations) : (MapEnv) C:\Users\rossi\Desktop\Imp!act\MapEnv\ActorMap>django-admin migrate Traceback (most recent call last): File "c:\users\rossi\appdata\local\programs\python\python36-32\Lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\rossi\appdata\local\programs\python\python36-32\Lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\rossi\Desktop\Imp!act\MapEnv\Scripts\django-admin.exe\__main__.py", line 9, in <module> File "c:\users\rossi\desktop\imp!act\mapenv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "c:\users\rossi\desktop\imp!act\mapenv\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\rossi\desktop\imp!act\mapenv\lib\site-packages\django\core\management\__init__.py", line 216, in fetch_command klass = load_command_class(app_name, subcommand) File "c:\users\rossi\desktop\imp!act\mapenv\lib\site-packages\django\core\management\__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "c:\users\rossi\desktop\imp!act\mapenv\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "c:\users\rossi\desktop\imp!act\mapenv\lib\site-packages\django\core\management\commands\migrate.py", line 12, in <module> from django.db.migrations.autodetector import MigrationAutodetector File "c:\users\rossi\desktop\imp!act\mapenv\lib\site-packages\django\db\migrations\autodetector.py", line 11, in <module> from django.db.migrations.questioner import MigrationQuestioner File "c:\users\rossi\desktop\imp!act\mapenv\lib\site-packages\django\db\migrations\questioner.py", line 9, in <module> from .loader import MigrationLoader File "c:\users\rossi\desktop\imp!act\mapenv\lib\site-packages\django\db\migrations\loader.py", line 8, in <module> from django.db.migrations.recorder import MigrationRecorder File "c:\users\rossi\desktop\imp!act\mapenv\lib\site-packages\django\db\migrations\recorder.py", line 9, in <module> class MigrationRecorder: File "c:\users\rossi\desktop\imp!act\mapenv\lib\site-packages\django\db\migrations\recorder.py", … -
How do I use a context from a loaded view to export a csv file in django?
I have written a Django app that does a database query and displays the data in a table. I want to create a link at the bottom of the page that allows the user to export this data to a csv file. So basically I want to take the query object from the original view and pass that to the csv export view. How do I do this? -
I try to check a variable for callable in Python 3.x
I try to check if name is callable. From john I expect "I'm a callable" and from kate "I'm not a callable". But I get "I'm not a callable" twice def name(first_name, last_name): return first_name+' '+last_name class Person: def __init__(self, name): self.name = name if callable(self.name): print("I'm a callable") else: print("I'm not a callable") john = Person( name('John', 'Green')) kate = Person("Kate") The result is: I'm not a callable I'm not a callable -
i im new on django framework and im having touble running the command 'python3 manage.py migrate'
Im using ubuntu 16.04 and im trying to learn django and im installed it in my virtual environment and and named it as myenv and i started a project name mysite when i tried to migrate the manage.py file it kept saying sqlite3 is not installed and i installed it but it is saying the same error as i rum python3 manage.py migrate it says "ModuleNotFoundError: No module named '_sqlite3'" `and i installed sqlite using the commands below sudo add-apt-repository ppa:jonathonf/backports sudo apt-get upgrade sudo apt-get install aqlite3 but it didnt work so pleaase help me??? -
Django throws 'Direct assignment to the forward side of a many-to-many set is prohibited.' error
I have two models in Django Users and Contexts.I have defined the models as below class User(models.Model): userId = models.PositiveIntegerField(null = False) pic = models.ImageField(upload_to=getUserImagePath,null=True) Email = models.EmailField(null = True) class Contexts(models.Model): context_name = models.CharField(max_length=50) context_description = models.TextField() context_priority = models.CharField(max_length=1) users = models.ManyToManyField(User, related_name='context_users') Now I get a POST request which contains the below JSON { "user" : 12, "action" : "add", "context_name": "Network debug", "context description" : "Group for debugging network issues", "context_priority": "L" } I want to create a record in the Contexts table.Below is what I am trying to do from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse import json from .models import * import json @csrf_exempt def context_operation(request): if request.method == "POST": user_request = json.loads(request.body.decode('utf-8')) try: if user_request.get("action") == "add": conv = Contexts.objects.create( context_name=user_request.get("context_name"), context_description=user_request.get("context_description"), context_priority=user_request.get("context_priority"), users=user_request.get("user") ) conv.save() except Exception as e: print("Context saving exception", e) return HttpResponse(0) return HttpResponse(1) Here I am trying to add a context based on the action field in the JSON request.As you can see, in the Contexts model, the field users has many to many relation with the User model.But when I try to save the values to the Contexts table, I recieve the … -
Django dynamic categories
I have the following task: Create a blog where the create blog post form looks like the following(in django 1.8.17): There is a title, content char/textfield There is a category field which is a list, and you have to choose one If you choose "Others" a CharField appear (or it can be exists before that, but i need to not allowed to write inside this form When I choose "Others" and fill the charfield, it create a new Category which I can choose later. My models.py now: from __future__ import unicode_literals from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.core.urlresolvers import reverse class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Post(models.Model): category = models.OneToOneField(Category) title = models.CharField(max_length=255) content = models.TextField() created = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) def __unicode__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): return reverse("detail", kwargs={"id" : self.id}) That's what I got now. It looks like in the form: https://i.imgur.com/sOsUZsR.png -
Django make Boolean Field required for CreateView
I have a model where I need to user to tick the Checkbox before proceeding. If the checkbox is not checked the browser should not allow the user to continue with form submission (simple, right?) I'm using a CreateView to handle this model and ... it doesn't work - one can submit the form without ticking the checkbox (the patient_agreement BooleanField). How to make this check-box required for this CreateView CBV? Here's my model: class Patient(models.Model): name = models.CharField(max_length=30, blank=False, verbose_name=_('Name')) surname = models.CharField(max_length=70, blank=False, verbose_name=_("Surname")) patient_agreement = models.BooleanField( blank=False, verbose_name=_("Patient has been notified about GDPR and his right to his data"), help_text=_("Mark only if you have informed the patient about his rights in the GDPR context"), ) And this is my view: class NewPatientFormView(LoginRequiredMixin, CreateView): model = Patient fields = ['name', 'surname','patient_agreement'] def form_valid(self, form): self.object = form.save(commit=False) self.object.created_by_user = self.request.user # self.object.save() return super().form_valid(form) How to make the checkbox required before the form can be submitted?! -
Django rest and axios post
So to I'm trying to submit data to my backend django rest. In my backend, If I manually type in the params like so http://127.0.0.1:8000/api/comments/create/?type=post&slug=first-post the data gets submitted and the comment gets created. I'm using react/redux as a my front end with axios and I've setup my request to submit data the same way. Passing in data, params, etc like so, export const createComment = (comment) => { return dispatch => { return axios.post(`http://127.0.0.1:8000/api/comments/create/`,qs.stringify({ content: comment.content }), { params: { type: comment.type, slug: comment.slug, parent_id: comment.parent_id }, xsrfHeaderName: "X-CSRFToken", } ).then((response) => { console.log(response); }).catch((err) => { console.log(err.message); }) } } This is the error I keep getting, xhr.js:178 POST http://127.0.0.1:8000/api/comments/create/?type=post&slug=second-post 500 (Internal Server Error) Can't understand how this continues to be a server error yet when I submit the comment through my django rest the comment successfully goes through. I'm new to this so any help would be appreciated. -
What is Django's default cache name prefix for session?
In my Django project I want to use one cache backend to store session data and any other cache. So my questions are: What is default name prefix for cached sessions? I need to know it to make sure, it will not intersect with names of other cached variables. Is it a good idea to store sesions with other cache? Maybe I should use different memcached/redis instances? -
..wsgi.py cannot be loaded as a Python module - Ubuntu 16.04.4, Django 1.9.7, Python 2.7.12
I performed a server update and this has broken the python-django website. A number off issues have been fixed but I am still left with a problem in that the server just shows the directory contents.'wsgi.py' fails to load correctly. Looking at the error log, it appears that it fails on trying to load wsgi.py. "Target WSGI script '/home/user/website.company.com/company/company/wsgi.py' cannot be loaded as Python module." I have spent a day on it and am unable to get past this point. Can anyone see why this should be happening? details++++++++++++++++++++++++++ Ubuntu 16.04 Apache 2.4.18 python 2.7.12 django 1.9.7 /etc/apache2/sites-available/000-default.conf ServerName website.crytallise.com ServerAdmin webmaster@company.com ServerAlias website.company.com DocumentRoot /home/user/website.company.com/company/company WSGIDaemonProcess company python-path=/home/user/website.company.com/company/company:python-path=/home/user/.virtualenvs/compweb/lib/python2.7/site-packages WSGIProcessGroup company WSGIScriptAlias / /home/user/website.company.com/company/company/wsgi.py Alias /static /home/user/website.company.com/static <Directory /home/user/website.company.com/static> Require all granted </Directory> <Directory /home/user/website.company.com/company/company/static> Require all granted </Directory> <Directory /home/user/website.company.com/company/company/> Options Indexes FollowSymLinks MultiViews AllowOverride None Require all granted <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined /home/user/website.company.com/company/company.wsgi.py import os, sys sys.path.append("/home/user/website.company.com/company") sys.path.append("/home/.virtualenvs/compweb/lib/python2.7/site-packages") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "company.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() /var/log/apache2/error.log [Sun Jun 24 14:42:08.547069 2018] [wsgi:error] [pid 3794:tid 140228412733184] [remote 00.111.222.33:12345] mod_wsgi (pid=3794): Target WSGI script '/home/user/website.company.com/company/company/wsgi.py' cannot be loaded as Python module. [Sun Jun 24 14:42:08.547117 2018] [wsgi:error] [pid 3794:tid 140228412733184] … -
Why do I get different results?
I use Django 2.x. I try to upload the file "image.png". models.py: def file_name(instance, filename): return os.path.join('uploads', 'my_name.png') class FileForm(models.Model): file = models.FileField(upload_to=file_name, null=True) As a result image.png is uploads into "uploads" folder with new filename "my_name.png" (..uploads/my_name.png) But when I do this: (I just take os.path.join('uploads', 'my_name.png') and put instead file_name) class FileForm(models.Model): file = models.FileField(upload_to=os.path.join('uploads', 'my_name.png'), null=True) The result is image.png is just uploads into "uploads/my_name.png" folder (...uploads/my_name.png/image.png) Why this happen? -
Django admin to add fields automatically from javascript function
I have a signup form that works great. One feature of it is users can press "Add more +" and have more identical "instrument" and "level" select fields created. The django user admin only shows the first "instrument"/"level" field under "Experience" and not the further ones created from the javascript function. How can I adjust my django admin model to create further fields when the javascript function is called? I appreciate any help I get. HTML <div> <div class="items"> <div id="ins"> <div> {{ form.instrument }} </div> <div> {{ form.level }} </div> </div> </div> <div id="add_more"> <button type="button" class="no_link" onclick="add_instrument()">Add more +</button> </div> </div> Javascript var i = 0; var original = document.getElementById('ins'); function add_instrument() { var clone = original.cloneNode(true); clone.id = "ins" + ++i; original.parentNode.appendChild(clone); } admin.py fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name', 'avatar', 'country', 'child_first_name')}), ('Experience', {'fields': ('instrument', 'level')}), ('Permissions', {'fields': ('student', 'parent', 'teacher', 'admin', 'staff', 'active')}), ) -
Django CSRF token failure risk
On our production server, periodically we suffer from many CSRF token failures. The site does work fine for the rest, and I am aware CSRF failures may be user-side errors. However, for example this morning we received a flood of new failures, so we want to exclude any other possibilities. An example failure mail today: { "GET": {}, "COOKIES": {}, "ERROR": "Referer checking failed - no Referer.", "USER": "AnonymousUser", "META": { "REMOTE_ADDR": "127.0.0.1", "mod_wsgi.version": "(4, 5, 20)", "DOCUMENT_ROOT": "/usr/local/apache2/htdocs", "SERVER_ADDR": "127.0.0.1", "HTTP_ACCEPT_ENCODING": "gzip, deflate, br", "wsgi.multithread": "True", "HTTP_FORWARDED_REQUEST_URI": "/", "CONTEXT_DOCUMENT_ROOT": "/usr/local/apache2/htdocs", "wsgi.file_wrapper": "<class 'mod_wsgi.FileWrapper'>", "mod_wsgi.path_info": "/", "HTTP_ORIGIN": "chrome-extension://aegnopegbbhjeeiganiajffnalhlkkjb", (...) }, "POST": {} } Especially the HTTP_ORIGIN looks "interesting": why is this Chrome extension scraping/bullying us? So essentially: Do we need to be worried about this? Thanks! -
Using Ajax and CreateView to return a value from a dropdown list
I am trying to retrieve the value of the selected item from a dropdown list at CreateView using Ajax call. For example, when an item has been selected from the dropdown menu, I want all of the related information of that item to be automatically displayed on the template. But I am not sure why I won't be able to return the value of the selected item (which will be needed for filtering) at CreateView with the following codes: models.py class Model_Item(models.Model): item_name = models.CharField(max_length = 20) item_description = models.CharField(max_length = 100) item_origin = models.CharField(max_length = 50) # and many more fields def __unicode__(self): return self.item_name class Model_Cart(models.Model): item = models.ForeignKey(Model_Item) customer_name = models.CharField(max_length = 50) html <form method = "POST"> {% csrf_token %} <table id = "table_01"> <tr> <th>Item name</th> <td>{{ form.item}}</td> </tr> </table> <div> preview the description, origin and other fields of the choosen item here --> </div> <table id = "table_02"> <tr> <th>Customer's name</th> <td>{{ form.customer_name}}</td> </tr> </table> <input type = "submit" value = "Submit"> </form> ajax $(document).ready(function(){ $("#id_item").change(function(){ var item_selection = $(this).val(); $.ajax({ type: "GET", data: {"item_name_id": item_selection} }); }); }); views.py class View_Cart(CreateView): form_class = Form_Cart def get_queryset(self): item_name_id = self.request.GET.get("item_name_id") print item_name_id # <------ … -
issue with django authenticate() :in my django app created a signup function through forms but i dont know why i couldnt authenticate any user
here is the code of my forms.py from django import forms class LoginForm(forms.Form): username=forms.CharField() password=forms.CharField(widget=forms.PasswordInput) views.py from django.shortcuts import render from django.shortcuts import render from django.contrib.auth import authenticate,login from .forms import LoginForm from django.http import HttpResponse # Create your views here. def user_login(request): if request.method=='POST': form = LoginForm(request.POST) if form.is_valid(): cd=form.cleaned_data username=cd['username'] password=cd['password'] print(username) print(password) print(cd) user = authenticate(username=username,password=password) print(user) if user is not None: if user.is_active: login(request,user) return HttpResponse('login succesfull') else: return HttpResponse('disabled account ') else: return HttpResponse('invalid login') else: return HttpResponse('invalid form') else: form =LoginForm() return render(request,'accounts/login.html',{'form':form}) but whenever i use that signup form there is a invalid login HttpResonse and when i tried to print the values of username and password i could see my credentials in the terminal but i couldn't authenticate the user any kind of support is appreciated -
getting POST data django
I have implemented payment gateway using form (with post method), and they send me a payment verification after all to url I gave them. How could I receive these data and check, next send to them as verified. Should I use special view to that url or sth? Actually they only send "data" like merchant id, currency etc. there. Give me a hint at least. -
AssertionError: Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set `.queryset` or have a `.get_queryset()` method
I am writing a simple Django web application and I am trying implement REST API. I use django-rest-framework package. I use Python 3.x on Debian sid GNU/Linux. However, when I try access REST API through browser I'm getting error: Traceback (most recent call last): File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 471, in dispatch self.initial(request, *args, **kwargs) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 389, in initial self.check_permissions(request) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/views.py", line 322, in check_permissions if not permission.has_permission(request, self): File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/permissions.py", line 141, in has_permission queryset = self._queryset(view) File "/home/lynx/PycharmProjects/hello_world/venv/lib/python3.6/site-packages/rest_framework/permissions.py", line 121, in _queryset ).format(self.__class__.__name__) AssertionError: Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set `.queryset` or have a `.get_queryset()` method. [24/Jun/2018 14:34:41] "GET /articles/ HTTP/1.1" 500 101619 Here's my code: news/serializers.py: from rest_framework import serializers from .models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = '__all__' news/views.py: from django.shortcuts … -
CSRF verification failed when using jQuery-csrf
I am trying to issue a post request using ajax <div> <h4>Comments</h4> <form action="#" method="post"> <textarea class="form-control" rows="5" name='comment' id="commentContent"></textarea> <br> <button class="btn btn-primary" id="commentBtn">Post Your Comment</button> </form> </div> </div><!--/class="col-xs-8 col-md-8">--> </div><!-- row --> <script src="/static/js/jquery-3.3.1.js"></script> <script src="/static/js/jquery-csrf.js"></script> <script> $(document).ready(function () { var article_id = {{ article.id }}; var num_pages = {{ page.num_pages }}; $('#commentBtn').on('click', function (e) { e.preventDefault(); alert('clicked'); var comment = $('#commentContent').val(); var param = { "article_id": article.id, "content": comment, }; $.post('/article/comment/create/', param, function (data) { var ret = JSON.parse(data); if ((ret['status'] = 'ok')) { $('#commentConent').val(''); window.location.href = '/article/detail/{{ article.id }}?page_number=' + num_pages; } else { alert(ret['msg']); } }); }); }); </script> It throw 'forbidden' error after submit the form Forbidden (403) CSRF verification failed. Request aborted. I tried different versions of jQuery, the problem stayed unsolved. The jquery-csrf.js is placed correctly according to the official documentation and was successfully loaded by the server" [24/Jun/2018 21:58:55] "GET /static/js/jquery-3.3.1.js HTTP/1.1" 304 0 [24/Jun/2018 21:58:55] "GET /static/js/jquery-csrf.js HTTP/1.1" 304 0 the jquery-csrf.js // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this … -
How can I do a join on 3 tables in Django Rest Framework (only primary keys). Please help me with this
I have three models each contains a primary key. How can I perform join operation using rest framework in django? -
Django field validation for non-empty values
I have a script in my Django app that is used to scrape some data from the web and save the results in the database using my Django models. For example, I have the following model: class WebPage(): diff = models.TextField() url = models.TextField() At first, I assumed since blank defaults to False, I wouldn't be able to accidentally save a model that is missing a url or diff. This is not true however since the database happily stores an underfilled model: I tried to define some validators on the fields: diff = models.TextField(validators=[MinLengthValidator(1)]) url = models.TextField(validators=[URLValidator()]) but that didn't work because apparently full_clean() would have to be called before each save, e.g.: from django.db.models.signals import pre_save def validate_model(sender, **kwargs): if 'raw' in kwargs and not kwargs['raw']: kwargs['instance'].full_clean() pre_save.connect(validate_model, dispatch_uid='validate_models') What is the best way to validate this data? I'm not exposing it via any forms. This being Django, I'm surprised there isn't any simple way to disallow empty values in fields. Am I missing something? -
Django Channels pip install fails
When running pip install -U channels command on Centos7 I get the following error: Could not find a version that satisfies the requirement twisted>=17.5 (from daphne~=2.2->channels) (from versions: ) No matching distribution found for twisted>=17.5 (from daphne~=2.2->channels) I have a virtual env in my localhost and I am trying to install all dependancies from my requirements.txt file. pip freeze gives the following output: aioredis==1.1.0 asgiref==2.3.2 asn1crypto==0.24.0 async-timeout==2.0.1 attrs==17.4.0 autobahn==18.4.1 Automat==0.6.0 cffi==1.11.5 configparser==3.5.0 constantly==15.1.0 cryptography==2.2.2 Django==2.0.2 django-bootstrap3==9.1.0 django-modalview==0.1.5 h2==3.0.1 hiredis==0.2.0 hpack==3.0.0 hyperframe==5.1.0 hyperlink==18.0.0 idna==2.6 incremental==17.5.0 msgpack==0.5.6 msgpack-python==0.5.6 Pillow==5.0.0 priority==1.3.0 pyasn1==0.4.2 pyasn1-modules==0.2.1 pycparser==2.18 PyMySQL==0.8.1 pyOpenSSL==17.5.0 pytz==2018.3 redis==2.10.6 service-identity==17.0.0 six==1.11.0 txaio==2.10.0 zope.interface==4.4.3 -
Insertions of same row is happening and how to reject an insertion if iti is already present in DB Django-rest-framework,PostgreSQL
I am trying to create a backend for social app. While inserting friend relation in database, It is also inserting relations already present in DB. Example: User 1 and User 2 are already friends So,The row in DB: 1,2,3,date Now the DB shouldn't accept the same row anymore but it is accepting !!! How to reject or restrict multiple insertions of same rows. My View: class Friendship(viewsets.ModelViewSet): """"Handles Creating Friendship""" authentication_classes = (TokenAuthentication,) serializer_class = UserFriendSerializer permission_classes = (permissions.FriendCreate,IsAuthenticated) queryset = Friends.objects.all() def perform_create(self, serializer): """"Sets the friendship status to user""" serializer.save(username = self.request.user) My serializer: class UserFriendSerializer(serializers.ModelSerializer): """"A serializer for adding and removing Friends""" class Meta: model = Friends fields = ('user_id_1','user_id_2','status',) def create(self, validated_data): """"Create user friendship with lesser id in first column""" friend_1 = validated_data['user_id_1'] friend_2 = validated_data['user_id_2'] if friend_1.pk > friend_2.pk: temp = friend_1 friend_1 = friend_2 friend_2 = temp friend = Friends( user_id_1 = friend_1, user_id_2 = friend_2, status = validated_data['status'], ) friend.save() return friend My Model: class Friends(models.Model): '''''Friend's or Relationship between user's and their relation status''' user_id_1 = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user_a') user_id_2 = models.ForeignKey(User,on_delete=models.CASCADE,related_name='user_b') status = models.PositiveSmallIntegerField() friends_on = models.DateTimeField(auto_now_add=True,auto_now=False) def __str__(self): """"Returns model as a String""" return str(self.user_id_1) class Meta: verbose_name_plural = "Friends" Any … -
Django Rest Framework categories and childs in one model
I have a very simple ( with a first look) problem. Case - A product can be sold in a several places(shops), and every product can be represented in a single shop with a different categories and sub categories ( That is why category linked via ForeignKey with Assortment twice). So here is My Assortment model, with several FKs. class Assortment(models.Model): category = models.ForeignKey('category.Category', null=True, blank=True, default=None,related_name='assortment_child') parent_category = models.ForeignKey('category.Category', null=True, blank=True, default=None,related_name='assortment_parent') product = models.ForeignKey(Product) shop = models.ForeignKey(Shop) View, based on rest_framework.generics.ListAPIView class InstitutionTreeCategories(generics.ListAPIView): """Resource to get shop's tree of categories.""" serializer_class = serializers.InstitutionCategoriesSerializer def get_queryset(self): shop = self.get_shop() return Category.objects.filter(assortment_parent__shop=shop).distinct() And finally, serializers class CategoryListSerializer(serializers.ModelSerializer): class Meta: """Meta class.""" model = Category fields = ('id', 'name', 'image') class CategoriesTreeSerializer(CategoryListSerializer): # childs = CategoryListSerializer(many=True, source='assortment_child__parent_category') childs = serializers.SerializerMethodField() class Meta(CategoryListSerializer.Meta): """Meta class.""" fields = ('id', 'name', 'image', 'childs') def get_childs(self, obj): qs = Category.objects.filter(assortment_child__parent_category=obj.id).distinct() return CategoryListSerializer(qs, many=True, context=self.context).data And i need to show Category Tree for a one single shop with my API. But the problem is - If I use serializer.SerializerMethodField - it works, but too many queries (for every parent category). I tried to avoid it using 'source' option with my 'CategoryListSerializer' by I can't make it. …