Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to define django's many to many field in postgres?
I have a django model called Contexts which is essentially a group that has a list of users.I have another model called UserProperty which has some user information. class Contexts(models.Model): context_name = models.CharField(max_length=50) context_description = models.TextField() users = models.ManyToManyField(UserProperty , related_name='context_users') def getUserImagePath(instance,filename): return "/static/images/%s_%s"% (str(time()).replace('.','_'),filename) class UserProperty(models.Model): username = models.CharField(max_length=255, null=False) pic = models.ImageField(upload_to=getUserImagePath, default="/static/images/user.png" ,null=True, blank=True) org = models.CharField(max_length=255, null=True) This works fine in my local system when I run a migration using django manage.py.But in the server for some reason, I cannot run migrations and I have to define the models manually in postgres (the server uses django _ postgres).So this is what I did CREATE TABLE webhook_contexts(id integer, context_name character varying(100), context_description character varying(100), users text [], FOREIGN KEY (users) REFERENCES webhook_userproperty); I am not sure exactly how to replicate this in postgres.For users field in Contexts model, I did models.ManyToManyField(UserProperty , related_name='context_users') so I assume the users must be an array in postgres that contains the fields of the referenced table UserProperty namely username, pic, org.So I do .., users text [], FOREIGN KEY (users) REFERENCES webhook_userproperty) But I get this error ERROR: there is no primary key for referenced table "webhook_userproperty" But I did … -
NULL issue in django DateField
There exists a DateField field in my model, where is declared as the following: show_date = models.DateField(help_text="Please use the following format: <em>YYYY-MM-DD</em>.", blank=True, null=True) It can be null because, for some reason, we cannot get the exact date for my model, and we want to tell the differences between the ones that have show_date and the ones that do not. But from the django admin, it shows 'NoneType' object has no attribute 'year', this makes me not able editing the items How to tell the differences between the ones that have show_date and the ones that do not nicely? -
`migrate` fails to detect new model
I've just created a new model in project/posts/models.py but manage.py migrate completes without creating the new model. Similarly manage.py makemigrations detects no changes either and returns No changes detected. Does anyone know why the new model is not detected? -
Does Caddy server serves Django static and media files?
No. 4 of this says Take care of your statics and medias Normally I takes care them by Nginx in dev-server or S3/CloudFront in prod-server. But this time I judge Caddy is a webserver like Nginx. Then I read on the DockerFile. But I couldn't find any example of them Question: My understanding is when I use Caddy I have to use something else to serve statics and medias. Am I correct? If not please show the reference then I will study further -
python django : list index out of bound
enter image description here this the error which is shown to me. I have checked everywhere in my code but i could not trace the problem. -
Django SingleObjectMixin: Page not found(404)
I am currently working on a blog for a project, and i want to add in a comment section for each post in the DetailView. My code seems fine, however i keep getting a "Page not Found(404) error". I am thinking it may be my url pattern but i cannot seem to figure out what i am doing wrong. error given url.py urlpatterns[ path('blog/post/<int:pk>/', views.PostDetailView.as_view(),name='post_detail'), path('blog/post/<int:pk>/comment/', views.MyFormView.as_view(), name='my_form_view_url'), ] forms.py class CommentForm(forms.ModelForm): class Meta(): model = Comment fields = ('text',) widgets = { 'text': forms.Textarea(attrs={'class':'ediable medium-editor-textarea'}) } views.py class PostDetailView(DetailView): model = Post template_name = 'carsforsale/post_detail.html' def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['form'] = CommentForm() return context class MyFormView(SingleObjectMixin,FormView): template_name = 'carsforsale/post_detail.html' form_class = CommentForm model = Comment def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) def get_success_url(self): return reverse('carsforsale:post_detail', kwargs={'pk': self.object.pk}) post_detail.html this is the form inside of the post_detail.html <form method="POST" action="{% url 'carsforsale:my_form_view_url' pk=post.pk %}"> {% csrf_token %} <div class="form-group"> {% render_field form.text class="form-control text" rows=3 %} </div> <input type="submit" class="btn btn-primary" value="Comment" /> </form> -
Django localization and csrf_token issues
I'm working on e-bookstore project inspired by the book Django 2 by Example At this dev-stage my project contains: Book catalog Book details Cart Promo-codes(Coupons) Orders & Payments via PayPal Landing page & Newsletter subscription Site recommendations I've decided to add custom user logging system and user profiles, and It was easy (thanks to Django). Everything related to site logic worked fine until I started working on localizing the site into Russian. After that, some problems appeared: #1 The books were removed from the basket not immediately, but only after switching to any other page of the site. #2 Changing the information in the user's profile also broken now - changes will be applied only when I switched to other pages, and/or when I'm switching the site language. #3. When I'm playing with site logic (ex: add some book to user cart, change book quantity, clear cart, edit profile, surfing the book catalog) I can admit that cart(or user) data is obsolete, then refresh the page and it's OK. No errors, no 500s, were noticed You can go and check my source code on GitHub. I can't place all the code here.Please, download and test It if you want. Adding … -
Python/Dango with Stripe: Error in Post request in creating stripe subscription
This is my first time using stripe does this look familiar to anyone? So I am able to see that a token is being created upon payment, but instead of being redirected to my template, i throws this error below! ERROR >**InvalidRequestError:** >Request req_d5BvUPtlpLrsG5: Received unknown parameter: source >Request Method: POST >Django Version: 2.1 >Exception Type: InvalidRequestError >Exception Value: >**Request req_d5BvUPtlpLrsG5: Received unknown parameter: source** CODE def PaymentView(request): user_membership = get_user_membership(request) selected_membership = get_selected_membership(request) publishKey = settings.STRIPE_PUBLISHABLE_KEY if request.method == "POST": try: token = request.POST['stripeToken'] subscription = stripe.Subscription.create( customer=user_membership.stripe_customer_id,# id on User Membership Model items=[ { "plan": selected_membership.stripe_plan_id, }, ], source=token # 4242424242424242 ) return redirect(reverse('memberships:update-transactions', kwargs={ 'subscription_id': subscription.id })) except stripe.error.CardError as e: messages.info(request, "Your card has been declined") context = { 'publishKey': publishKey, 'selected_membership': selected_membership } return render(request, "path/templategoeshere.html", context) -
Authenticate method has stopped working
I have an application in Django that worked perfectly until I tried what this guide says: https://scribles.net/deploying-existing-django-app-to-heroku/ Now when I try to log in with a user, it always returns a NonType The application opens normally, I can recover the password, modify it.... but do not log in. The DB contains the user, so it has not been deleted. When I execute the following statement in the django shell I get the following: user = authenticate(username='email@gmail.com', password='1234') user.name AttributeError: 'NoneType' object has no attribute 'name' >>>tpye(user) <class 'NoneType'> Which makes me think that authenticate is always returning a NonType to me, because the User object does have the name property. I've tried to fix it by running the following commands: pipenv uninstall django-heroku pipenv clean pipenv install (all packages again) pipenv lock I've tried to fix it errase DB and created it again and removing the header I created in the settings.py file As a curious fact, when I try to open the application's database without being connected to the internet, (it's local, so I shouldn't need the internet... and I didn't need it before) I get the following message: Image It should not be a problem in my code … -
Django database: how to filter objects based on other object's field?
In the code below, how do I filter capital_listings so to return listings only for capital cities? Also, is it possible to get rid of the intermediate capitals_names list? capitals = City.objects.filter(status='capital') capitals_names = [capital.name for capital in capitals] capital_listings = Listing.objects.filter #??? Models: class Listing(models.Model): city = models.CharField(max_length = 30, default = 'placeholder') date_added = models.DateTimeField() def __str__(self): return self.name class City(models.Model): name = models.CharField(max_length = 30, default = 'placeholder') status = models.CharField(max_length = 30, default = 'placeholder') def __str__(self): return self.name -
django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library
I'm trying to use gis in the docker: This is Dockerfile of django: FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ # CFFI dependencies && apk add libffi-dev py-cffi \ # Translations dependencies && apk add gettext \ # https://docs.djangoproject.com/en/dev/ref/django-admin/#dbshell && apk add postgresql-client # ADD PostGIS here # POSTGIS dependencies ENV POSTGIS_VERSION 2.4.4 ENV POSTGIS_SHA256 0dff4902556ad45430e2b85dbe7e9baa758c6eb0bfd5ff6948f478beddd56b67 RUN set -ex \ \ && apk add --no-cache --virtual .fetch-deps \ ca-certificates \ openssl \ tar \ \ && wget -O postgis.tar.gz "https://github.com/postgis/postgis/archive/$POSTGIS_VERSION.tar.gz" \ && echo "$POSTGIS_SHA256 *postgis.tar.gz" | sha256sum -c - \ && mkdir -p /usr/src/postgis \ && tar \ --extract \ --file postgis.tar.gz \ --directory /usr/src/postgis \ --strip-components 1 \ && rm postgis.tar.gz \ \ && apk add --no-cache --virtual .build-deps \ autoconf \ automake \ g++ \ json-c-dev \ libtool \ libxml2-dev \ make \ perl \ \ # add libcrypto from (edge:main) for gdal-2.3.0 && apk add --no-cache --virtual .crypto-rundeps \ --repository http://dl-cdn.alpinelinux.org/alpine/edge/main \ libressl2.7-libcrypto \ && apk add --no-cache --virtual .build-deps-testing \ --repository http://dl-cdn.alpinelinux.org/alpine/edge/testing … -
Allowed host for Django with uWSGI not connecting using IPV6?
Allowed host for Django with uWSGI not connecting? Allowed hosts are [::]:8080 and [domain_name::]:8080 uWSGI in terminal is: uwsgi --http :8080 --home /home/user/mysite --chdir /home/user/mysite -w mysite.wsgi so trying wwww.domain_name.com:8080 is not connecting. But with the development server it is connecting. -
Accessing local mysql server from my docker container
I have a mysql server and a docker container running on my machine. In the docker container, I run a django website. I want to connect to the local mysql server from the docker container. How can I do that? -
Django Select2Widget has no attribute "attrs"
I am trying to implement django_select2 in an form, but when I try to render the page I get the following error: type object 'Select2Widget' has no attribute 'attrs' The widget is declared like this(it's a modelform): self.fields["prodotti_var"].widget = Select2Widget Here is the complete traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/magazzino/bolle_in/5/ Django Version: 2.0.6 Python Version: 3.6.5 Installed Applications: ['django_select2', 'actstream', 'amministrazione', 'clienti', 'fornitori', 'prodotti', 'documenti', 'fatture', 'admin_interface', 'colorfield', 'magazzino', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', 'widget_tweaks'] Installed 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'] Template error: In template /home/matteo/Naturelab/amministrazione/templates/base_site.html, error at line 0 type object 'Select2Widget' has no attribute 'attrs' 1 : {% load static %} 2 : {% load widget_tweaks %} 3 : <!DOCTYPE html> 4 : <!-- 5 : Template Name: LuMa CMS 6 : Version: 1.0 7 : Author: LucyT & MatFire1999 8 : Contact: hello@lumacms.com 9 : --> 10 : <html lang="it"> Traceback: File "/home/matteo/virtualenvs/Naturelab/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/matteo/virtualenvs/Naturelab/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/matteo/virtualenvs/Naturelab/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/matteo/Naturelab/magazzino/views.py" in ddt_in_detail 76. return render(request, "ddt_in_mod.html", context) File "/home/matteo/virtualenvs/Naturelab/lib/python3.6/site-packages/django/shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File … -
Run Discord bot inside Django
Hello I would like to have a discord bot that accesses a Django DB. An obvious solution is to have 2 separate scripts. I would like to know if there is a way to make the discord-bot part of the Django as an app or something. -
How do I run a django project when it is written in Linux, do I have Windows?
I download django-project Linux. Now, i try run it Windows. Project dont hawe setting.py end i dont know how to run him? When i start project i have massage "module not found", and i dont know how need to do. Manage.py if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings.dev") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) Error File "", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'website.settings' -
Mistake of running Django project
I have 2 project but when want to run first project ,the result for second project: the second project is stop. python 3 install -
Django generating sitemap from third party data
I have a website which pulls data from third party using API. Third party API can send a json response for all "querystring", and in second API call I can pull data for each querystring. Basically the API urls will looks something like below: apiexample.com/?querystring="searchterm" Now I process this data and show in my website with below url: example.com/details/querystring Its working fine. Now I need to generate a sitemap with urls: example.com/details/querystring example.com/details/querystring1 example.com/details/querystring2............ API can give list of all possible querystring. How do I generate sitemap in Django? Normally with my own models I do something like this: class qssitemap(Sitemap): def items(self): return modelsname.objects.filter() def location(self, obj): return reverse('slugdata',kwargs={'slug':obj.slug_tn,'pk':obj.id}) -
Django query of many to many relation by count of items
I have word model and phrase model class Word(models.Model): .... class Phrase(models.Model): words = models.ManyToManyField(Word, null=True,related_name = "phrases") I need to perform a complex query: We say that Word is unique if it belongs only to one Phrase . If Phrase has at least 2 unique words => we say it's special I need to find all words that can be found in special phrases So far I am doing this by iterating using for..in loop but it doesn't seem to be effective. How do I do this? (Phrase will always have at least one word and word will always have at least one phrase. -
Dynamic job scheduling in django project
I want to apply dynamic job scheduling in Django project. my desired scenario- admin can introduce activities to their teams member. this activities will flash on company's portal. so admin can post more than one activities and scheduled them. so now if admin post 3 activities A ( for 13-08-2018 at 3pm), B(for 15-08-2018 at 12pm) , c(for 18-08-2018 at 10Am) so if today is 13th aug so at 3pm activity A should be flash on portal, in this scenario I need to implement dynamic job scheduling. Any idea how can I achieve this in Django. Please help. Thanks in advance -
How to create dependent drop down box in django from two different models?
I want to create a dependency drop down list to get result and student table. from student model, I have to get an available batch in the drop down in a page. and get the available course corresponding/depending on the batch in the second drop down. If I hit submit, it will show the list of all students with the same batch and their results on the selected course in a page List item My models.py is: from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.db.models.signals import post_save from django.dispatch import receiver from django.core.validators import RegexValidator from smart_selects.db_fields import ChainedForeignKey class Course(models.Model): cid = models.AutoField(primary_key=True) cnam = models.CharField(max_length=200) cidn = models.IntegerField() cred = models.IntegerField() def __str__(self): return 'IT-' + str(self.cidn) + ' - ' + self.cnam class Student(models.Model): snam = models.CharField(max_length=200) sid = models.AutoField(primary_key=True) sroll = models.IntegerField() sreg = models.IntegerField() sbtc = models.IntegerField() sses = models.CharField(max_length=10) def __str__(self): return self.snam class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_regex = RegexValidator(regex=r'^\0?1?\d{11}$') mobile = models.CharField(validators=[phone_regex], max_length=11, blank=True) avatar = models.ImageField(upload_to='avater', blank=True) def __str__(self): return self.user.first_name + ' '+self.user.last_name @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Teacher.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.teacher.save() class Session(models.Model): sesid … -
serializer fields are missing in the response: Django REST Frameword
I'm using Django 2.0 and Django REST Framework. I have two models contact and transaction as below contact model class Contact(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, blank=True, null=True) amount given model class AmountGiven(models.Model): contact = models.ForeignKey(Contact, on_delete=models.PROTECT) amount = models.FloatField(help_text='Amount given to the contact') interest_rate = models.FloatField(blank=True, default=None, null=True, help_text='% of interest to be calculated') _given_date = models.DateTimeField( db_column='given_date', default=timezone.now, help_text='Date and time when amount was given to the contact' ) def __str__(self): return str(self.amount) @property def given_date(self): return self._given_date @given_date.setter def given_date(self, value): self._given_date = value @property def interest_to_pay(self): if self.interest_rate: datetime_diff = datetime.now(get_localzone()) - self.given_date days = datetime_diff.days duration_in_year = days/365 simple_interest_amount = (self.amount * duration_in_year * self.interest_rate)/100 return simple_interest_amount return 0 @property def total_payable(self): return self.amount + self.interest_to_pay @property def amount_due(self): returned_amount = 0 for returned in self.amountreturned_set.all(): returned_amount += returned.amount return self.total_payable - returned_amount and ContactSerializer class ContactSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedRelatedField( view_name='contacts:detail', read_only=True ) user = serializers.CurrentUserDefault() amount_due = ReadOnlyField(source='amountgiven__amount_due') class Meta: model = Contact fields = ('url', 'id', 'first_name', 'last_name', 'full_name', 'amount_due') and in views.py class ContactViewSet(viewsets.ModelViewSet): serializer_class = ContactSerializer permission_classes = (IsAuthenticated, AdminAuthenticationPermission,) def get_queryset(self): return Contact.objects.filter(user=self.request.user) def perform_create(self, serializer): serializer.save(user=self.request.user) But there is no field as amount_due and … -
Django : using url in path causes error 'Uncaught SyntaxError'
I'm going to use uuid in the url like this. path('cafe/menu/edit/<uuid:menu_id>/', cafe.CafeMenuEditView, name='cafe_menu_edit'), and when I try to access this url, it gaves me error message in chrome console log like this. Uncaught SyntaxError: Invalid regular expression flags I would like to know if there is special way to use uuid in django. -
How are fixture objects written to the Django DB?
I have a model A with an overriden models.Model.save(…) method where I instantiate additional objects upon saving an instance of A. That is, whenever a new A instance is written to the DB or an existing instance gets updated and then saved, a new instance of B is created. When using a fixture to provide the DB with an initial A instance, the A instance is created as expected but to my surprise after running loaddata no B instance is present in the DB. This leads me to believe that As save(…) method is not called during loading the fixture. Is this the default behaviour? Are fixture objects not created via the Django ORM system? If so, does this mean that I would have to manually create the B instance by specifying it in the fixture? -
Calculate the sum by group using Queryset API
I have such a following table: MySQL [distributor]> select * from orderitems; +-----------+------------+---------+----------+------------+ | order_num | order_item | prod_id | quantity | item_price | +-----------+------------+---------+----------+------------+ | 20005 | 1 | BR01 | 100 | 5.49 | | 20005 | 2 | BR03 | 100 | 10.99 | | 20006 | 1 | BR01 | 20 | 5.99 | | 20006 | 2 | BR02 | 10 | 8.99 | | 20006 | 3 | BR03 | 10 | 11.99 | | 20007 | 1 | BR03 | 50 | 11.49 | | 20007 | 2 | BNBG01 | 100 | 2.99 | | 20007 | 3 | BNBG02 | 100 | 2.99 | | 20007 | 4 | BNBG03 | 100 | 2.99 | | 20007 | 5 | RGAN01 | 50 | 4.49 | | 20008 | 1 | RGAN01 | 5 | 4.99 | | 20008 | 2 | BR03 | 5 | 11.99 | | 20008 | 3 | BNBG01 | 10 | 3.49 | | 20008 | 4 | BNBG02 | 10 | 3.49 | | 20008 | 5 | BNBG03 | 10 | 3.49 | | 20009 | 1 | BNBG01 | 250 | 2.49 …