Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Filter - 'str' object has no attribute '_meta', possibly related to circular imports?
In order to avoid a circular import I am using 'app.model' as a foreign key, However since I made that that change im now seeing the error: sites.models: class Site(models.Model): location = models.CharField(max_length=50) tel = models.CharField(max_length=20, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) town = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) region = models.ForeignKey(Region, verbose_name="Region", on_delete=models.CASCADE) country = models.CharField(max_length=255, blank=True, null=True) postcode = models.CharField(max_length=10, blank=True, null=True) active_link = models.OneToOneField('circuit.Circuit', verbose_name="Active Circuit", blank=True, null=True, on_delete=models.CASCADE) active_link_timestamp = models.DateTimeField(blank=True, null=True) circuits.models: class Circuit(models.Model): site = models.OneToOneField(Site, on_delete=models.CASCADE, verbose_name="Site", blank=True, null=True) subnet = models.OneToOneField(Subnet, on_delete=models.CASCADE, verbose_name="Subnet", blank=True, null=True) name = models.CharField(max_length=200, verbose_name="Name", blank=True, null=True) order_no = models.CharField(max_length=200, verbose_name="Order No") ref_no = models.CharField(max_length=200, verbose_name="Reference No") sites.filters: import django_filters, itertools from django.db.models import Q from sites.models import * from sites.forms import * class SiteFilter(django_filters.FilterSet): location = django_filters.CharFilter(lookup_expr='icontains') town = django_filters.CharFilter(lookup_expr='icontains') postcode = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Site exclude = () Error: File "/myapp/myapp/myapp/urls.py", line 21, in <module> path('sites/', include('sites.urls')), File "/usr/local/lib/python3.7/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", … -
How to add custom left-link models to wagtail admin page
I've been trying to add a left-link to the wagtail administration interface sidebar so that I can provide an easier experience to moderators. My ultimate goal is to add a collection of custom objects (already made), editable from the sidebar from wagtail's admin interface, and displaying that collection on the site's home page. Wagtail left links example (taken from official documentation) I'm new to python/Django and especially new in Wagtail, but I didn't find any help with this on official documentation. Is there an easy way to do this? Or you have to edit Wagtail source code? Thanks a lot in advance -
Django building a messaging system
I'm trying to build a messaging system for my website using Django but I don't know how to do. What I want is a system that enables a user to send a message to another user, with an inbox to see the received messages and notifications that warn the user he received messages. Since it's a feature many websites need, I guess there already exists some build-in functions and templates to do that in Django. I made some researchs and I found existing apps like django-messages or django-postman but there are little or no documentations about these apps, the ways to use it in the view, the way to customize the message model or the templates, ... . I guess these apps are not widely used since there are no tutorials about them or precise documentation, but I didn't found other apps for messaging. To summarize my question, what is the easiest way to build a customizable messaging system in Django ? If it's an app, where can I find good and easy documentation/tutorial about it ? Thanks in advance ! -
Split testing layouts for Djang-CMS
I know there are things like django-experiments which do split testing at the python level. What I need is a tool to have multiple published versions of a single page in django-cms and a way to toggle between them. Basically we want to split test layouts of a page more than actual functionality to see what has the best user retention. I haven't found any good examples of how to implement anything similar to this with django-cms. -
Count instances from multiple foreign key through multiple models
I have those models in Django (1.11): class Provider(models.Model): name = models.CharField(max_length=200) def get_contracts_number(self, kwargs): total = 0 for offer in self.offer_set.all(): total += offer.get_contracts_number(kwargs) return total class Offer(models.Model): name = models.CharField(max_length=200) provider = models.ForeignKey("Provider", on_delete=models.CASCADE) def get_contracts_number(self, kwargs): total = 0 total += self.contract_elec_set.filter(**kwargs).count() total += self.contract_gas_set.filter(**kwargs).count() total += self.contractgastank_set.filter(**kwargs).count() total += self.contractboilerinstallation_set.filter(**kwargs).count() total += self.contractboilermaintenance_set.filter(**kwargs).count() total += self.contractcomble_set.filter(**kwargs).count() total += self.contractinsurance_set.filter(**kwargs).count() return total class Contract_elec(models.Model): offer = models.ForeignKey( "Offer", on_delete=models.SET_NULL, verbose_name="Offre", null=True ) date_lead = models.DateTimeField() class Contract_gas(models.Model): offer = models.ForeignKey( "Offer", on_delete=models.SET_NULL, verbose_name="Offre", null=True ) date_lead = models.DateTimeField() And so on (I have in total 7 contracts types). Differents contracts types can point to the same offer. I wish to count all contracts for each provider (for all of its offers), when date_lead > to one choosen date. I manage to do that with my two methods get_contracts_number but I think this is really not optimized. I tried some stuff with annotates and aggregates without much result. What I should I do? Thanks in advance -
How to properly patch with ModelSerializer?
I'm trying to .save() my data in database. Models.py: class Hero(models.Model): Hero_id = models.IntegerField(auto_created=True, primary_key=True, serialize=False, verbose_name='Hero_id') race = models.CharField(max_length=50, blank=True) age = models.IntegerField(blank=True) class_= models.CharField(max_length=50, blank=True) Views.py: class HeroSerializer(serializers.ModelSerializer): class Meta: model = Hero fields = ['Hero_id', 'race', 'age', 'class_'] extra_kwargs = { 'race': { 'required': False, 'allow_null':True }, 'age': { 'required': False, 'allow_null':True }, 'class_': { 'required': False, 'allow_null':True } } def PATCH(request): if request.method == "PATCH": stream = io.BytesIO(request.body) data = JSONParser().parse(stream) serializer = HeroSerializer(data=data["json"],partial=True) if serializer.is_valid(): serializer.save() return JsonResponse(data,save=False) return JsonResponse(serializer.errors) My incoming data is always containing Hero_id. Example: {"json":{"Hero_id":"4", "race":"orc"}} or {"json":{"Hero_id":"4", "race":"Human", "age":"34", "class_":"archer"}} Questions: 1)How to patch specific row in database depending on Hero_id? 2)How can I pass a request.data? I always get an error 'WSGIRequest' object has no attribute 'data'. 3)Is there any difference between JSONParser().parse(io.BytesIO(request.body)) and request.data in my case? -
Django project has an internal 'lib' folder that has all Independence. How can i use .bash_profile project link dependencies
I have a Django 1.2 web app. It uses python 2.7 and has very old libraries. The project has a folder called 'lib' and 'webapp_extras" that have all the dependicnes. But when i run it, it gives the following error: File main.py, line , in <module> from google.appengine.ext import db ImportError: No module named google.appengine.ext How can i tell the project to look in the 'lib' or project root for the dependencies? So far i have tried to use a .bash_profile and set $PYTHONPATH to try and make it look in the correct folder. /.bash_profile $PYTHONPATH="${PYTHONPATH}:/home/<path to root folder>/" export PYTHONPATH Am i doing something wrong? Also i tried to pip install all the dependencies and it gives me an error when i try to install google-appengine pip install google-appengine #main error "HTTP Error 403: SSL is required" -
How to setup docker compose with redis, sentinel and django+celery
I'm having trouble with the setup of sentinel on docker. Everything I've found looks old and deprecated and having issues when I'm trying to run. I'm using docker-compose with code like this : redis-master image: redis:4.0.11-alpine volumes: - broker-data:/data networks: - db ports: - 6379:6379 redis-slave: image: redis:4.0.11-alpine command: - redis-server --slaveof redis-master 6379 volumes: - broker-data:/data networks: - db links: - redis-master sentinel: build: ./sentinel volumes: - broker-data:/data networks: - db ports: - 26379:26379 links: - redis-slave - redis-master And sentinel from https://github.com/mustafaileri/redis-cluster-with-sentinel/tree/master/sentinel This part seems to run correctly but Celery (onboarded in Django) doesn't found it. CELERY_BROKER_URL="sentinel://sentinel:26379/0" and I tried to change the transport options, but always have No master found for None error when starting django with docker-compose. CELERY_BROKER_TRANSPORT_OPTIONS={"my_master":"redis-master", "master_name":"redis-master"} Any idea about a mistake I made, or good tips to use sentinel on django with docker ? -
Django - display image from static folder in accordance to values from DB
I have a Django app which has a model that holds cities, counties and countries codes: models.py class AreaMap(models.Model): Code = models.AutoField(primary_key=True) fCityCode = models.CharField( verbose_name='City', max_length=100) fCountyCode = models.CharField( verbose_name='County', max_length=100) fCountryCode = models.CharField( verbose_name='Country', max_length=100) def __str__(self): return self.fCityCode For each city, I have some static images in my static folder which are not going to be changed (or at least, if required, the old file would be overwritten with a new one but keeping the same filename). The correspondence between the image and the value from the database is by field 'fCityCode`: Example: For New York - in the database is saved as 'NewYork' and the image filename from my static folder is the same, 'NewYork'. Now, I would like to display in my HTML template every image from the folder that corresponds to a value from the database. I've done some research and I read that when it comes to static images is better to import them from the static folder rather than storing the images in the database which makes sense. Is there any way of doing this mapping and achieving this using Django? Thanks -
How can I access model instance in save_related method of ModelAdmin class?
I have a model with 2 attributes which value depends on related items: class Offer(models.Model): rating = models.DecimalField(max_digits=3, decimal_places=1, default=0) count = models.IntegerField(default=0) Related items are set as inlines of model in admin page. I want to execute two functions after adding new related items via admin page. When I overwrite save_model method new related items are not saved yet as apparently save_related method executes after save_model class OfferAdmin(admin.ModelAdmin): model = Offer inlines = [ CommentInline ] def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) obj.rating = get_rating(obj) obj.count = get_count(obj) obj.save() How can I access object and make changes in model instance in save_related? -
Django Json like button and counting likes isn't working
i'm making a like button in Django with a JSON code but i when I click the like button it doesn't increment the number of likes in this product or pass the like (as this hunter liked this product).Do I need to make a separate class for like in models.py, if so what should be in it. Or is it that the slug isn't set up the right way. In the urls.py and models.py I'm showing all the code, in views.py only the method of the like button and the imports, and in detail.html only the HTML tag's for the like button and the JSON script. I'm working with : Django Version: 2.2.9 Python Version: 3.7.4 . The models.py in the app "products": from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify from django.urls import reverse class Product(models.Model): title = models.CharField(max_length = 80) pub_date = models.DateTimeField() body = models.TextField() url = models.TextField() image = models.ImageField(upload_to = 'images/') icon = models.ImageField(upload_to = 'icon/') votes_total = models.IntegerField(default=1) slug = models.SlugField(null=False, unique=True) likes = models.ManyToManyField(User, blank=True, related_name='likes') hunter = models.ForeignKey(User, on_delete = models.CASCADE) def __str__(self): return self.title def summary(self): return self.body[:100] + "..." def pub_date_pretty(self): return self.pub_date.strftime("%b %e %Y") def … -
Which skills are actually required to build a good web application or a website? [closed]
I am stuck in just learning so many things. Now I know python, JavaScript, HTML, CSS and learning django and jQuery. I don't know the best way. Now a days i want to build a shop with sign up and sign in system and online order (a website or web application i even don't know). Can someone help me. -
How to import auth.User on django-import/export
I can't import a CSV file into model on Django. I made a column 'author' and put the superuser's id which I am login to the admin site. But there was an error like this when I import the CSV file. Line number: 1 - null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (10, abc, blahblah, null, ). 5, abc, blahblah, , nah,wha,blah csv file author,title,text,file,free_tags 5,abc,blahblah,,"nah,wha,blah" models.py from django.db import models from django.urls import reverse from taggit.managers import TaggableManager class KnowHow(models.Model): author = models.ForeignKey('auth.User',on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField(blank=True) file = models.FileField(blank=True,upload_to='explicit_knowhows') free_tags = TaggableManager(blank=True) def __str__(self): return self.title admin.py from django.contrib import admin from import_export import resources from import_export import fields from import_export.admin import ImportExportModelAdmin from .models import KnowHow # Register your models here. class KnowHowResource(resources.ModelResource): class Meta: model = KnowHow exclude = 'id' import_id_fields = ('title', ) @admin.register(KnowHow) class knowHowAdmin(ImportExportModelAdmin): resource_class = KnowHowResource -
Jquery Ajax submit() not firing in django model form
I've tried looking up online, rewriting the code but the submit() won't fire but when I use a click event, it fire an calls the callback and the ajax() runs. I cannot figure out what's really wrong with the code even after going through so many tutorials and documentation online. Here's the code: HTML template with the form {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- site icon --> <link rel="icon" href="{% static 'img/question.png' %}"> <!-- Bootstrap core CSS --> <link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Font Awesome --> <link href="{% static 'css/font-awesome.min.css' %}" rel="stylesheet"> <!-- Endless --> <link href="{% static 'css/endless.min.css' %}" rel="stylesheet"> </head> <body> <div class="login-wrapper"> <div class="text-center"> <span> <img src="{% static 'img/question.png' %}" style="height: 100px; width: 100px; border-radius: 50%;"> </span> </div> <div class="text-center"> <h2 class="fadeInUp animation-delay8" style="font-weight:bold"> <span class="text-success">CitiSpy User Login</span> </h2> </div> <div class="login-widget animation-delay1"> <div class="panel panel-default"> <div class="panel-heading clearfix"> <div class="pull-left"> <i class="fa fa-lock fa-lg"></i> Login </div> </div> <div class="panel-body"> <div id="login-form-main-message"></div> <form class="form-login" id="login_form" method="POST"> {% csrf_token %} <div id="form_content"> {{ form.non_field_errors }} <div class="form-group"> {{ form.email.errors }} <label for="{{ form.email.id_for_label }}">{{ form.email.label }}</label> {{ form.email }} … -
Vimrc for react, angular, node, phyton
Some have set up the vimrc to work for web development in a proper way. I would like to use the vim again but I've been trying to configure it for days and I can't get it to work correctly. I would be interested in completing the code, and checking the errors for Django, Nodejs, React, angular 8 The error control works with the Ale Plugin, but it doesn't quite convince me at all -
What is the meaning of "Model.delete() isn't called on related models" in Django Doc
I was reading Django's article on model fields and models.CASCADE. I don't understand this phrase: Model.delete() isn’t called on related models models.CASCADE means that related objects to delete when the target object deleted ,so what is the meaning of "isn't called on related models"? Please explain that for me. -
Error on setting Environment variables in Google Cloud using the SDK
I am trying to set up Environment Variables for my django app on google cloud. I entered the following on the SDK: gcloud functions deploy env_vars --runtime python37 --set-env-vars SUBSCRIPTION_KEY=1234567890 --trigger-http The error returned was: ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Build failed: {"error": {"canonicalCode": "INTERNAL", "errorMessage": "`pip_install_from_wheels` had stderr output:\n/opt/python3.7/bin/python3.7: No module named pip\n\nerror: `pip_install_from_wheels` returned code: 1", "errorType": "InternalError", "errorId": "ECB5F712"}} Please help. -
Context is not displaying in the template when using ListView
I can't understand why nothing comes out in the html template. class TrainersListView(ListView): model = Profile template_name = 'trainers.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) _list = Profile.objects.filter(city__slug=self.kwargs['slug']).order_by('id') context['trainers'] = _list print(len(context['trainers']) --> return 5 html {% for trainer in trainers %} {{ trainer.id }} {% endfor %} Even if I take out all the instances _list = Profile.objects.all() still a blank result -
How can I put django static files in javascript array?
I need to get static files from django to a "links" array... var links = [ '/static/uploads/fth/FthAgg.xlsx', '/static/uploads/fth/FthCon.xlsx' ]; This wont work though. When I try to put https links it will work. Im doing this so that i can later download these files simultaniously with one button. Here is my javascript file: https://pastebin.com/0sCTav8G Here is my html template: https://pastebin.com/yvz2AL0M -
Why in python lowe-case "a" is greater than capital "A"? [duplicate]
This question already has an answer here: String comparison technique used by Python 8 answers I have problem to understand why: print("a" > "A") is True and why: print("a" > "b") is False -
Authentication Error when trying to reset password - django
I try to reset password with gmail.com. I think I set everything correct, but it's still doesn't work and raise error like so: settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') I set my enviroment variables EMAIL_USER (login to my gmail account) and EMAIL_PASS (16-sign password provided by Google when you use 2-step authentication - Google App Password). I tried also use password to my gmail account but this also not work. Someone know what I do wrong ? Thanks for any help. -
What exactly is the condition for executing the m2m_changed signal?
I have an overridden save() method of the model, in which, after performing some actions, an object of another model(Clients) is created using the command "model_name.objects.create". Everything worked perfectly. Then I needed the m2m_changed signal to extract data from ManyToManyField, because save() method is not capable of this. In the function associated with m2m_changed, I execute other code that is not related to creating an object of another model(Clients), which I described above. To apply the changes in the signal function, I call "instance.save()". After executing the code, I look at the contents of Clients in the database and there, instead of one value(1), another(3) is written. So I wonder what the hell does the m2m_changed signal function do? It is somehow linked to the "super().save(*args, **kwargs)" save command? -
Python Django Celery, terminating running task not working
I create an web app, where users can run multiple scripts (django tasks). I went through this artcle and found out that i have to use --pool (prefork, eventlet or gevent) not solo because more scripts can run in one time. What i need is to be able to terminate the running task if user needs to do so therefore i need to use only prefork . I found that eventlet and gevent do not have implemented revoke method. Now the issue. When i run --pool with eventlet or gevent , the task is received and executed. But i cannot terminate it as said. When i run --pool with prefork , it should be able to terminate the task, but when i run the task it is only received but not even executed. And the last think i do no realy understand. I tried to start with --pole=solo just to try revoking tasks (but i cannot use this later, because i need to run more scripts in one time). And revoke method here does nothing. app.control.revoke(task_id, terminate=True) So my question is what should i use, to be able to terminate tasks and to be able to run more tasks in … -
Django RadioSelect field not rendering correctly
I'm using Django FilterSet to enable the user to filter a list of products on my website. Everything is working perfectly, I'm using standard html code to display a form. However there is a RadioSelect field that is not rendering correclty and I don't understand why. I provide you below the relevant parts of my code as well as a screenshot of the rendering problem. Does anyone know how I can solve that ? filters.py class PlatFilter(django_filters.FilterSet): titre = django_filters.CharFilter( field_name='titre', label='Mot clé :', lookup_expr='icontains', widget=forms.TextInput(attrs={'class': 'form-control'}), ) prix_min = django_filters.NumberFilter( field_name='prix', label='Prix minimum :', lookup_expr='gte', widget=forms.NumberInput(attrs={'class': 'form-control'}), ) prix_max = django_filters.NumberFilter( field_name='prix', label='Prix maximum :', lookup_expr='lte', widget=forms.NumberInput(attrs={'class': 'form-control'}), ) nb_portions = django_filters.NumberFilter( field_name='nb_portions', label='Nombre de portions minimum :', lookup_expr='gte', widget=forms.NumberInput(attrs={'class': 'form-control'}), ) date_prep = django_filters.DateFilter( field_name='date_prep__date', label='Date de préparation (format JJ/MM/AAAA)', lookup_expr='exact', widget=forms.DateTimeInput(attrs={'class': 'form-control'}), ) CHOICES = ((True, 'Oui'), (False, 'Non')) is_delivering = django_filters.BooleanFilter( field_name='chef__is_delivering', label='Livraison comprise', widget=forms.RadioSelect(attrs={'class': 'form-control'}, choices=CHOICES), ) class Meta: model = Plat fields = ['titre', 'nb_portions', 'date_prep'] html file (using Bootstrap) <div class="col-md-3"> <div class="filters shadow-sm rounded bg-white mb-4"> <div class="filters-header border-bottom pl-4 pr-4 pt-3 pb-3"> <h5 class="m-0" style="font-size: 200%">Filtrer par</h5> </div> <div class="filters-body"> <form method="get"> <div class="well"> <div class="row"> <div class="col-md-12 pl-5 pb-4 pt-4 … -
auth.user.none and <QuerySet []> in ManyToManyField rendering
I try to display numbers of Users who liked some image on my website written in Django. The Image model looks like this below: class Image(models.Model): (***) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked', blank=True) When I use in my template: {{image.users_like.all}} I get : QuerySet [], when I use in templates {{image.users_like}} I get auth.User.None. It's weird because in my admin page I have information that someone liked this photo. Below my view function: def image_detail(request, id, slug): image = get_object_or_404(Image, id=id, slug=slug) return render(request, 'images/image/detail.html', {'section': 'images', 'image': image})