Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Want to use method DELETE using ModelViewSet and routers. But Page not found, Django tried these URL patterns, in this order:
I want to allow delete and update html methods for my view set. But when I trying to lie a url prefix/pk-value I face this: Page not found (404) Request Method: GET Request URL: http://localhost/api/cutarea-dual-fca-planuse/108 Using the URLconf defined in lesoved.urls, Django tried these URL patterns, in this order: #... ^api/ ^cutarea-dual-fca-factuse/$ [name='cutarea-dual-fca-factuse-list'] ^api/ ^cutarea-dual-fca-factuse\.(?P<format>[a-z0-9]+)/?$ [name='cutarea-dual-fca-factuse-list'] ^api/ ^cutarea-dual-fca-factuse/(?P<pk>[^/.]+)/$ [name='cutarea-dual-fca-factuse-detail'] ^api/ ^cutarea-dual-fca-factuse/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='cutarea-dual-fca-factuse-detail'] ^api/ ^cutarea-dual-fca-planuse/$ [name='cutarea-dual-fca-planuse-list'] ^api/ ^cutarea-dual-fca-planuse\.(?P<format>[a-z0-9]+)/?$ [name='cutarea-dual-fca-planuse-list'] ^api/ ^cutarea-dual-fca-planuse/(?P<id_fca>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$ [name='cutarea-dual-fca-planuse-detail'] ^api/ ^cutarea-dual-fca-planuse/(?P<id_fca>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})\.(?P<format>[a-z0-9]+)/?$ [name='cutarea-dual-fca-planuse-detail'] #... So there are urls.py and views.py: #There is my views.py class DualFcaPlanUseViewSet(viewsets.ModelViewSet): authentication_classes = (CsrfExemptSessionAuthentication,) def get_queryset(self): user = self.request.user return FcaPlanUse.objects.filter(id_fca__num_of_agree__renters_id__user_key = user) def get_serializer_class(self): if self.request.method == 'GET': return FcaPlanUseSerializer if self.request.method == 'POST': return FcaPlanUsePOSTSerializer #Project urls.py from cutarea.views import * #... from rest_framework import routers router = routers.DefaultRouter() router.register(r'cutarea-dual-fca-planuse',DualFcaPlanUseViewSet, base_name='cutarea-dual-fca-planuse') #... urlpatterns = [ #... url(r'^api/', include(router.urls)), ] How to allow delete or update method, and hou to use routers for appling http methods? -
How i can load 2 forms in one page(url)?
I need load 2 forms in one page, and for mapping URL, I must add the path('',.........) for 2 forms. but how I can do that? if add path(''.....) for 2 forms, its add one of my forms not both on the same path. how I can do that? I tried this : urlpatterns=[ path('',views.register,name='register') path('',views.login,name='login') ] because I need load this 2 forms in one page in another word in index path, but when I runserver I see one of these forms, not both. -
How to check the validation of a field of each objects contained in a queryset?
I have a queryset of "Match". In "Match" model there is a boolean field and I'd like to check if this field is equal to True for each objects contained in my queryset. How can I do this ? matches = Match.objects.filter(phase=phase) models.py class Match(models.Model): isFinished = models.BooleanField(default=False) team1Win = models.BooleanField(default=False) team2Win = models.BooleanField(default=False) phase = models.ForeignKey(Phase, default=None, on_delete=models.CASCADE) teams = models.ManyToManyField(Team, default=None, blank=True) The field in question is isFinished`. -
Django ModelChoiceField queryset keeps returning same result regardless of input
I am trying to create a choicefield in a form which only contains those fields which relate to a previously selected option. So far on the site a user can select a parent option ( I Call discipline) and then submit at which time they are ask to select from a set of fields which are a subset of the selected discipline. Currently the pages all work and render except that on the second page I also get the same 6 results regardless of which discipline I select. I ran a print command and can see the objects.filter are returning the correct results but those results are not appearing in the drop down menu. I am stumped.... any suggestions? I have tried a number of online tutorials and checked several questions in stack exchange but nothing matches my issue. I am really confused how fieldOptions = Field.objects.filter(discipline_Main=discipline) print("The available fields are: %s" % fieldOptions) returns the correct results yet: field_name = forms.ModelChoiceField(queryset=Field.objects.filter(discipline_Main=disciplineID)) only ever shows the same 6 results. My Models are: class Discipline(models.Model): #This is the top level category ie: Math, physics, chemistry, biology, history, english, etc discipline_name = models.CharField(max_length=50) description_text = models.CharField(max_length=200) discipline_create_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): … -
How to get data from MLS api for property listing?
I am making a real estate project so please can you tell me what is the use of MLS Api in that project as I have to verify the property which is going to be added with MLS API Hardly find any matter which is sufficient for this -
NGINX 502 bad gateway gunicorn timeout
502 bad gateway error pops up on saving data to the db. Once the user logs into the django app (OLE 7). Data is pulled regarding that user from ldap server and saved in my local db(postgres). It worked perfectly fine on local server after configuring nginx, gunicorn once the user logs into the website instead of displaying retrieved data it shows 502 Bad gateway. I went thru a lot of stackoverflow post regarding this, some said increase the timeout, check gunicorn is running. I have already tried all this but it still wont work. nginx.conf user nginx; worker_processes 2; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } er nginx; worker_processes 2; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 300; #gzip on; upstream app_server { server 10.111.234.110:8001 fail_timeout=0; } server{ listen 80; server_name 10.111.234.110; location = /favicon.ico { access_log off; log_not_found off; } location /static/ {root /home/lisa/revcon;} location / { proxy_set_header Host $http_host; proxy_set_header Connection ""; 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/lisa/revcon/revcon.sock; … -
Why post_save signal is not working here?
I created a signal that creates profile when a user is created. Previously, the same code was working fine in other projects. Here, I don't know what I am doing wrong that it doesn't work and doesn't create profile for created users. This is the signal. @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): print(instance) if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() All the imports are done properly, and here I imported that in my app: class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals In case if you want to look at profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return "{} Profile".format(self.user.username) Since I created a signal, for all new created users it should add that default.jpg as default profile picture. But if I create a new user, login then go to profile page it shows something like this: and if I go to admin and add this profile picture manually it works fine. One final thing I added the following settings in urls.py as well: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Please help me fix it, it has been 3 hours I tried all possible ways but couldn't make … -
how to validate email properly while register and edit users in django
I am not using django default admin dashboard and i am using my own custom template for the admin.but here i got some problem while editing and updating the user.I want to make email of every user unique in the database this code in my forms.py does pretty well while adding the user but while updating it i got some problem regarding the email.Since I have done the email unique in forms.py it is giving me error while updating also.How can i update users so that the edited user can have the same email but not same as the other user's email address. forms.py class RegisterForm(UserCreationForm): def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise ValidationError('Email Already Exists') return email class Meta: model = User fields = ['username', "email", "password1", "password2",'is_superuser','is_staff','is_active'] views.py def register(request): if not request.user.is_superuser: messages.warning(request, 'Permission Denied.You have no permission to register users.') return redirect('students:home') if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() messages.success(request,'user created with username {}'.format(user.username)) return redirect('students:our_users') else: form =RegisterForm() return render(request,'students/register.html',{'form':form}) def editusers(request,id): if not request.user.is_superuser: messages.warning(request, 'Permission Denied.You have no permission to perform this action.') return redirect('students:our_users') user = User.objects.get(id=id) return render(request,'students/edit_users.html',{'user':user}) def updateusers(request,id): if not request.user.is_superuser: messages.warning(request, … -
Django rest framework quickstart tutorial error The included URLconf 'tutorial.urls'
I tried to complete the drf quickstart tutorial from https://www.django-rest-framework.org/tutorial/quickstart/ using Python 3.6.1 django-rest-framework 3.9.4 Django 2.2.1 but when I run python manage.py runserver I got an error File "E:\Dropbox\python\drf2\venv\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'tutorial.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
How to get input from a HTML form into my Python script
So guys, I am using Django right now to test some stuff out. So what I want to do is I have a HTML form which takes a input from a user, I want to pass this input to my python script to do something with this input, how do i do this? {% extends 'base.html' %} {% block content %} <h1> League of Legends Rank lookup</h1> <div id ="ranklookup"> <form name="search" action="" method="get"> Search: <input type="text" name="summoner"> <input type="submit" value="Submit"> </form> </div> {% endblock %} My Python script is rankfinder.py I want to use the value of 'summoner' in my python script to do something with this input, How do I do this in Django? -
django: Why can't I use __year lookup inside F() expression?
Suppose I have a model with two DateField's: class Event(models.Model): start_date = models.DateField() finish_date = models.DateField() This allows me to make queries that compare these fields, like ee=Event.objects.filter(finish_date=F('start_date')) and I can deal with the year of the date, like ee=Event.objects.filter(finish_date__year=2000) but when I try to use the same lookup __year inside F(), like this: ee=Event.objects.filter(finish_date__year=F('start_date__year')) , it fails: FieldError: Cannot resolve keyword 'year' into field. Join on 'start_date' not permitted. Is there any reason for such behavior, or does it look like a bug? I am using Django 1.11, and I see no such restricitions at https://docs.djangoproject.com/en/1.11/topics/db/queries/#using-f-expressions-in-filters . -
How to make triggers in backend with Django?
I am developing a personal project where teacher accounts can design their own multiple-choice exams for student accounts. One of the Exam class attributes is exam_time, an integer attribute which sets how many minutes are provided to the students when they are doing an exam. When a student starts running an exam, the Student class has two important fields, one is running_exam, which sets the exam id that the student is currently doing, and the other is exam_time, an integer that stores how many seconds are left for that student. def start_exam(request, exam_id): exam = Exam.objects.get(id=exam_id, students=Student.objects.get(email=request.user.email)) if exam: Student.objects.filter(email=request.user.email).update( doing_exam=exam.id, exam_time=exam.time*60, ) return etc... Now I need a way to trigger an event for each second to update the student's exam_time field, subtracting -1 for each second and checking if it is not in 0. Other way would be doing this with JavaScript but it is maybe very vulnerable since it is pure front-end. Suggestions? -
While installing requirements.txt, ImportError: No module named pip
I had installed Pycharm community version and Python 3.7.3. After setting up virtual environment successfully, I tried to install requirements.txt by command:- pip install -r requirements.txt but it shows importerror that no module named pip -
Apache not serving Django on 443 (aws)
I've got a django app I'm trying to serve over HTTPS and struggling. I'm not strong in Apache configs and trying to piece this together. Hopefully somebody can point out what seems like a simple oversight. My certificate is set up and when I visit my site at http:// it redirects to https:// with a valid cert issued by Amazon. So, that seems to be correct. PROBLEM With my current container commands adding virtual hosts to apache, it is not serving django to 443 as I just see a page with: Index of / Here are my configs that get written with container commands: /etc/httpd/conf.d/wsgi.conf (which gets rewritten by aws each deployment) LoadModule wsgi_module modules/mod_wsgi.so WSGIPythonHome /opt/python/run/baselinenv WSGISocketPrefix run/wsgi WSGIRestrictEmbedded On <VirtualHost *:80> Alias /static/ /opt/python/current/app/www/static/ <Directory /opt/python/current/app/www/static/> Order allow,deny Allow from all </Directory> WSGIScriptAlias / /opt/python/current/app/proof/proof/wsgi.py <Directory /opt/python/current/app/> Require all granted </Directory> WSGIDaemonProcess wsgi processes=3 threads=20 display-name=%{GROUP} \ python-home=/opt/python/run/venv/ \ python-path=/opt/python/current/app user=wsgi group=wsgi \ home=/opt/python/current/app WSGIProcessGroup wsgi </VirtualHost> LogFormat "%h (%{X-Forwarded-For}i) %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined /etc/httpd/conf.d/virtualhost_http.conf <VirtualHost *:80> RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} =http RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent] </VirtualHost> /etc/httpd/conf.d/virtualhost_https.conf LoadModule wsgi_module modules/mod_wsgi.so WSGIPythonHome /opt/python/run/baselinenv WSGISocketPrefix run/wsgi WSGIRestrictEmbedded On Listen 443 <VirtualHost *:443> Alias /static/ … -
when popup by jquery ajax is showing is it possible reloading current popup by refresh(f5)
is it possible? jquery ajax popup => refresh (f5) => jquery ajax popup reloading Can I keep the pop-up so that I can reload the screen right now if I refresh? view code # todo 상세 보기 class todoDetail(DetailView): model = Todo def get_template_names(self): if self.request.is_ajax(): return ['todo/_todo_detail.html'] return ['todo/_todo_detail.html'] def get_context_data(self, *, object_list=None, **kwargs): context = super(todoDetail, self).get_context_data(**kwargs) context['comments'] = CommentForTodo.objects.filter(todo=self.object.pk) context['detail_id'] = self.object.pk context['comment_form'] = CommentForm() return context -
Custom User model error on changing password form through admin interface
Trying to set up custom user model on the start of django project, but i am facing a recurrent problem that i have only been able to patch, that now is affecting the changepassword of admin interface. On change password form submit, it crashes with error: AttributeError at /admin/custom_users/customuser/7/password/ 'NoneType' object has no attribute 'strip' on stack trace, i can see that the problem is that is_staff=NULL and is_superuser=NULL on the attempted query. I dont know why django passes this parameters as null on passwordchange since they are set to false on model and nowhere are they as fields on the CustomUserPassForm. Had this same issue on user change form, but after adding fieldsets to CustomUserAdmin(UserAdmin) class, i was able to edit a user. (as the is_superuser and is_staff input checkboxes appeared on form in html) models.py class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError('correo es obligatorio') email = self.normalize_email(email) extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_staff', False) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('superuser must have is_staff=True') if extra_fields.get('is_superuser') is not True: raise ValueError('superuser musthave is_superuser=True') return self.create_user(email, password, **extra_fields) … -
unexpected test failures in docker version of Django Rest Framework app
I have two environments in which I am running unit tests an application built on Django/DRF. Both are running on the same host machine. The legacy environment is a vagrant box, and the new environment is a docker container. Both environments have mounted the git repo for the Django application, so they are running identical code. I get a bash shell on each, and invoke the tests. The legacy environment has passes, the new environment fails. import json from rest_framework.viewsets import ModelViewSet from rest_framework.test import APIRequestFactory, force_authenticate from model_mommy import mommy from django.contrib.auth import get_user_model from .models import TestModel from .serializers import TestModelSerializer from ..views import BatchUpdateMixin from ..test_utils import CommonTestCase factory = APIRequestFactory() User = get_user_model() class SimpleBatchViewset(ModelViewSet, BatchUpdateMixin): """ For testing out-of-the-box functionality for the `BatchUpdateMixin` """ serializer_class = TestModelSerializer queryset = TestModel.objects.all() class LookupTestViewset(ModelViewSet, BatchUpdateMixin): """ for testing using a custom `batch_lookup_field` """ serializer_class = TestModelSerializer queryset = TestModel.objects.all() class BatchUpdateMixinTests(CommonTestCase): def test_basic_batch_update(self): """ sending update information should update all the requisite models and send the updated data back """ model_1 = mommy.make(TestModel, name='test model 1') model_2 = mommy.make(TestModel, name='test model 2') model_3 = mommy.make(TestModel, name='test model 3') no_update_model = mommy.make(TestModel, name='This will not change') update_data = … -
Django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query')
I'm using apschduler to call a task every 2hs, in this task it will read data from mysql db. But after mysql's default wait_timeout 28800s, it always raise Django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query') According from doc MySQL server has gone away, I think it should be child process issue. But I still can't solve this problem main.py import sys, os import django import logging import datetime import argparse BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR,'src')) sys.path.append(os.path.join(BASE_DIR,'data_model')) if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument('-d', '--execute_dir', type=str, help='exe_dir', default=BASE_DIR) args = ap.parse_args() sys.path.append(os.path.join(args.execute_dir, "conf")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_settings") django.setup() from auto_management_v2 import auto_manage from baseApscheduler import baseScheduler scheduler = baseScheduler.scheduler scheduler.add_job( func=auto_manage, trigger='interval', hours=1, start_date=(datetime.datetime.now() + datetime.timedelta(seconds=20)).strftime("%Y-%m-%d %H:%M:%S"), id='auto_manage', jobstore='default', replace_existing=True) scheduler.start() baseApscheduler.py import logging from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.jobstores.memory import MemoryJobStore from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED from django.conf import settings from utils import sendEmail logging.basicConfig( level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename=settings.AUTO_MANAGEMENT_FILE_NAME, filemode='a') def event_listener(event): if event.exception: print("task failed!") info = ''' time:{}, task_name: {}, fail_reason: {} '''.format(str(event.scheduled_run_time), str(event.job_id), str(event.exception)) sendEmail(message=info, subject='task failed') else: print(event.job_id + "task successed!") class BaseScheduler(): def __init__(self): self.executors = { 'default': ThreadPoolExecutor(10), 'processPool': ProcessPoolExecutor(3) } self.jobstores = { … -
serializers validation of request.data returns tuple for fields and "int() argument must be a string, a bytes-like object or a number, not 'tuple'"
When I call the serializer with request.data serializer = serializers.EventSerializer(data = request.data) and then when I print request.data['details'] returns the right string value but serializer.validated_data['details'] returns value as tuple Checked threads that deals with similar error code, but different context and it doesn't help. I am trying to call python API from form template using Ajax call. modules.py class Event(models.Model): title = models.CharField(max_length=200) details = models.TextField(blank=False) serializers.py class EventSerializer(serializers.ModelSerializer) class Meta: model = Event fields = ('title', 'details') Ajax post call from the form (html) template $.ajax({ url: ws, mimeType: "multipart/form-data", contentType: false, cache: false, processData: false, data:formData, headers: {"Authorization": "Token " + token}, type:(pk>0?"PUT":"POST"), success: function(json){ //success }, error:function(xhr, errmsg, err){ //error } }); apiviews.py class EventsApiView(viewsets.ViewSet): def update(self, request, pk=None): serializer = serializers.EventSerializer(data = request.data) print(request.data['details']) print(serializer.validated_data['details']) I expect a string value, not tuple. The serializer.validated_data['details'] returns a tuple while request.data['details'] returns the right value -
AttributeError at /ask/ module 'django.db.models' has no attribute 'Student'
I get the following error in Django: Can anyone help me Pic from Visual Studio Module 'django.db.models' has no 'Student' memberpylint(no-member) I get the following error in Django: Can anyone help me Pic from Visual Studio Module 'django.db.models' has no 'Student' memberpylint(no-member) Request Method: POST Request URL: http://127.0.0.1:8000/ask/ Django Version: 2.2.1 Exception Type: AttributeError Exception Value: module 'django.db.models' has no attribute 'Student' Python Version: 3.7.3 This is where the error is being generated: views.py from django.shortcuts import render, get_object_or_404 from .models import post from .models import Lost from .models import Student from social import forms from django.db import models def home (request) : context = { 'titel': 'homepage', 'posts': post.objects.all() } return render (request, 'site.html', context) def post_detail(request, post_id): post= get_object_or_404(Lost, pk=post_id) context = { 'title': post, 'post': post, } return render(request, 'details.html', context) def Register(request): form_data=forms.UserRegistrar(request.POST or None) msg='' if form_data.is_valid(): student=models.Student() student.first_name=form_data.cleaned_data['first_name'] student.last_name=form_data.cleaned_data['last_name'] student.save() msg='data is saved' context={ 'formregister':form_data, 'msg':msg } return render(request,'ask.html',context) forms.py from django import forms from django.db import models class UserRegistrar(forms.Form): first_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control'} )) last_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control'} )) models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class post(models.Model): title = models.CharField(max_length=10) content = models.TextField(max_length=30) post_date … -
How to fix attribute error in Django(Python)?
I'm newbie to Python and Django. I'm watching https://www.youtube.com/watch?v=a48xeeo5Vnk&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=2 this course and following instructions. But there is and error message keeps coming out like this. AttributeError: module 'blog.views' has no attribute 'post_list' C:\Users\Administrator\PycharmProjects\django_project\blog\urls.py changed, reloading. Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 398, in check for pattern in self.url_patterns: File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 572, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen … -
Django - function views do not show up in admindocs
I have some function based views in Django that are fairly simple, I followed the instructions here: https://docs.djangoproject.com/en/2.2/ref/contrib/admin/admindocs/ to set it up and it seems to work just fine for a view given by the Django REST Framework: rest_framework.authtoken.views.ObtainAuthToken As an example, this is what is generated in admindocs for the above view: /endpoint/auth View function: rest_framework.authtoken.views.ObtainAuthToken. Name: endpoint. But in the same namespace, the other function based views look like this: /endpoint/config View function: endpoint.views.WrappedAPIView. Name: endpoint. All of the other function views have the above endpoint.views.WrappedAPIView listed as the view function, and when I click that I obviously get a 404 because that is incorrect and doesn't exist as far as I can tell. The documentation I followed seems to indicate that function based views should work with admindocs, so I'm just confused on why they're not getting picked up. Thanks!! -
Django query: Sort objects by the number of occurrences of a value?
I'm trying to use Django to return a list of objects with duplicate values, sorted from most-duplicated to least-duplicated. For example, let's say I have the following model: class Person(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=128) I want to return a list of Persons, sorted from those with the most common name to those with the least common name. I know that I can use values and annotate to create a sorted list of name values like this: Person.values('name').annotate(Count('id')).order_by('id__count') But I don't want a list of names; I want a list of Person objects. Is there a way to accomplish this? -
is it possible to search two fields with one passed in reference django rest framework
I have a django rest framework project. I have a friend models which has a friender and friended model. the friender is a foreign key for the user which contains a username and friended is a char field that is going to be a username. I have a username passed in through the url that calls the serialize. I want it to be used to search through both fields and see if any records contain username for friender and friended. Would it be better to set both of the as charfields and store usernames in both or is there an easy way to seach both fields and combine the results... right now it checks the friended... i want to to check friended and friender.username here is my code: models: class Friend(models.Model): friender = models.ForeignKey(User, on_delete=models.CASCADE) friended = models.CharField(max_length=50) status = models.SmallIntegerField() blocked = models.BooleanField(default=False) favorite = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.friender.username + self.friended serializer: class FriendSerializer(serializers.ModelSerializer): class Meta: model = Friend fields = ( 'friender', 'friended', 'status', 'blocked', 'favorite', ) depth=2 views: from users.models import Friend from ..serializers import FriendSerializer from rest_framework import viewsets class FriendViewSet(viewsets.ModelViewSet): queryset = Friend.objects.all() lookup_field = 'friended' serializer_class = FriendSerializer -
Can I print pop-up dl again when I refresh (f5)? (requires jquery ajax request)
Can I print pop-up dl again when I refresh (f5)? (jquery ajax request required, django)