Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OperationalError: create_superuser doesn't work
I'm trying to make custom user model for my app named Bookjang. When I typed python manage.py createsuperuser Error raised like this django.db.utils.OperationalError: no such column: Bookjang_user.rank Here is my custom user manager class code. class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('user_type', 'Manager') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) And my custom user model. class User(AbstractBaseUser, PermissionsMixin): USER_TYPE_CHOICES = ( ('reader', 'Reader'), # 독자 ('author', 'Author'), # 저자 ('publisher', 'Publisher'), # 출판사 ('manager', 'Manager'), ) email = models.EmailField(unique=True) rank = models.IntegerField(default=1) exp = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100)]) user_type = models.CharField( max_length=10, choices=USER_TYPE_CHOICES, default=USER_TYPE_CHOICES[0] ) created_date = models.DateField(auto_now_add=True) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'email' objects = UserManager() I already check migrations and here it is. migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('email', models.EmailField(max_length=254, unique=True)), ('rank', models.IntegerField(default=1)), … -
Django-Cookiecutter: Why is dist listed in .gitignore?
A fundamental question about the .gitignore list that's auto generated by django-cookiecutter. I suppose this it's best practice to ignore dist. I am not a front-end/UI master but many javascript packages come with a dist folder which I just copy into the static folder. Is that a bad idea? Is there something I should know about files in a dist folder? -
Djongo (Django+Mongo) - Can't insert new documents [django.db.utils.DatabaseError Error]
I'm using djongo to connect to Mongo DB with Django. This is my DATABASES configuration in my settings.py: DATABASES = { 'default': { 'ENGINE': 'djongo', 'CLIENT': { 'host': 'mongodb+srv://{}:{}@{}/?retryWrites=true&w=majority'.format( USERNAME, PASSWORD, HOST), 'username': USERNAME, 'password': PASSWORD, 'name': DB_NAME, 'authSource': 'admin', 'ssl':False, 'authMechanism': 'SCRAM-SHA-1', } } } I can't insert new documents using djongo, but i can update existing ones. I have a view that upserts a document based on the primary key field: def upsert_document_view(request): try: form_data = request.POST form = self.form(form_data) if form.is_valid(): print("SAVING TO MONGODB. Data:\n{}".format(form_data)) form.save() except Exception as err: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] msg_text = msg_text + "\n\nPython Error:\n{} `{}`\nfile_name: {} | line_number: {}".format(exc_type, exc_obj, fname, exc_tb.tb_lineno) print(msg_text) When a document does not exist, djongo should insert a new document when the code gets to form.save(). Unfortunately i'm getting this weird empty error: <class 'django.db.utils.DatabaseError'> `` As you can see, its a django.db.utils.DatabaseError error, but the error message is empty. Like i mentioned, when i try to use form.saves() for existing documents, djongo does not throw any errors and works properly. -
http://<domain> gets redirected to https://<ip> (NGINX, Django, Gunicorn)
I'm hosting a website using nginx, Django and Gunicorn and just installed the SSL certificate so I can use HTTPs for the website. Everything works perfectly fine when using https://.com, even http://www..com works like it should, but http://.com gets redirected to https:// for some reason. My sites nginx config is: server { listen 443 ssl; listen [::]:443 ssl; ssl on; ssl_certificate /etc/ssl/<crt>; ssl_certificate_key /etc/ssl/<key>; server_name <domain>.com; client_max_body_size 100M; access_log on; location /static/ { alias /opt/<dir>/; } location /uploads/ { alias /opt/<dir>/; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } server { listen 80; server_name <domain>.com www.<domain>.com; return 301 https://<domain>.com$request_uri; } When I cURL my site, its properly redirected to its HTTPs version, but in Firefox in gets redirected to the server IP. I'm very unsure why this is the case, so I'd appreciate any ideas! -
Websites for smartphones, tablets and pc [closed]
I wanna design a website that works on smartphones, tablets and pc. So which platform will be able to do that effectively. -
my django api view.py not showing list and creat new list
Hello developer I'm beginner to django , im following a tutorial in which he create concrete views classes and convert them to viewset.ModelViewSet classes. and he use default router in urls.py my app showing list of articles with viewset but not perform the post method with the ArticleViewSet(viewset.ModelViewSet) so im confused about it to use viewset This is my api/view.py file im using Concrete View Classes in which i using concrete view classses ** class ArticleListView(ListAPIView): queryset = Articles.objects.all() serializer_class = ArticleSerializer class ArticleDetailView(RetrieveAPIView): queryset = Articles.objects.all() serializer_class = ArticleSerializer class ArticleUpdateView(UpdateAPIView): queryset = Articles.objects.all() serializer_class = ArticleSerializer class ArticleDeleteView(DestroyAPIView): queryset = Articles.objects.all() serializer_class = ArticleSerializer class ArticleCreateView(CreateAPIView): permission_classes = [] #parser_classes = (FormParser,MultiPartParser, FileUploadParser ) serializer_class = ArticleSerializer queryset = Articles.objects.all() #serializer = ArticleSerializer(queryset, many=True) def post(self, request): serializer = ArticleSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(True, status=200) # class ArticleViewSet(viewsets.ModelViewSet): # parser_classes = (FormParser,MultiPartParser, FileUploadParser ) # serializer_class = ArticleSerializer # queryset = Articles.objects.all() **this are my urls patterns api/url.py in Article app ** urlpatterns = [ path('articles', ArticleListView.as_view() name=""), path('xyz', ArticleCreateView.as_view()), path('<pk>', ArticleDetailView.as_view()), path('<pk>/update/', ArticleUpdateView.as_view()), path('<pk>/delete/', ArticleDeleteView.as_view()) ] #from articles.api.views import * # from rest_framework.routers import DefaultRouter # router = DefaultRouter() # router.register(r'', ArticleViewSet, basename='articles') # urlpatterns = router.urls … -
I am unable to access the id of a newly saved instance of model to be used in processing another form within the same page
I am trying to create a page with two different forms and one submit button. One form creates the title and the other form creates the questions that will be placed under the title. The title is linked to the question with a one to many relationship. However, when I submit the form, the title get created but I can't access the title so that my other form can use it in the view. The forms are created like so: 6 class DeckForm(ModelForm): 7 title = forms.CharField(widget = forms.TextInput( 8 attrs={'class': 'title', 9 'placeholder': 'Title'}), 10 label='') 11 subject = forms.CharField(widget = forms.TextInput( 12 attrs={'class': 'subject', 13 'placeholder': 'Subject'}), 14 label='') ⚠ 15 class Meta: 16 model = Deck 17 fields = ['title', 'subject'] 18 ⚠ 19 class CardsForm(ModelForm): ⚠ 20 class Meta: 21 model = CardsQuestion 22 fields = ['questionText', 'answerText'] 23 24 CardsFormset = formset_factory(CardsForm, extra=1) ~ And they are managed in the view like so: ⚠ 27 class QuestionsView(TemplateView): 28 template_name = "cards/questions.html" 29 30 def get(self, *args, **kwargs): ⚠ 31 NewCardsForm= CardsFormset() ⚠ 32 NewDeckForm= DeckForm() 33 return self.render_to_response( 34 {'CardsFormset': NewCardsForm, 35 'DeckForm': NewDeckForm}) ⚠ 36 def post(self, *args, **kwargs): ⚠ 37 NewDeckForm= DeckForm(data=self.request.POST) ⚠ … -
how to calculate upload speed in js
i'm working on a django website and i have a view where the user is able to upload videos and i need to add a button for the user so he can make a short test for his upload speed after a lot of research i found this script but it seems that it's not working and i could not know why var http = new XMLHttpRequest(); var startTime, endTime; var myData = "d="; // the raw data you will send for(var i = 0 ; i < 1022 ; i++) //if you want to send 1 kb (2 + 1022 bytes = 1024b = 1kb). change it the way you want { myData += "k"; // add one byte of data; } http.open("POST", url, true); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.setRequestHeader("Content-length", myData .length); http.setRequestHeader("Connection", "close"); http.onreadystatechange = function() { if(http.readyState == 4 && http.status == 200) { endTime = (new Date()).getTime(); ShowData(); } } startTime = (new Date()).getTime(); http.send(myData); function ShowData() { var duration = (endTime - startTime) / 1000; var bitsLoaded = myData * 8; var speedMbps = ((bitsLoaded / duration) / 1024 / 1024).toFixed(2); alert("Speed: " + speedMbps + " Mbps"); } so is there any simple method for calculating … -
Automatically delete logs in Django
Building a Django app, I am trying to figure out what would be the best way to automate log file deletion. My try so far is to build a admin command that delete old logs. From this I can setup a scheduler in python or at server's level but I am not very satisfied with this option because it makes more configuration steps to do during deployment. I was wondering if sub-classing log module to trigger a delete-log function on a log write would be a good idea. The pros would be that there is not setup to do a deployment, the cons would be to rely on log write to clean log directory could be useless if there is no log records for a long time. On the other hand it could be resource consuming if there is too many log records. So first of all, is a log-delete triggered by any action could be a good idea and what would be the best action to choose (a daily one)? If not, what would be the best option to perform this in a beautiful way? -
Django: How to filter model objects after passing through functions?
I have a model called Service, which has a field url of type str. I have a function f that returns the hostname of an url: def f(url): return urllib.parse.urlparse(url).hostname I want to get all the objects whose f(url) equals a value target. One way to achieve this would be by doing the following: [x for x in Service.objects.all() if(f(x.url) == target)] But in that case, I'll get a list, not a QuerySet. Is there a way to filter the objects and get a QuerySet satisfying the above criteria? -
Filtering a foreign key in Django
I'm trying to filter a foreign key, but it's not rendering any data, no matter the approach I use from examples.Here is the code class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customer',primary_key=True) first_name = models.CharField(blank=True, max_length=150) last_name = models.CharField(blank=True, max_length=150) name = models.CharField(max_length=200, null=True) ' class Order(models.Model): Distributor = models.ManyToManyField(settings.AUTH_USER_MODEL,) Customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='customer_client') The Views def dashboard(request): orders = Order.objects.filter(Distributor=request.user) customers = orders.filter(Customer_id=1) i'm trying to filter the customers who have made the orders from a particular Distributor, kindly assist -
How to connect Django to remote MySQL database over ssh tunnel?
I have access to remote MySQL database using ssh tunnel with host, user, password. I can access to database in MySQL Workbench using ssh tunnel with SSH Hostname, SSH Username, SSH Password. Also I have access in Pycharm using ssh tunnel with Host, User name, Password. I'm trying to connect Django to a MySQL database. Is it possible to add SSH settings to these database settings in Django settings file and have access through Django? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '<DATABASE NAME>', 'USER': '<USER NAME>', 'PASSWORD': '<PASSWORD>', 'HOST': '<HOST>', 'PORT': '3306' } } -
Having problems with Django Translation in italian
I was trying to create a django site in two languages, English and Italian. I have declared in the settings.py file all the properties necessary for it to work, following both the django doc and other guides on stackoverflow, but with no positive results. settings.py file: it/LC_MESSAGES/django.po file: index.html file: views.py file: result: commands used: -
NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f09b9f0a7c0>: Failed to establish a new connection: [Errno 111] Connection refused)
I am trying to build a simple django elastice search which can search cars. But when I am trying to rebuid the indexes, it gives me the error above. I am following this doc -> quickstart elasticsearch...full traceback is given below-> elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f09b9f0a7c0>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f09b9f0a7c0>: Failed to establish a new connection: [Errno 111] Connection refused) my models.py is simple Car model having name, color, description, type filds on which I add in document class Car(models.Model): name = models.CharField(max_length=50) color = models.CharField(max_length=50) description = models.TextField() type = models.IntegerField(choices=[ (1, "Sedan"), (2, "Truck"), (4, "SUV"), ]) my documents.py file-> from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Car @registry.register_document class CarDocument(Document): class Index: name = 'cars' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Car fields = [ 'name', 'color', 'description', 'type', ] but when i am trying to rebuid the index, it gives the new connection error. The command I am using to rebuild the index is given below -> python manage.py search_index --rebuild -
django-taggit Error on calling names() on Custom Tag
I am trying to create a model with two types of tags associated with companies and topics and followed the documentation at django-taggit for making Custom Tags to facilitate having two Taggable Manager in one model. My models.py from django.db import models from taggit.managers import TaggableManager from taggit.models import GenericTaggedItemBase, TagBase # Create your models here. class TopicTag(TagBase): class Meta: verbose_name = "TopicTag" verbose_name_plural = "TopicTags" class CompanyTag(TagBase): class Meta: verbose_name = "CompanyTag" verbose_name_plural = "CompanyTags" class ThroughTopicTag(GenericTaggedItemBase): tag = models.ForeignKey(TopicTag, on_delete=models.CASCADE) class ThroughCompanyTag(GenericTaggedItemBase): tag = models.ForeignKey(CompanyTag, on_delete= models.CASCADE) class Questions(models.Model): name = models.CharField(max_length=255) path = models.CharField(max_length=500) company_tags = TaggableManager(blank = True, through=ThroughCompanyTag, related_name="company_tags") topic_tags = TaggableManager(blank = True, through=ThroughTopicTag, related_name="topic_tags") Now, when I try to running the following commands in django shell from QuestionBank.models import Questions Questions.objects.first().company_tags.names() I get the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/taggit/utils.py", line 124, in inner return func(self, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/taggit/managers.py", line 248, in names return self.get_queryset().values_list("name", flat=True) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/taggit/managers.py", line 74, in get_queryset return self.through.tags_for(self.model, self.instance, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/taggit/models.py", line 155, in tags_for return cls.tag_model().objects.filter(**kwargs).distinct() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 904, in filter return self._filter_or_exclude(False, *args, … -
Employee matching query does not exist
Its my view function i have two db tables customer and employee when im deleting a row in employee table im getting this error (Employee matching query does not exist.). same issue in customer table also. def delete(request, user_id): delCust = Customer.objects.get(user_id = user_id) delEmp = Employee.objects.get(user_id = user_id) delEmp.delete() delCust.delete() return redirect("/admins") -
"ImportError: Traceback (most recent call last):" I don'y know how to fix this Error
I got an error while making a chat bot watching some video and I install python 3.6.5 and pip install nltk pip install numpy pip install tflearn pip install tensorflow and I wrote codes import nltk from nltk.stem.lancaster import LancasterStemmer stemmer = LancasterStemmer() import numpy import tflearn import tensorflow import random import json with open("intents.json") as file: data =json.load(file) print(data) and I run this codes Traceback (most recent call last): File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 64, in <module> from tensorflow.python._pywrap_tensorflow_internal import * ImportError: DLL load failed: 지정된 모듈을 찾을 수 없습니다. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "main.py", line 6, in <module> import tflearn File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tflearn\__init__.py", line 4, in <module> from . import config File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tflearn\config.py", line 3, in <module> import tensorflow as tf File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\__init__.py", line 41, in <module> from tensorflow.python.tools import module_util as _module_util File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\python\__init__.py", line 40, in <module> from tensorflow.python.eager import context File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\python\eager\context.py", line 35, in <module> from tensorflow.python import pywrap_tfe File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\python\pywrap_tfe.py", line 28, in <module> from tensorflow.python import pywrap_tensorflow File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 83, in <module> raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\Users\USER\anaconda3\envs\chat\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 64, in <module> from tensorflow.python._pywrap_tensorflow_internal import * ImportError: DLL load … -
Django-oscar attribute cannot be blank
I'm new to learning django-oscar. I recently installed a project and am trying to create my first directory. Now I have only 1 product class and 1 product attribute(I want to make it required). When I try to create a product I get the error color attribute cannot be blank.I filled in the fields with text and even filled in the time of adding, but I get this error. What could be the problem? -
Django - track down the code that generated slow queries in database
I'm using Django for a large app. When monitoring the DB (Postgres) I sometimes see a few slow queries log written. The problem is how to track down the code that generated these queries. optimally I want some stack trace for these logs, but wonder if there is some other best-practice, or maybe some other tool. It's in production so DEBUG is set to False, so Django itself doesn't track the speed of the queries. -
How can i load Vue on a Django project using Webpack-Loader?
I would like to add VueJS to my Django project, and since i don't want to go full SPA, i decided to use Webpack-Loader, so after making some research i cloned a very simple Django+Vue app from Github, to see how would that work, here is the full code. Now, on my local everything works fine. In order to run the project i do manage.py runserver and npm run serve. I'm trying, now, to run this same example project in production on a Digital Ocean vps using Gunicorn + Nginx, but the problem is that while the Django app works fine, none of the Vue frontend is being loaded. I only see a bunch of errors like: net::ERR_ABORTED 404 (Not Found). Can anyone help me find what's wrong? I thought that on production i would not need to use two servers since i'm using Webpack. The code is exactly the same i linked. Can anyone help me out on this? -
FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/lib/python3.6/site-packages/django_redis_cache-3.0.0-py3.6.egg'
While docker image was being created, I've got the below exception: FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/lib/python3.6/site-packages/django_redis_cache-3.0.0-py3.6.egg' Dockerfile: FROM python:3.6 # ... Packages: django==2.0.6 redis==3.5.3 django-redis-cache==2.0.0 django-redis-sessions Here is a full trace of the exception: Traceback (most recent call last): File "/usr/local/bin/pip", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/main.py", line 75, in main return command.main(cmd_args) File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 121, in main return self._main(args) File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 265, in _main self.handle_pip_version_check(options) File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 152, in handle_pip_version_check timeout=min(5, options.timeout) File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 97, in _build_session index_urls=self._get_index_urls(options), File "/usr/local/lib/python3.6/site-packages/pip/_internal/network/session.py", line 249, in __init__ self.headers["User-Agent"] = user_agent() File "/usr/local/lib/python3.6/site-packages/pip/_internal/network/session.py", line 159, in user_agent setuptools_version = get_installed_version("setuptools") File "/usr/local/lib/python3.6/site-packages/pip/_internal/utils/misc.py", line 665, in get_installed_version working_set = pkg_resources.WorkingSet() File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 567, in __init__ self.add_entry(entry) File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 623, in add_entry for dist in find_distributions(entry, True): File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1983, in find_eggs_in_zip if metadata.has_metadata('PKG-INFO'): File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1414, in has_metadata return self._has(path) File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1854, in _has return zip_path in self.zipinfo or zip_path in self._index() File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1731, in zipinfo return self._zip_manifests.load(self.loader.archive) File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1688, in load mtime = os.stat(path).st_mtime FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/lib/python3.6/site-packages/django_redis_cache-3.0.0-py3.6.egg' Question: How can I overcome this issue? Any help would be … -
Django REST API - Joining multiple tables in a query
My goal is to get all EmployeeQuestions, such that employee has an employer with the given id (request.user.pk). More formally, I want to get all EmployeeQuestions where question has a course where employer_id is the given id. I hope this makes sense. Basically as an employer I want to retrieve all the question progress of all my employees. I thought I made the right query but it just returns all EmployeeQuestions: EmployeeQuestion.objects.filter(question__in=CourseQuestion.objects.filter(course__in=Course.objects.filter(employer_id=request.user.pk))) Any Django query geniuses here who can help me? :) View class EmployeeQuestionByEmployerId(viewsets.ModelViewSet): queryset = EmployeeQuestion.objects.all() serializer_class = EmployeeQuestionSerializer def list(self, request): queryset = EmployeeQuestion.objects.all() if request.query_params: queryset = EmployeeQuestion.objects.filter(question__in=CourseQuestion.objects.filter(course__in=Course.objects.filter(employer_id=request.user.pk))) serializer = EmployeeQuestionSerializer(queryset, many=True) return Response(serializer.data) Models class CustomUser(AbstractBaseUser): username = ... employer = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE) class Course(models.Model): employer_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=255, blank=False, null=False) class Question(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, null=False) question = models.CharField(max_length=255, blank=False, null=False) question_type = models.CharField(max_length=255, blank=False, null=False) # mult/ord/open class EmployeeQuestion(models.Model): employee = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) question = models.ForeignKey(CourseQuestion, on_delete=models.CASCADE, null=False) passed = models.BooleanField(default=False) -
Django using URL dispatcher
I have a horoscope site, I want to make a blog, I created an HTML file called Bloglist.html where the pictures and names of the blogs are listed, then I made Blogdetail.html where there is already a definition of a specific block (body_Text, author ..). It's all I want to link to the URL dispatcher. but can not do it , can anyone help? url.py urlpatterns = [ path('',Home,name= "Home"), path("blog/<slug:slug>/",blog_list, name="blog_list"), ] Models.py class Blogmodel(models.Model): Title = models.TextField(blank=True, null=True) image = models.ImageField(upload_to="media/image",null=True) body = models.TextField(blank=True, null=True) slug = models.TextField(blank=True, null=True) bloglist.html <div class="blog_box"> <a href="/blog/{{ article.slug }}" class="blog_img"><img src="/storage/blog/thumbs/251-.png"></a> <a href="/blog/{{ article.slug }}" class="blog_title">{{ article.Title }}</a> </div> views.py def blog_list(request,slug): article = Blogmodel.objects.get(Title=slug) args = {'article':article, 'slug':slug} return render(request,'blog.html',args) -
Ended up with Pylint-django issue while trying to modify single table postgreSQL database to One-to-Many relationship
I was trying to modify my single table db to 1-to-many relationship database with two tables, "proType" and "Work" respectively where one proType can have multiple work and vice versa. Initially I only had "Work" table. I added new model class "proType" added Foreignkey for the relationship as below. After creating the model I deleted everything from migration folder except init_.py file and I ran following code in cmd prompt python manage.py makemigrations (showed me the two new models/tables that needed migration) python manage.py migrate and got result as below, Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, works Running migrations: No migrations to apply. Now when I run my localhost for django I get rendering error coming from views.py with following error which asks me to fulfill necessary requirements for pylint. And when I try to install pylint I am getting following results, Is it suggesting me to use cpython instead of pylint because of my python version not being compatible to the package that I need. Or I don't need pylint in first place to accomplish my one-to-many db model? or if there's any other workaround to meet my goal? Please guide me through this issus. … -
how to make end_year choice value start from start_year input value : Django
I have start_year and end_year choice in model fields. How to make end_year field choice will start from start_year value that you user input. enter code here Models.py: YEAR_CHOICES = [] for r in range(2005, (datetime.datetime.now().year+5)): YEAR_CHOICES.append((r,r)) start_year = models.IntegerField(choices=YEAR_CHOICES, default=datetime.datetime.now().year) ENDYEAR_CHOICES = [] for r in range((start),(datetime.datetime.now().year+5)): ENDYEAR_CHOICES.append((r,r)) end_year = models.IntegerField(choices=ENDYEAR_CHOICES, default=datetime.datetime.now().year)