Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
npm install in Django Docker file
I am working with Django and currently try to move my local dev. to Docker. I managed to run my web server. However, what I didn't to yet was npm install. That's where I got stuck and I couldn't find documentation or good examples. Anyone who has done that before? Dockerfile: # Pull base image FROM python:3.7 # Define environment variable ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install -y \ # Language dependencies gettext \ # In addition, when you clean up the apt cache by removing /var/lib/apt/lists # it reduces the image size, since the apt cache is not stored in a layer. && rm -rf /var/lib/apt/lists/* # Copy the current directory contents into the container at /app COPY . /app # Set the working directory to /app WORKDIR /app # Install Python dependencies RUN pip install pipenv RUN pipenv install --system --deploy --dev COPY ./docker-entrypoint.sh / RUN chmod +x /docker-entrypoint.sh ENTRYPOINT ["/docker-entrypoint.sh"] docker-compose: version: '3' services: db: image: postgres ports: - "5432:5432" environment: # Password will be required if connecting from a different host - POSTGRES_PASSWORD=django web: build: . env_file: .env volumes: - .:/app ports: - "8000:8000" depends_on: - db container_name: django docker-entrypoint.sh #!/bin/bash # Apply … -
Get the records by joining three table that are not in another table
I'm trying the get the records from the Student table, condition is that the student's primary key do not exist in the From table.(From is used as a relation) table. Relation is "student from department" Model: class Student(models.Model): name = models.CharField(max_length=20) password = models.CharField(max_length=30) phone_no = PhoneNumberField(null=False, blank=False, unique=True) email = models.EmailField() pic_location = models.FileField() username = models.CharField(max_length=30) class From(models.Model): s = models.ForeignKey(Student, on_delete=models.PROTECT) d = models.ForeignKey(Department,on_delete=models.PROTECT) class Department(models.Model): name = models.CharField(max_length=20) password = models.CharField(max_length=30) phone_no = PhoneNumberField(null=False, blank=False, unique=True) email = models.EmailField() I'm trying to get those records in the list view. And please review whether the way i'm retrieving session variable is good to go in such case?? class PendingStudent(ListView): # Students pending for department approval context_object_name = 'pending_students' model = From template_name = "admin_panel/department/student_detail.html" def get_queryset(self): department = self.request.session.get('username') return From.objects.filter(~Q(d__name==department)) I've used session, to store what type of user is logged in (student/teacher/department). -
How to get a Form für all elements in html?
I have the problem that my issue is not as expected. I want to output the name of each object in the database and then have a drop-down where I can make the selection of the Ingredient. I use Forms with Django How it is: https://imgur.com/a/8cxLtXk How it should be: https://imgur.com/a/QyinUyJ models.py from django.db import models class Drink(models.Model): name = models.CharField(max_length=256, unique=True) description = models.TextField() image_path = models.ImageField(upload_to=".\images") slug = models.SlugField(unique=True) ingredient = models.ManyToManyField('Ingredient', through='IngredientRatio', related_name='mischung',) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=256, unique=True) alcohol = models.BooleanField() def __str__(self): return self.name class IngredientRatio(models.Model): quantity = models.DecimalField(max_digits=4, decimal_places=2) ingredient = models.ForeignKey('Ingredient', on_delete=models.CASCADE) drink = models.ForeignKey('Drink', on_delete=models.CASCADE) def __str__(self): return "{0}: {1} : {2}".format(self.drink.name, self.ingredient.name, self.quantity) class TankAllocation(models.Model): name = models.CharField(max_length=8, unique=True) allocation = models.ForeignKey('Ingredient', on_delete=models.CASCADE, default='NULL', related_name='ingredients') def __str__(self): return "{0}: {1}".format(self.allocation.name, self.name) views.py from django.shortcuts import render, get_object_or_404, get_list_or_404 from .models import Drink, Ingredient, IngredientRatio, TankAllocation from . import forms from django.http import HttpResponse def index(request): context = {'drinks': Drink.objects.all(), 'titel': "Drink Uebersicht"} return render(request=request, template_name='index.html', context=context) def DrinkDetails(request, slug): drink = get_object_or_404(Drink, slug=slug) drinkID = drink.id irgedients = get_list_or_404(IngredientRatio, drink_id=drinkID) context = {'drink': drink, 'ingredients': irgedients} return render(request=request, template_name='drink.html', context=context) def tankAllocation(request): form = forms.TankForm() return render(request, … -
Raw SQL in Django - how to properly write query without sql injection?
I am attempting to perform a raw sql query in Django but I cannot get it to perform properly unless I add ' characters around the string. Example: '%s'. However, I read this leaves me open to sql injection. q_params = [ new_dtl_params["email_addr"], new_dtl_params["attach_html"], new_dtl_params["attach_csv"], new_dtl_params["attach_text"], new_dtl_params["text_rpt"], int(new_dtl_params["seq_num"]), old_dtl_params["email_grp"], int(old_dtl_params["seq_num"]) ] query = """UPDATE emaildtl SET email_addr = %s, attach_html = %s, attach_csv = %s, attach_text = %s, text_rpt = %s, seq_num = %s WHERE email_grp = %s AND seq_num = %s""" Emaildtl.objects.raw(query, q_params) The code doesn't work because there is no ' around each string %s. I'm not sure how to get this to work without the quote character. -
Why does my Django Application timeout on AWS?
I've recently (today) uploaded a Django application onto AWS through elastic beanstalk. It shows good health, I've ssh'd in and everything seems to be in the right place. When I try to access the site it timesout. If I run the site locally, the home page returns in under a second I know this is rather broad but I have no errors in the logs. Any ideas where to troubleshoot? -
How to create a shared model in Django?
I have a couple of models that have need of a common set of fields. It is basically a set of various different types of contacts: # models I would like to share class Address(models.Model): label = models.CharField(_('label'), max_length=50, blank=True) street1 = models.CharField(_('street1'), max_length=125, blank=True) street2 = models.CharField(_('street2'), max_length=125, blank=True) city = models.CharField(_('city'), max_length=50, blank=True) state = models.CharField(_('state'), max_length=2, blank=True) zip_code = models.CharField(_('zip_code'), max_length=10, blank=True) class Phone(models.Model): label = models.CharField(_('label'), max_length=50, blank=True) phone = models.CharField(_('phone'), max_length=50, blank=True) # these are the models that I would like to have addresses and phone numbers class Contact(models.Model): name = models.CharField(_('name'), max_length=50, blank=False) class Organization(models.Model): name = models.CharField(_('name'), max_length=255, blank=False) email = models.CharField(_('email'), max_length=100, blank=True) website = models.CharField(_('website'), max_length=255, blank=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) photo = models.CharField(_('photo'), max_length=255, blank=True) I would like to share the Phone and Address models with the Contact, Organization and UserProfile models. My first attempt was to add ForeignKey on each of Contact, Organization and UserProfile but after more research I believe this is backwards, so I moved the ForeignKey to Address and Phone but then discovered that ForeignKey can belong to one and only one model. In addition to sharing this data structure between multiple different contact … -
Django annotate - get attribute of all related objects
I have such a models: # models.py class A(Model): ... class B(Model): parent = ForeignKey(A) comments = ForeignKey(Comments) class Comments(Model): title = CharField(...) How, using annotate method of queryset, I can get all titles of Bs' comments related to some A object? I tried: result = A.object.all().annotate(b_titles=F("b__comments__title")) but it returns only first object. FilteredRelation also didnt helped (FilteredRelation's condition doesn't support nested relations) -
Django - Variable coming from context processor not updated when deployed but works locally
I'm deploying a Django website to a DigitalOcean Droplet, using Nginx and Gunicorn. The idea is to every month update the date depending on the current day. Locally works perfectly but once deployed, the value doesn't update, in order to make it update I have to restart Gunicorn with the next command: sudo systemctl restart gunicorn Do you know what is stopping the variables of being updated? The project has an App called "pages", which it has a utils.py in charge of calculating and prepare the date in two languages: from babel.dates import format_date import calendar import datetime import locale import time def cat_date(): # get current date num_date = str(time.strftime("%d/%m/%Y")) current_month = int(time.strftime("%m")) current_year = int(time.strftime("%Y")) today = datetime.date.today() # get last day of current month last_day_current_month = calendar.monthrange(current_year, current_month)[1] date_last = today.replace(day=last_day_current_month) date_last_day_current_month_num = date_last.strftime("%d/%m/%Y") # get last week date date_prev_week = today - datetime.timedelta(days=7) num_date_prev_week = date_prev_week.strftime("%d/%m/%Y") month_lw = int(date_prev_week.strftime("%m")) year_lw = int(date_prev_week.strftime("%Y")) # get last day of previous month last_day_previous_month = calendar.monthrange(year_lw, month_lw)[1] date_last_prev = date_prev_week.replace(day=last_day_previous_month) date_last_day_previous_month_num = date_last_prev.strftime("%d/%m/%Y") # use babel to get the long readable formated date catalan_text_date_current = format_date(date_last, format='long', locale='ca') catalan_text_date_previous = format_date(date_last_prev, format='long', locale='ca') # choose date to display depending on … -
ptvsd remotely debugging from Django's dev server port binding error
Python process we are limited to binding to one IP address. So when trying to run "python manage.py runserver" after adding pdvsd lines results in an error. Is there a way around this? Traceback (most recent call last): File "manage.py", line 27, in <module> main() File "manage.py", line 14, in main ptvsd.enable_attach(address=('0.0.0.0', 18080), redirect_output=True) File "/usr/local/lib/python3.7/site-packages/ptvsd/attach_server.py", line 96, in enable_attach ptvsd_enable_attach(address) File "/usr/local/lib/python3.7/site-packages/ptvsd/_remote.py", line 75, in enable_attach patch_multiprocessing=ptvsd.options.multiprocess) File "/usr/local/lib/python3.7/site-packages/ptvsd/_vendored/pydevd/pydevd.py", line 2017, in settrace wait_for_ready_to_run, File "/usr/local/lib/python3.7/site-packages/ptvsd/_vendored/pydevd/pydevd.py", line 2068, in _locked_settrace debugger.connect(host, port) # Note: connect can raise error. File "/usr/local/lib/python3.7/site-packages/ptvsd/_vendored/pydevd/pydevd.py", line 914, in connect s = start_client(host, port) File "/usr/local/lib/python3.7/site-packages/ptvsd/pydevd_hooks.py", line 132, in <lambda> _start_client = (lambda h, p: start_client(daemon, h, p)) File "/usr/local/lib/python3.7/site-packages/ptvsd/_remote.py", line 58, in <lambda> start_client=(lambda daemon, h, port: start_daemon()), File "/usr/local/lib/python3.7/site-packages/ptvsd/_remote.py", line 50, in start_daemon _, next_session = daemon.start_server(addr=(host, port)) File "/usr/local/lib/python3.7/site-packages/ptvsd/daemon.py", line 161, in start_server self._server = create_server(addr.host, addr.port) File "/usr/local/lib/python3.7/site-packages/ptvsd/socket.py", line 79, in create_server server.bind((host, port)) OSError: [Errno 98] Address already in use manage.py is this #!/usr/bin/env python import os import sys import dotenv def main(): dotenv.read_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.app.env'), override=True) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') try: # for debug if os.environ['APP_MODE'] == 'DEBUG': import ptvsd ptvsd.enable_attach(address=('0.0.0.0', 18080), redirect_output=True) from django.core.management import execute_from_command_line except ImportError as exc: raise … -
migrations not creating new tables in django 2
i am using mysql for the database and each time when i created new models i have to create new table by going in the phpmyadmin because the migration is not creating any tables but the migrate happens successfully.How can i solve this ? -
django_cms forced language in url problem : TypeError at / string indices must be integers
I am trying to use divio - django-cms, but whenever I try to connect to local server, I get error because of my local language. I tried to delete the settings.py's language code snippets but in vain since it raised another eror like TypeError at / string indices must be integers **Request Method: GET Request URL: http://54.180.150.144:52761/ Django Version: 1.11.21 Exception Type: TypeError Exception Value: string indices must be integers Exception Location: /workspace/heydj/venv/lib/python3.6/site-packages/cms/utils/conf.py in _ensure_languages_settings, line 205 Python Executable: /workspace/heydj/venv/bin/python3 Python Version: 3.6.5 Python Path: ['/workspace/djcms_r', '/workspace/heydj/venv/lib/python36.zip', '/workspace/heydj/venv/lib/python3.6', '/workspace/heydj/venv/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6', '/workspace/heydj/venv/lib/python3.6/site-packages'] Server time: 수요일, 5 6월 2019 10:47:35 +0000** In the settings.py it goes like : """ { 'code': 'ko', 'name': gettext('ko'), 'redirect_on_fallback': True, 'public': True, 'hide_untranslated': False, },""" When I change the code, it throws another error like page not found Using the URLconf defined in djcms_r.urls, Django tried these URL patterns, in this order: ^media/(?P<path>.*)$ ^static\/(?P<path>.*)$ ^sitemap\.xml$ ^ko/ ^admin/ ^ko/ ^ ^cms_login/$ [name='cms_login'] ^ko/ ^ ^cms_wizard/ ^ko/ ^ ^(?P<slug>[0-9A-Za-z-_.//]+)/$ [name='pages-details-by-slug'] ^ko/ ^ ^$ [name='pages-root'] The current path, /ko/, didn't match any of these. I tried to change the linux language using "export LC_ALL=C" but it doesn't work too. How can I fix this error? Thank you -
solving error unauthorized /rest-auth/registration/ in django allauth
Hello guys I finally can ask for help since I believe my issue is holding me back for the third day now googling. am using react in the frontend and Django in the backed and am trying to register user, the login is working like charm! but when I try creating new user I get error Unauthorized: /rest-auth/registration/ [05/Jun/2019 10:34:45] "POST /rest-auth/registration/ HTTP/1.1" 401 27 I am sure that is the path to register user because when I visit the link in the browser it works fine. the issue is I am sending data from react from end set like this return dispatch => { dispatch(authStart); axios.post('http://127.0.0.1:8000/rest-auth/registration/', { username: username, email: email, password1: password1, password2: password2 }).then(res => { const token = res.data.key; const expirationDate = new Date(new Date().getTime() + 3600 * 1000); localStorage.setItem('token', token); localStorage.setItem('expirationDate', expirationDate); dispatch(authSuccess(token)); dispatch(checkAuthTimeOut(3600)); }) .catch(err => { alert(err) // dispatch(authFail(err)) }) } and my django settings file is like this MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] #This is required otherwise it asks for email server EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' REST_AUTH_SERIALIZERS = { 'TOKEN_SERIALIZER': 'jobs_home.serializer.TokenSerializer', } ROOT_URLCONF = 'jobs_dj.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, '../build') ], 'APP_DIRS': … -
Django tutorial: name 'HttpRespone' is not defined
I was following Django tutorial to create first Django app. I wrote some codes, then run it on browser. However I got an error said: name 'HttpRespone' is not defined I have read this question too: Django Tutorial: name 'HttpResponse' is not defined. It didn't help me. Here is my code: polls\views.py from django.shortcuts import render,HttpResponse def index(request): return HttpRespone("Hello") poll\urls.py from django.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), ] mysite\urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] -
Django error: [<class 'decimal.InvalidOperation'>]
I have done the following signal in my project: @receiver(pre_save, sender=group1) @disable_for_loaddata def total_closing_group1(sender,instance,*args,**kwargs): total_group_closing_deb_po = instance.master_group.filter(ledgergroups__Closing_balance__gte=0,balance_nature='Debit').aggregate(the_sum=Coalesce(Sum('ledgergroups__Closing_balance'), Value(0)))['the_sum'] total_group_closing_deb_neg = instance.master_group.filter(ledgergroups__Closing_balance__lt=0,balance_nature='Debit').aggregate(the_sum=Coalesce(Sum('ledgergroups__Closing_balance'), Value(0)))['the_sum'] total_group_closing_po_cre = instance.master_group.filter(ledgergroups__Closing_balance__gte=0,balance_nature='Credit').aggregate(the_sum=Coalesce(Sum('ledgergroups__Closing_balance'), Value(0)))['the_sum'] total_group_closing_neg_cre = instance.master_group.filter(ledgergroups__Closing_balance__lt=0,balance_nature='Credit').aggregate(the_sum=Coalesce(Sum('ledgergroups__Closing_balance'), Value(0)))['the_sum'] total_closing_deb_po = instance.ledgergroups.filter(Closing_balance__gte=0,group1_Name__balance_nature='Debit').aggregate(the_sum=Coalesce(Sum('Closing_balance'), Value(0)))['the_sum'] total_closing_deb_ne = instance.ledgergroups.filter(Closing_balance__lt=0,group1_Name__balance_nature='Debit').aggregate(the_sum=Coalesce(Sum('Closing_balance'), Value(0)))['the_sum'] total_closing_cre_po = instance.ledgergroups.filter(Closing_balance__gte=0,group1_Name__balance_nature='Credit').aggregate(the_sum=Coalesce(Sum('Closing_balance'), Value(0)))['the_sum'] total_closing_cre_ne = instance.ledgergroups.filter(Closing_balance__lt=0,group1_Name__balance_nature='Credit').aggregate(the_sum=Coalesce(Sum('Closing_balance'), Value(0)))['the_sum'] if total_group_closing_deb_po != None and total_group_closing_neg_cre != None and total_closing_deb_po != None and total_closing_cre_ne != None: instance.positive_closing = total_group_closing_deb_po + abs(total_group_closing_neg_cre) + total_closing_deb_po + abs(total_closing_cre_ne) if total_group_closing_po_cre != None and total_group_closing_deb_neg != None and total_closing_cre_po != None and total_closing_deb_ne != None: instance.negative_closing = total_group_closing_po_cre + abs(total_group_closing_deb_neg) + total_closing_cre_po + abs(total_closing_deb_ne) My models are: class Group1(models.Model): group_name = models.CharField(max_length=32) master = models.ForeignKey("self",on_delete=models.CASCADE,related_name='master_group',null=True) negative_closing = models.DecimalField(max_digits=10,default=0,decimal_places=2,null=True) positive_closing = models.DecimalField(max_digits=10,default=0,decimal_places=2,null=True) class Ledger1(models.Model): name = models.CharField(max_length=32) group1_name = models.ForeignKey(Group1,on_delete=models.CASCADE,null=True,related_name='ledgergroups') closing_balance = models.DecimalField(default=0.00,max_digits=10,decimal_places=2,blank=True) It was working fine in the beginning but all of a sudden when I am increasing the load of the database by putting datas into fields. It is throwing me the error [<class 'decimal.InvalidOperation'>]. What this error implies? Any idea anyone Thank you -
How can I get the distinct values of queryset?
I have this query such as query1 = A.objects.filter(a=a).values('color__red') And the debugger told me that : <QuerySet [{'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}, {'color__red': 'yes'}]> I would like to count the number of distinct values of color__red (in my case it is one because color__red = 'yes' but sometimes it can be 2) I know in the case of an arrays I have to do a len(list(set(array))) but I don't achieve to get the value in the case of queryset. Could you help me please ? Thank you ! -
AttributeError at /hajj/scratchcard/2/ - 'function' object has no attribute 'objects' -
I have a model named ScartchCard with I have input PIn and Serial Number into. However, User will enter the PIN and Serial Number into form. I want my view to confirm that the Serial and pins are tally or exit in the Database. Then, the user can proceed to another page. models.py class ScratchCard(models.Model): user = models.OneToOneField(User, related_name='card', on_delete=models.CASCADE, blank=True, null=True) serial = models.CharField('Serial Number', max_length=50) pin = models.PositiveIntegerField("Card PIN") is_used = models.BooleanField(default=False) created_at = models.DateField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py def ScratchCard(request, user_id): template_name = 'scratch_card.html' if request.method == "POST": pin = request.POST.get('pin') serial = request.POST.get('serial') print(pin) print(serial) person = ScratchCard.objects.get(pin=pin) print(person) return render(request, template_name)][1] scratch_card.html <form method="post" class="form-element" novalidate> {% csrf_token %} <label for="pin">PIN No:</label> <input type="text" name="pin" placeholder="pin"> <label for="serial">Serial No:</label> <input type="text" name="serial" placeholder="serial"> <input type="submit" name="" value="Login"> </form> -
Django: Creating form to add related data
I have problem to undestand ORM in Django. I have 3 models and 2 of them use first as FK. I want to create buttons/forms which allow me to add related data. My models.py *imports* class PersonManager(models.Manager): def get_by_natural_key(self,name,surname): return self.get(name=name,surname=surname) class Person(models.Model): name = models.CharField(attributes) surname = models.CharField(attributes) objects = PersonManager() class Phone(models.Model): person = models.ForeignKey(Person.editable=False,on_delete=models.CASCADE) phone = model.CharField(attributes) class Email(models.Model): person = models.ForeignKey(Person,editable=False,on_delete=models.CASCADE) email - models.EmailField() I have form which I use to add persons to database and now I want to add buttons near to each object person which will allow me to fill phone and email, but to be honest I have no idea in which way I can connect them together -
Django rest framework JWT only works for superuser
I am trying to implement jwt token authentication in my DRF project with the settings.py file REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } AUTH_USER_MODEL = 'core.User' My urls.py contains the jwt viewset like so urlpatterns = [ path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), ..., ] I can now go to /api/token and enter a username and password to obtain { "refresh": "eyJ...", "access": "eyJ..." }, however, this only works for a superuser account generated via the shell. If I go to the standard django admin interface and add a non-superuser and try to get the token at /api/token, I just get HTTP 401 Unauthorized Allow: POST, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Bearer realm="api" { "detail": "No active account found with the given credentials" } -
I cant migrate Category model. No such table: blog_catergory. How can I fix this?
I already checked some of other posts with similar problems. I`v done all of that... I tried to delete all migrations then to migrate again. I went for syncdb option also. Still i get this error : http://prntscr.com/nxuq1d no such table. Im using django 2.5.1 version here is the code models.py from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.utils.text import slugify from ckeditor_uploader.fields import RichTextUploadingField class Category(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(max_length=150) class Meta: ordering = ('name',) verbose_name = 'catergory' verbose_name_plural = 'catergories' def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField( help_text="A short label, generally used in URLs.", default='', max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['-date_posted'] def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('detail', kwargs={'slug': self.slug}) def __str__(self): return self.title 0001_initial.py ..my only migrations. i deleted all then i migrated again import ckeditor_uploader.fields from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, … -
Query for email existing is in database and not empty
I'm looking for single-line filter query if given email is already in database but allow for empty value. forms.py def clean_email(self): email = self.cleaned_data.get('email') q = Email.objects.filter(email=email) if not email or q.count() == 0: return email raise forms.ValidationError('Podany email już widnieje w bazie') models.py class Email(models.Model): person = models.ForeignKey(Person, editable=False, on_delete=models.CASCADE) email = models.EmailField(max_length=70, blank=True) -
How to unregister table from django admin whose created when package are installed
I want to remove some table or section form my django admin. for example: i install summernote package who created attachment table in my admin. i dont want to show this table in admin (see in below screenshot) -
How do I order a field's returned objects by default after defining a through model?
I realise I have an issue with my Model names, I'll come to fix that. I have an Item model, and a Set model. Set's have a ManyToMany relationship with Item, so each Set is basically a collection of Items. The issue is, there's no order to these items when I display them, and I want to be able to order them arbitrarily. Ie. not just by date or title. I've defined a through relationship, in which Set items are defined through a new class SetMeta which has an order field. I can now set that order in my web app front end, but the actual ordering of the objects hasn't yet worked. models.py class Item(models.Model, AdminVideoMixin): title = models.TextField(max_length=5000) .... class Set(Item): items = models.ManyToManyField(Item, related_name='in_sets', through='SetMeta', max_length=5000,) def get_absolute_url(self): return reverse('curate:set_detail',kwargs={'slug':self.slug}) def get_queryset(self): return self.items.all().order_by('-itemOrder__order') def __str__(self): return self.title class SetMeta(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='itemOrder', max_length=5000) set = models.ForeignKey(Set, on_delete=models.CASCADE, related_name='SetOrder', max_length=5000) order = models.IntegerField(default=0, null=True,) def up(self): self.order += 1 self.save() print(self.order) def down(self): self.order -= 1 self.save() print(self.order) views.py def setEdit(request, slug): set = Set.objects.get(slug__exact=slug) user = request.user ### SOME OTHER STUFF ### return render(request, 'curate/set_edit.html', {'set_edit': set_edit, 'item_form': item_form, 'set' : set}) I've added … -
How do I access windows environmental variables in pipenv environment on Windows?
I set environmental variables in windows and can access them with import os os.environ.get('variable') just fine when I'm not in pipenv environment. How can I access them in pipenv? -
Access local html files in Django
I would like to access local html files from my Django app. These file are generated during the use of the webapp. How can be done? Should I store them in specific folders? Many thanks -
Django urls new views and new redirects (for old views) get confused
I used to have 2 specific urls that read like this: '/gamedata/tennis/' '/gamedata/tennis/tennis-2018' The "tennis" string comes from a Sport model, the "tennis-2018" string comes from a Season model. class Sport(models.Model): name = models.CharField(max_length=50) class Season(models.Model): ... slug = models.SlugField(...) The first url would display tennis stuff for the current season (2019) and the second one would do the same for the previous season. I wanted to make things better, so I want to use these new urls for the same outcome: '/gamedata/tennis-2019' '/gamedata/tennis-2018' I have managed to implement the change and I am now dealing with redirections for old urls. The second url ('/gamedata/tennis/tennis-2018') no problems: I can get the season slug and easily redirect to /gamedata/tennis-2019. The problem is with redirecting /gamedata/tennis to gamedata/tennis-2019. Have a look at my urls: ... url(r'^(?P<season_slug>[^/]+)/$', views.SportdataView.as_view(), name="sportdataview"), url(r'^(?P<sport_name>[^/]+)/$', views.SportdataRedirectView.as_view(), name="redirect-old-sportdata") For some reason, which I do not understand, Django brings up the same view for these 2 urls. In fact, if I invert the order of the urls, I always get the redirect view; even in the case of /gamedata/tennis-2018. What am I doing wrong with the url regex? PS I have managed to sort things out hardcoding the redirect urls …