Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django oscar multiple bulk offers
I'm new to django oscar framework. when i'm add two bulk offers with offer condition type called Coverage. i'm only getting one bulk offer.. my basket has a1 and a2 product bulk offer 1, products in offer a1, a2 bulk offer 2, products in offer a1, b2 its only add bulk offer 1, my problem is want to get two offers separately -
How do i set the current logged in user as default in Django view when no url parameters are given
i want the /profile/ route to be accessible without having to pass any url argument This is my profile View: @login_required def profile(request, username): ctx = {"username" : username} return render(request, "raynet/profile.html",ctx) This is my url pattern: urlpatterns = [ path('', views.landing), path('home/', views.home), path('profile/', views.profile), path('profile/<username>', views.profile), path('apps/', views.apps), path('signin/', views.signin), path('signup/', views.signup), path('testing/', views.testing), path('signout/', views.signout), ] It works fine if i specify a username in the url, but it doesnt work if i just go to /profile/ I want to get the current logged in user as default when no url variable is specified. -
OSError: libjson-c.so.3: cannot open shared object file: No such file or directory
My Amazon EBS EC2 is looking for libjson-c.so.3, I tried running 'yum install json-c' but that didn't help my issue. Can anyone point me in the right direction. I'm trying to run a Django web application with GeoDjango and it's returning this error... the previous error was looking for libcrypto.so.1.1, I was able to fix that by reinstalling a later version of openssl. I'm not sure why that was relevant though. [Wed Feb 19 04:46:01.617682 2020] [:error] [pid 32491] from .fields import ( # NOQA [Wed Feb 19 04:46:01.617688 2020] [:error] [pid 32491] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/contrib/gis/forms/fields.py", line 2, in <module> [Wed Feb 19 04:46:01.617691 2020] [:error] [pid 32491] from django.contrib.gis.geos import GEOSException, GEOSGeometry [Wed Feb 19 04:46:01.617696 2020] [:error] [pid 32491] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/contrib/gis/geos/__init__.py", line 5, in <module> [Wed Feb 19 04:46:01.617699 2020] [:error] [pid 32491] from .collections import ( # NOQA [Wed Feb 19 04:46:01.617704 2020] [:error] [pid 32491] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/contrib/gis/geos/collections.py", line 9, in <module> [Wed Feb 19 04:46:01.617707 2020] [:error] [pid 32491] from django.contrib.gis.geos.geometry import GEOSGeometry, LinearGeometryMixin [Wed Feb 19 04:46:01.617712 2020] [:error] [pid 32491] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/contrib/gis/geos/geometry.py", line 8, in <module> [Wed Feb 19 04:46:01.617715 2020] [:error] [pid 32491] from django.contrib.gis import gdal [Wed Feb 19 04:46:01.617720 2020] [:error] [pid … -
None type object has no attribute delete()
getting error 'NoneType' object has no attribute 'delete' class LogoutViewSet(viewsets.ViewSet): def (self,request): user_token=request.auth refresh_token=RefreshToken.objects.filter(access_token=user_token) refresh_token.delete() user_token.delete() return Response({'done':True}) -
You are trying to add a non-nullable field 'owner' to product without a default
You are trying to add a non-nullable field 'owner' to product without a default; we can't do that (the database needs something to populate existing rows -
django.db.utils.OperationalError: (1045, "Access denied for user 'epaysave_user'@'localhost'
I am running a website using Django. Below is my error: django.db.utils.OperationalError: (1045, "Access denied for user 'epaysave_user'@'localhost' (using password: YES)") Below is what i have tried: GRANT ALL PRIVILEGES ON `epaysave_db_prod`.* TO 'epaysave_user'@'localhost'IDENTIFIED BY PASSWORD 'MYPASSWORD'; FLUSH PRIVILEGES; Still i am getting the error. Why is that? -
TypeError: my_task() takes 2 positional arguments but 3 were given
This is a headscratcher... I have the following view: def progress_view(request): result = hello.tasks.my_task.delay(8, request.POST.get('account_name')) return render(request, 'display_progress.html', {'task_id': result.task_id}) I also have the following in tasks.py @shared_task(bind=True) def my_task(self, seconds, account_name): progress_recorder = ProgressRecorder(self) result = 0 pprint(seconds) pprint(account_name) for i in range(seconds): timeline = api.GetUserTimeline(screen_name=account_name, include_rts=True, trim_user=True, exclude_replies=True, count=2) time.sleep(1) result += i progress_recorder.set_progress(i + 1, seconds) return result The call: result = hello.tasks.my_task.delay(8, request.POST.get('account_name')) gives me: TypeError: my_task() takes 2 positional arguments but 3 were given The full traceback is as follows: [2020-02-19 15:28:58,951: ERROR/ForkPoolWorker-4] Task hello.tasks.my_task[5b4f0731-0c48-4bd3-ac5d-8c585a0758c8] raised unexpected: TypeError('my_task() takes 2 positional arguments but 3 were given',) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery. /app/trace.py", line 382, in trace_task R = retval = fun(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery. /app/trace.py", line 641, in __protected_call__ return self.run(*args, **kwargs) TypeError: my_task() takes 2 positional arguments but 3 were given [2020-02-19 15:29:30,479: ERROR/ForkPoolWorker-6] Task hello.tasks.my_task[a17c78e5-4835-4a31-a000-d0a0955c91e0] raised unexpected: TypeError('my_task() takes 2 positional arguments but 3 were given',) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery. /app/trace.py", line 382, in trace_task R = retval = fun(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/celery. /app/trace.py", line 641, in __protected_call__ return self.run(*args, **kwargs) TypeError: my_task() takes 2 positional arguments but 3 were given -
Django SPA application
I have created a site with django as a multi page application and everything was working smoothly until the company asked my to integrate a player for the radio station they own. I created the multipage application with a base.html and i extend it in the other page of the site. Then i integrated the player (it´s a JavaScript player) so i call the JavaScript file, assign some parameters with a const and it loads properly. But obviously it´s a multi page application and every time a user navigates through the pages the player stops because all the content is reloaded. Right now i included a way to navigate as a SPA $.ajax({ url: pageurl + '?', success: function (data) { $('#mainContent').html(data); //.... } }); and load content in a div with Ajax and also update the history with window.history.pushState() but every time i navigate ajax loads all my site and breaks the JavaScript i use for the player. How can i replace the extends that i used so when i make the ajax calls it doesn´t reload all the site again and also, how can i make this changes without losing direct links navigation. -
Django + Heroku: KeyError when accessing Heroku's config vars
I'm trying to get all the environment variables from Heroku's config vars by following this page. So in settings.py I wrote: import os from dotenv import load_dotenv from boto.s3.connection import S3Connection # ... load_dotenv(verbose=True) # ... s3 = S3Connection(os.environ['SECRET_KEY'], os.environ['DATABASE_URL'], os.environ['SENDGRID_API_KEY']) SECRET_KEY = os.getenv('SECRET_KEY') # ... if os.environ.get('DEBUG') is None: DEBUG = False else: DEBUG = True # ... # Sending emails SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY') EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = SENDGRID_API_KEY EMAIL_PORT = 587 EMAIL_USE_TLS = True # ... I want to have a local .env that contains those vars, and use Heroku's config vars in production. But when I deploy, I get an Application Error, and this is the result of heroku logs --tail: 2020-02-19T04:09:27.730183+00:00 app[web.1]: File "/app/smart_toilet_system/settings.py", line 34, in <module> 2020-02-19T04:09:27.730183+00:00 app[web.1]: os.environ['SENDGRID_API_KEY']) 2020-02-19T04:09:27.730183+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/boto/s3/connection.py", line 194, in __init__ 2020-02-19T04:09:27.730184+00:00 app[web.1]: validate_certs=validate_certs, profile_name=profile_name) 2020-02-19T04:09:27.730184+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/boto/connection.py", line 502, in __init__ 2020-02-19T04:09:27.730185+00:00 app[web.1]: self.port = PORTS_BY_SECURITY[is_secure] 2020-02-19T04:09:27.730185+00:00 app[web.1]: KeyError: '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' 2020-02-19T04:09:27.730911+00:00 app[web.1]: [2020-02-19 04:09:27 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-02-19T04:09:27.838786+00:00 app[web.1]: [2020-02-19 04:09:27 +0000] [4] [INFO] Shutting down: Master 2020-02-19T04:09:27.839030+00:00 app[web.1]: [2020-02-19 04:09:27 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-02-19T04:09:28.081341+00:00 heroku[web.1]: State changed from up to crashed 2020-02-19T04:09:28.062132+00:00 … -
Docker + Django + Nginx Random Intermittent 504
I am working on containerizing a Django application with Docker but I am having a lot of trouble getting the application to run consistently. My configuration below: Dockerfile FROM ubuntu:18.04 RUN apt-get update -y RUN apt-get upgrade -y RUN apt-get install -y \ nginx \ git \ python3 \ python3-dev \ python3-pip \ build-essential \ libpq-dev RUN apt-get install postgresql-client -y RUN mkdir /config COPY requirements.txt /config/ RUN pip3 install --no-cache-dir -r /config/requirements.txt COPY wait-for-postgres.sh /config/ RUN chmod +x /config/wait-for-postgres.sh RUN mkdir /src COPY ./src /src WORKDIR /src docker-compose.yml version: '3' services: db: image: postgres:9.5 container_name: pg01 environment: POSTGRES_PASSWORD: dusk web: build: . command: ["/config/wait-for-postgres.sh", "db", "python3", "manage.py", "runserver", "0.0.0.0:8000"] expose: - "8000" depends_on: - db - nginx container_name: dj01 environment: POSTGRES_PASSWORD: mypass PGPASSWORD: mypass PGHOST: postgres PGPORT: 5432 nginx: image: nginx:latest container_name: ng01 ports: - "8000:8000" volumes: - ./config/nginx:/etc/nginx/conf.d - ./src/static:/static nginx.conf upstream web { ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /static/; } location / { proxy_pass http://web/; } listen 8000; server_name localhost; } I'm running the application with docker-compose up --build and about 95% of the time I get a 504 timeout. The other 5% of the time the application loads. Sometimes … -
How To reverse a URL with hyphens in the name?
I have a Django Application, with a file like the next one app_something/url.py: from django.urls import include, path, re_path from rest_framework import routers from . import views slashless_router = routers.DefaultRouter(trailing_slash=True) router = routers.DefaultRouter() router.register(r'complex-name', views.ComplexNameModelViewSet) router.register(r'simple', views.SimpleModelViewSet) app_name='something' urlpatterns = [ path('api/', include(router.urls)), ] It works perfect. Or that is what I used to think. Now, I'm trying to add Tests (Yep, my bad they should be there first) BUT, now in my test_complex_name_api.py: from django.urls import reverse from rest_framework import status from app_something import models, serializers SIMPLE_MODEL_NAME_URL = reverse('something:simple-list') COMPLEX_MODEL_NAME_URL = reverse('something:complex-name-list') # ... # My Tests But, when I run my tests I got next error: django.urls.exceptions.NoReverseMatch: Reverse for 'complex-name-list' not found. 'complex-name-list' is not a valid view function or pattern name. SimpleModel works pretty cool. So, I think it's related to the name. But I haven't found which should be the name pattern to use? Should I rename the url or can I still use in this way and I'm only missing the part of the docs which talk about this? (I read from: https://www.django-rest-framework.org/api-guide/routers/) -
Django app on Heroku: Issues with continuous development AFTER deployment
So, I just updated my Django app for Heroku and GIT pushed my master branch to production for the first time. Works well. However, when I try to run my app locally on the same master branch, I get all these errors. Understandably, since I've updated the settings file specifically for production on Heroku. My question is the following: If I want to continue my development locally and periodically push stable versions to production, do I need to maintain 2 settings.py files? (ie, one for dev and one for prod) I'm a beginner, so sorry if this question sounds ridiculous, but I can't seem to find any clear information about this, after reading Heroku's documentation about deployment: https://devcenter.heroku.com/articles/git I just want to be able to continue running my development locally. Any suggestions would be greatly appreciated. -
listing out particular folder name content on website using django
I want to list out files from particular folder on s3..On s3 I have created User wise directory so I want to list out only those directory which has user name on it and no all directory other than that...how to do this? I am doing it on django -
Many-to-Many relationships Direct assignment to the forward side of a many-to-many set is prohibited
Ive created a few models, one with a many to many relationship. class PBSItems(models.Model): PBSCode = models.CharField(max_length=6, primary_key=True) RestrictFlag = models.CharField(max_length=1) eAuthQuant = models.TextField() def __str__(self): return self.PBSCode class Restrictions(models.Model): IndicatId = models.IntegerField(primary_key=True) RestrictFullText = models.CharField(max_length=17040) def __str__(self): return self.IndicatId class Drug(models.Model): PBSCode = models.ForeignKey(PBSItems, null=True, on_delete = models.CASCADE) def __str__(self): return self.PBSCode class Links(models.Model): PBSCode = models.ManyToManyField(Drug) IndicatId = models.ForeignKey(Restrictions, on_delete = models.CASCADE) def __str__(self): return self.IndicatId However, once I create the instances for PBSItems, Restrictions and Drug, and I try and create the instance for Links, I get the following message: TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use PBSCode.set() instead. How do I use PBSCode.set() in the model, or how do I get around this issue? Many thanks -
A a foreign key child model multiple dynamic forms inside Model
The following is the registered admin models: models.py class TestMain(models.Model): course = models.ForeignKey(Course, on_delete=models.PROTECT) question = models.TextField(max_length=200, unique=True) ## If I uncomment below and comment question attr in TestChild it doesnt work # answerfk = models.ForeignKey(TestAnswer, related_name="answerfk", on_delete=models.PROTECT) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return '{} - QUESTION: {}'.format(self.course, self.question) class TestChild(models.Model): ## If I comment below and uncomment answerfk attr in TestMain it doesnt work question = models.ForeignKey(TestMain, related_name="questionfk", on_delete=models.PROTECT) answer = models.CharField(max_length=250, default=None) correct_answer = models.BooleanField(verbose_name="correct answer", default=False, editable=True) answer_comment = models.CharField(max_length=250, unique=False, default=None) internal_comments = models.CharField(max_length=250, unique=False, default=None) def __str__(self): return '{} ANSWER: {} {}'.format(self.question.question, self.answer, self.correct_answer) forms.py from django import forms class TestMainForm(forms.ModelForm): pass class TestChildForm(forms.ModelForm): pass admin.py class TestChildInline(admin.TabularInline): model = TestChild fk_name = "question" extra = 0 def get_formset(self, request, obj=None, **kwargs): TestChildInline.form = type( 'TestChildInlineAlt', (TestChildForm, ), {}) formset = super(TestChildInline, self).get_formset(request, obj, **kwargs) return formset class TestMainAdmin(admin.ModelAdmin): inlines = [TestChildInline, ] admin.site.register(TestMain, TestMainAdmin) The goal is to have a TestMain form and a dynamic multiple form addition for TestChild. The issue I am facing is if I have the foreign key (models.ForeignKey) in the TestMain (answerfk) to TestChild (answer attr) then the inline for TestChildInline gives an error … -
Django Admin edit related custom user model
I have the following models: class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) All the django admin docs specify that I can edit the Student in the User view, but I have multiple models that have a related user so that solution does not work. I would like to be able to edit the User from the Student and the Teacher views. -
How do I make my model's depdent fields appear in my JSON using Django serializers?
I'm using Django 2.0 and Python 3.7. I have the following models ... from django.db import models from address.models import AddressField from phonenumber_field.modelfields import PhoneNumberField from address.models import State from address.models import Country class CoopTypeManager(models.Manager): def get_by_natural_key(self, name): return self.get_or_create(name=name)[0] class CoopType(models.Model): name = models.CharField(max_length=200, null=False) objects = CoopTypeManager() class Meta: unique_together = ("name",) class Coop(models.Model): name = models.CharField(max_length=250, null=False) type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() And then I created the following serializers ... from rest_framework import serializers from maps.models import Coop, CoopType class CoopSerializer(serializers.ModelSerializer): class Meta: model = Coop fields = ['id', 'name', 'type', 'address', 'enabled', 'phone', 'email', 'web_site'] def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Coop.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Coop` instance, given the validated data. """ instance.name = validated_data.get('name', instance.name) instance.type = validated_data.get('type', instance.type) instance.address = validated_data.get('address', instance.address) instance.enabled = validated_data.get('enabled', instance.enabled) instance.phone = validated_data.get('phone', instance.phone) instance.email = validated_data.get('email', instance.email) instance.web_site = validated_data.get('web_site', instance.web_site) instance.save() return instance class CoopTypeSerializer(serializers.ModelSerializer): class Meta: model = CoopType fields = ['id', 'name'] def create(self, validated_data): """ Create and return a new … -
Django custom ModelManagers to implicitly restrict queryets available per user
My use case is that I want different users to be able to work on their own projects and be restricted from seeing material in other projects, even in the Admin site. There are a number of models that ought to be filtered back to 'project' - for example a concrete Answer extends the Abstract class Answer, which has question as a foreign key and Question which have project as a foreign key. My plan was to modify the default ModelManager get_queryset() and return a queryset with a filter something like: Project.objects.filter(group__in=user.groups.all()) The challenge is for the ModelManager to reliably know which user is calling it, without changing the signature every time a queryset is produced. I found this solution, which looks extremely smooth: Middleware maintaining a dict of requests indexed by the thread handling them But its from 2010 and I'm not sure how much Django, Python, thread-handling, the security landscape etc may have changed in the mean time. Is there now a preferred way to do this, with sessions perhaps? -
Using Django's CheckConstraint with annotations
I have a Django model where each instance requires a unique identifier that is derived from three fields: class Example(Model): type = CharField(blank=False, null=False) # either 'A' or 'B' timestamp = DateTimeField(default=timezone.now) number = models.IntegerField(null=True) # a sequential number This produces a label of the form [type][timestamp YEAR][number], which must be unique unless number is null. I thought I might be able to use a couple of annotations: uid_expr = Case( When( number=None, then=Value(None), ), default=Concat( 'type', ExtractYear('released_at'), 'number', output_field=models.CharField() ), output_field=models.CharField() ) uid_count_expr = Count('uid', distinct=True) I overrode the model's manager's get_queryset to apply the annotations by default and then tried to use CheckConstraint: class Example(Model): ... class Meta: constraints = [ models.CheckConstraint(check=Q(uid_cnt=1), name='unique_uid') ] This fails because it's unable to find a field on the instance called uid_cnt, however I thought annotations were accessible to Q objects? Are constraints applied against something other than the queryset returned by the model manager? Is there a way to apply a constraint to an annotation? I'd really like to enforce this at the db layer. Thanks. -
How to use a form to update a model while displaying the data already stored in Django?
I have a model called Client and I want to update through a form, and I want that form to display the info that is already stored. This is the model: class Clients(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, verbose_name="Morada") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], unique=True, null=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) avatar = models.ImageField(null=True) def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) class Meta: verbose_name_plural = "Clientes" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Clients.objects.create(user=instance) instance.clients.save() This is my views.py def client_det(request, nif): instance = Client.objects.get(nif=nif) form = UpdateClient(request.POST or None, instance=instance) if form.is_valid(): form.save() return redirect('clients') return render(request, 'backend/client_detail.html', {'form': form}) And this is my forms.py class UpdateClient(forms.ModelForm): address = forms.CharField(max_length=200, label="Morada", widget=forms.TextInput(attrs={'class': 'form-control'})) nif = forms.CharField(max_length=9, label="NIF", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control'})) mobile = forms.CharField(max_length=9, label="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control'})) def clean_nif(self): nif = self.cleaned_data['nif']; if Clients.objects.filter(nif=nif).exists(): raise forms.ValidationError("NIF já existente.") return nif class Meta: model = User fields = ('email', 'first_name', 'last_name', 'address', 'nif', 'mobile') def __init__(self, *args, **kwargs): super(UpdateClient, self).__init__(*args, **kwargs) self.fields['first_name'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['last_name'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['email'].widget = EmailInput(attrs={'class': 'form-control'}) Right now, the form gets rendered but it only shows the data from address, mobile and nif, from the Client model. The … -
How to add moderation to a model in Django_comments
My first question is, is it possible to check if a user has already flagged a comment in the template? 2nd question, I was reading through the code for the django_comments frameworks, It reads as follows in these lines: is_removed = models.BooleanField(_('is removed'), default=False, help_text=_('Check this box if the answer is inappropriate. ' 'A "This comment has been removed" message will ' 'be displayed instead.')) However, when I do that(check the is_removed), the text 'A "This comment has been removed"' is never displayed, instead, the comment disappears completely. How do I get the message to display when the is_removed is checked? 3rd Question, I am unable to get the bad words moderation to work. I have a profanity word list set up in my settings.py # Moderate Answers COMMENTS_ALLOW_PROFANITIES = False PROFANITIES_LIST = ('Be quiet',) But the profanity words just doesn't prevent the comment from being posted Here is my post moderator. Do I need to do more extension to get the above functionalities? from django_comments.moderation import CommentModerator, moderator class PostModerator(CommentModerator): email_notification = False enable_field = 'enable_comments' moderator.register(Post, PostModerator) Thank you. -
Repurposing old project for a new app, trying to figure out what i was doing, in order to fix this error (django)
Traceback: $ python3 manage.py migrate /home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 79, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 267, in build_graph raise exc File "/home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 241, in build_graph self.graph.validate_consistency() File "/home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/django/db/migrations/graph.py", line 243, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/django/db/migrations/graph.py", line 243, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/home/michael/projects/znet/bosnet/bosnetvenv/lib/python3.6/site-packages/django/db/migrations/graph.py", line 96, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration engine.0002_auto_20180914_1228 dependencies reference nonexistent parent node ('powerdns_manager', '0007_auto_20180909_1126') As you can see, I am using the django_powerdns_manager package (you can find this on github: https://github.com/kumina/django-powerdns-manager/). One of my migrations has a powerdns_manager table as a dependency. I'll just post the … -
CSRF Cookie error with Chrome browser that I cannot solve
I'm using javascript with a Django api to submit a modal form. I'm sending a CSRF cookie that works in other circumstances (like on other browsers or with other forms in Chrome), but when I submit a Django form, but it fails on chrome and I get the following error: Error: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. How might I fix this and what other information do you need? -
Django// How to display complex depth data in template
Django 2.2// python 3.6// I have a context created with a combination of 'list' and 'dictionary'. The data structure is shown below. { "Mike":[ { "month":"2020-02", "consult_counts_total":2, "consult_counts_total_uid":2 }, { "month":"2020-01", "consult_counts_total":4, "consult_counts_total_uid":7 }, { "month":"2019-12", "consult_counts_total":6, "consult_counts_total_uid":1 } ], "Jaden":[ { "month":"2020-02", "consult_counts_total":8, "consult_counts_total_uid":12 }, { "month":"2020-01", "consult_counts_total":23, "consult_counts_total_uid":11 }, { "month":"2019-12", "consult_counts_total":2, "consult_counts_total_uid":19 } ], "Sarah":[ { "month":"2020-02", "consult_counts_total":2, "consult_counts_total_uid":2 }, { "month":"2020-01", "consult_counts_total":4, "consult_counts_total_uid":7 }, { "month":"2019-12", "consult_counts_total":6, "consult_counts_total_uid":1 } ], "John":[ { "month":"2020-02", "consult_counts_total":1, "consult_counts_total_uid":0 }, { "month":"2020-01", "consult_counts_total":2, "consult_counts_total_uid":7 }, { "month":"2019-12", "consult_counts_total":5, "consult_counts_total_uid":1 } ] } I'm trying to display this data through a loop in template. First I'v tried. It shows nice result. {% for foo in context_data %} <p>{{ foo }}</p> {% endfor %} # result Mike Jaden Sarah John But I can't get more depth data. For example, I want to get Mike's all months (2020-02, 2020-01, 2019-12) Second tried.. {% for foo in context_data %} <p class="big">This is {{ foo }}'s months.</p> {% for foo2 in foo %} <p class="small">{{ foo2.months }}</p> {% endfor %} {% endfor %} # but it's showing nothing Third tried.. {% for foo in context_data %} <p class="big">This is {{ foo }}'s months.</p> {% for … -
How to display label from many-to-many relationship
I have got a main table called Item, which is connected to table Label with many-to-many relationship. I would like to display the label in the view, but it doesnt work. I have tried item.label.name which gives value None and item.label gives core.Label.None. What would be the right way to display the label? views.py def HomeView(request): item_list = Item.objects.all() item_list = item_list.annotate( current_price=Coalesce('discount_price', 'price')) category_list = Category.objects.all() label_list = Label.objects.all() query = request.GET.get('q') if query: item_list = item_list.filter(title__icontains=query) cat = request.GET.get('cat') if cat: item_list = item_list.filter(category__pk=cat) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') if price_from: item_list = item_list.filter(current_price__gte=price_from) if price_to: item_list = item_list.filter(current_price__lte=price_to) paginator = Paginator(item_list, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'items': items, 'category': category_list, 'label': label_list } return render(request, "home.html", context) hmtl template: {% for item in items %} <div class="col-lg-3 col-md-6 mb-4"> <div class="card"> <div class="view overlay"> <img src="{{ item.image.url }}" class="card-img-top"> <a href="{{ item.get_absolute_url }}"> <div class="mask rgba-white-slight"></div> </a> </div> <div class="card-body text-center"> <h5> <strong> <a href="{{ item.get_absolute_url }}" class="dark-grey-text">{{ item.title }} <span class="badge badge-pill "></span> <p>{{ item.label }}</p> </a> </strong> </h5> <h4 class="font-weight-bold blue-text"> <strong> {% if item.discount_price %} <strike>£{{ item.price …