Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django reduce(or_) - How can I store an unmatched query with 0 results in a variable
I have a function that takes a user's input from a list of data and searches my database for any items that matches the user's input, and returns all results that are in my database: results = results.filter( reduce(or_, (Q(name__icontains=itm.strip()) for itm in query)) ) I would like to handle cases where the user's input is not present in my database. since results fitlers down to what exists, how can I check if the above code failed to find at least one matching result for a query, and store that query in a variable? -
How to find an aggregate count min count of related objects of related objects
I have models with relations likes this: Parent(models.Model): pass Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) Grandchild(models.Model): child = models.ForeignKey(Child, on_delete=models.CASCADE) I am trying to find a way to annotate a queryset of parent with an aggregate of counts of grandchildren. For example, say 2 parents: (A, B). A has 3 children: (A.a, A.b, A.c). A.a has 1 grandchildren, A.b has 2 grandchildren, A.c has 3 grandchildren, B has 2 children: (B.a, B.b). B.a has 2 grandchildren. B.b has 3 grandchildren. I want to annotate the parent queryset with an aggregate of the grandchild count for each child count on each parent. E.g. aggregating with Min would be A:1, B: 2. I believe this make need .extra to accomplish, but I am not sure. -
Wagtail - Programatically Edit Existing Page
How do i edit an existing Wagtail page programatically? There's a few explanations of how to add new pages, but i still can't seem to figure out how to edit a single field on an existing page. I'd like to use the 'Title' field as reference. This seems to be completely undocumented officially, but there is a nice written guide to adding pages programatically here. -
Ternary model association in Django
I've modeled a UML class Diagram like this UML Diagram with ternary association I want to translate this association to Django. I have the following: class Crypto(models.Model): cryptoName = models.CharField(max_length=64, primary_key=True) class Worker(models.Model): name = models.CharField(max_length=64) lastname = models.CharField(max_length=64) email = models.EmailField(max_length=128, primary_key=True) tlf = models.CharField(max_length=20) cryptos = models.ManyToManyField(Crypto) class Operation(models.Model): refNum = models.IntegerField() datetime = models.DateTimeField() amount = models.FloatField() amountCrypto = models.FloatField() I'm stuck at trying to represent the ternary association. Django has the through attr for ManyToManyField but, as you can see, the association is not m2m in any way, but mostly one-to-many. So how is the best way to represent this ternary association with Django models? -
How to add search bar on django2
I want add a search bar but i have this error OSError at /search/ [Errno 36] File name too long: urls: path('search/', views.search, name="search")' on view: def search(request): query = request.GET['search'] results = Products.objects.filter(Q(categoria__icontains=query)|Q(text__icontains=query)).values('text','category','type') context = {'results':results} return render('search.html', context) on the html {% if results %} {% for item in results %} <div class="col"> <div class="card bg-light"> <div class="card-body"> {{ results.texto }} </div> <div class="card-body"> Más del Tema : {{results.categoria}}</a> </div> </div> </div> {% endfor %} {% else %} <p>We dont have articles about that topic.</p> {% endif %} </div> -
Error was: cannot import name 'GDALRaster' on Wondows 10 for GeoDjango
I am trying to follow GeoDjango Tutorial . I am using a windows-10 64bit computer. and I am using Python 3.6 and Django 1.11 I followed the GeoDjango Windows Documentation to install. I have successfully completed all the steps it told me to I also downloaded and ran OSGeo4W and successfully ran the paths in my cmd.exe as administrator Now getting back to the Django Tutorial Create a Spatial Database: I made a Database in my Postgres Sql I started a Django project called geodjango, Started a app called world I changed the database in the setting to DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geodjango', 'USER': 'geo', }, } I added the below in my installed apps apps 'django.contrib.gis', 'world', I made a directory called data in the world application. I downloaded the zip file and unzipped it in my data folder. I have the below files in my data folder Use ogrinfo to examine spatial data(I dint know what to do here, So I ignored this part) I successfully made the models.py like it says in the tutorial from django.contrib.gis.db import models class WorldBorder(models.Model): # Regular Django fields corresponding to the attributes in the # world borders … -
Django queryset (filter based on other fields in the same model)
class PriceRepository(models.Model): product = models.ForeignKey(Product, related_name='price_repo') price = models.DecimalField('price of product', max_digits=7, decimal_places=2) location = models.ForeignKey(Location, on_blank=True, null=True, related_name='price_repo') is_default = models.BooleanField() This is my model class. I want to create a queryset such that I pick a price, if a location is specified and if such record doesn't exists for a product, I want to pick the price with is_default set. It is given that there will always be one default price. PriceRepository.objects.filter(location__id=1) returns records with prices for location.id = 1. I want to return default price for all the products present in PriceRepository , if location.id = 1 is missing How do I approach this problem? -
Extending standard Django admin, and using it as standalone
Is there a way to fully extend and override specific parts of the standard Django admin, and use it in my projects as the standalone application, the way in which I would not need to add both links, 'django.contrib.admin' and 'custom.admin' in INSTALLED_APPS config. At the moment, I copied templates and static folders, and it worked, but then I needed some new logic and copied sites.py where I extended AdminSite with CustomAdminSite(admin.AdminSite), and this when I started to get errors about missing components, for example, the most recent error Model class django.contrib.admin.models.LogEntry doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. So basically I want custom.admin to call all necessary components from django.contrib.admin and for my application just call custom.admin. -
Django queryset object attributs
How can I access a queryset object attributes if the attribute name is stored in a variable. such as name = "symbol" list = ticker.objects.filter(symbol = "AMZN") output = (list[0])[name] I am trying to get all the combinations but its not working. I am trying to avoid converting the queryset to json object as some fields of the model act as foreign keys and their values are not properly stored in the json output. -
ForwardManyToOneDescriptor AttributeError
This error is not consistent. Sometimes I'm facing this error. What could causes following problem? AttributeError 'User' object has no attribute '_type_cache' django/db/models/fields/related_descriptors.py in __get__ at line 178 # The related instance is loaded from the database and then cached in # the attribute defined in self.cache_name. It can also be pre-cached # by the reverse accessor (ReverseOneToOneDescriptor). try: rel_obj = getattr(instance, self.cache_name) except AttributeError: val = self.field.get_local_related_value(instance) if None in val: rel_obj = None else: -
How do I create a Django 2.0 database entry when the attributes are delivered with a string?
Lets say I have a django model class, say class customers(models.Model): name=models.TextField(max_length=40) age=models.PositiveSmallIntegerField(default=0) haircolor=models.TextField(max_length=20) You get the information from a python variable list: var=[name=betty, age=20, gender=female] and you want to do something like >> customers.objects.create(var) E.g. >> customers.objects.create(str.join(',',var)) does not work. For instance you want to write this code into the clean method of another model. Thank you in advance! -
In Django, does the intermediate model need to belong in the same file as the target model?
When running a migration, I am currently getting this lazy reference ValueError whenever the model that I have a defined ManyToManyField is in a separate file from the model that I am targeting. However, when I place the two models in the same file, I am able to successfully run the mirgation. Why is this error happening? Is it possible to separate the models (community.py and community_member.py) into separate files? ValueError: contains a lazy reference to fitness.communitymember, but app 'fitness' doesn't provide model 'communitymember'. My directory structure looks like this: fitness |----models |----user.py |----community.py |----community_member.py community.py class Community(models.Model): id = models.AutoField( primary_key=True, ) owner = models.ForeignKey( User, ) members = models.ManyToManyField( User, through='CommunityMember', through_fields=('community', 'member') ) class Meta: db_table = 'Communities' community_member.py class CommunityMember(models.Model): community = models.ForeignKey( Community, db_column='community_id' ) member = models.ForeignKey( User, db_column='member_id', ) class Meta: db_table = 'Community_Members' If I place the contents of community_members.py inside of community.py the migration is successfully executes, but I am not sure why. -
(Django) disable button after one click(or only submit once even clicked multiple times)
Likes field is a ManyToManyField and I want to render the post in order from most likes to least. ... order_by("-likes") didn't work and I don't see why here's the code. I'm guessing it's because it's not an integer but I can't just do ... order_by("-likes.count"), right? views.py def top_Post(request, id=None): queryset_list = Post.objects.all().order_by("-likes") paginator = Paginator(queryset_list, 10) page = request.GET.get('page') try: queryset = paginator.page(page) except PageNotAnInteger: queryset = paginator.page(1) except EmptyPage: queryset = paginator.page(paginator.num_pages) context = { "object_list":queryset, "title":"List", } return render(request, 'blog/top.html', context) top.html {% for obj in object_list %} <div class="card border-success mb-3" style="max-width: 54rem;"> <div class="card-header bg-transparent border-success">{{ obj.user|truncatechars:12}} <br> <small>{{ obj.date|timesince }} ago</small> </div> <div class="card-body text-success"> <h5 class="card-title">{{ obj.title |truncatechars:13 }}</h5> <p class="card-text">{{ obj.body|truncatechars:20 }}</p> <a class="btn btn-outline-success" href="{{ obj.get_absolute_url }}" role="button">Detail</a> </div> <div class="card-footer bg-transparent border-success"> {{obj.text_author|truncatechars:25 }}</div> </div> {% endfor %} models.py class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True) date = models.DateTimeField(auto_now=True, auto_now_add=False) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='post_likes') text_author = models.CharField(max_length=200, null=True, blank=True) -
Django - A Single Column Form Layout
I'm trying to display a django form in a single column in stead of in the default two-column display. not like this... ...but rather like this! I've been looking through some videos and posts, and found only methods like using crispy-forms and the like, but it strikes me, that that's an awful lot of lines of code to add for achieving such a tiny goal. - Might there be a simpler sollution perhaps (otherwise, which is the best method)? :) -
in Django ORM, how to get a count in a reverse set query
I have these three models: class Member (models.Model): FederationID = models.FloatField(unique=True) User = models.ForeignKey(User, on_delete=models.CASCADE) height = models.IntegerField(blank=True, null=True) eye = models.CharField(blank=True, null=True, max_length=10) hair = models.CharField(blank=True, null=True, max_length=10) birthdate = models.DateField() bio = models.TextField() Address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, blank=True) Phone = models.ForeignKey(Phone, on_delete=models.CASCADE, null=True, blank=True) Photos = models.ManyToManyField(Photos) Rank = models.ManyToManyField('Rank', through='Promotion') Unit = models.ManyToManyField('Unit', through='Assignment') class Genre(models.Model): ShortName = models.CharField(max_length=50) LongName = models.CharField(max_length=500) def __str__(self): return self.LongName + ' (' + self.ShortName + ')' class Career(models.Model): ShortName = models.CharField(max_length=50) LongName = models.CharField(max_length=500) def __str__(self): return self.LongName + ' (' + self.ShortName + ')' class Rank(models.Model): RANK_TYPE_CHOICES = ( ('O', 'Officer'), ('E', 'Enlisted'), ('V', 'Civilian'), ('C', 'Cadet'), ) ShortName = models.CharField(max_length=50) LongName = models.CharField(max_length=500) Type = models.CharField(max_length=1, choices=RANK_TYPE_CHOICES, default='O') Genre = models.ForeignKey(Genre, on_delete=models.DO_NOTHING) Career = models.ForeignKey(Career, on_delete=models.DO_NOTHING) image = models.ForeignKey(Photos, on_delete=models.DO_NOTHING) def __str__(self): return self.LongName + ' (' + self.Career.LongName + ') from ' + self.Genre.LongName class Promotion(models.Model): Rank = models.ForeignKey(Rank, on_delete=models.DO_NOTHING) Member = models.ForeignKey(Member, on_delete=models.CASCADE) PromotionDate = models.DateField(default=now) def __str__(self): return self.Member.User.first_name + ' ' + self.Member.User.last_name + ' promoted to ' + self.Rank.LongName + ' on ' + str(self.PromotionDate) I created a many-to-many relationship between Rank and Member via Promotion. In the model Rank, I have … -
Gmail API error when access token expires (Python, Django): HttpAccessTokenRefreshError invalid_client: The OAuth client was not found
i'm building a Django project. I need to send emails through Gmail's API, so i created a project, got API keys, oauth credentials, etc. I managed to do the "authorization" part, where the user signs in, gives you permission to read + send emails (with access_type=offline, as far as I know) and you get an access_token. I save the "access_token", the "expires_in" and the "refresh_token" fields for the user in a database. Then, i can read the labels of the user's emails, send emails in his name, etc. No problem. The problem arises once the access_token expires (so, after an hour of the user giving permission). When trying to send an email, the error i get is: HttpAccessTokenRefreshError at /test_gmail_api3/ invalid_client: The OAuth client was not found. I browsed a lot of related stackoverflow questions and tried changing a lot of different things but nothing works. The only thing that works is manually revoking access from my test gmail account, giving access again, and then it works perfectly... until the access_token expires again. This is the error: screenshot of HttpAccessTokenRefreshError And these are the relevant parts of the code (t ): This are the relevant parts of the code: View … -
get long name during annotate in django ORM query
I have this model: class Rank(models.Model): RANK_TYPE_CHOICES = ( ('O', 'Officer'), ('E', 'Enlisted'), ('V', 'Civilian'), ('C', 'Cadet'), ) ShortName = models.CharField(max_length=50) LongName = models.CharField(max_length=500) Type = models.CharField(max_length=1, choices=RANK_TYPE_CHOICES, default='O') Genre = models.ForeignKey(Genre, on_delete=models.DO_NOTHING) Career = models.ForeignKey(Career, on_delete=models.DO_NOTHING) image = models.ForeignKey(Photos, on_delete=models.DO_NOTHING) when I perform this ORM action: models.Rank.objects.values('Type').annotate(total=Count('Type')).order_by() I get this response <QuerySet [{'Type': 'O', 'total': 1}]> Exactly as I want. However, as you can see, it gives me the short type. How do I make it show the long name instead of the type choice short name? Thanks. -
Remove session data in database-backed session in django after clearing history
After i clear my browser history the session id and data that was added to the table django_session (session engine is database-backed by mysql) for the session remains and for subsequent requests a new session is created. In a situation where users clear their history frequently this table will grow inadvertently. Using clearsessions command doesn't remove the rows because the expiry date has not yet been reached. How do i overcome this issue ? Is there some setting wrongly set up? -
Django Projekt Management
im currently facing the problem that i want to call a view from another app (accounts app which holds the user model) within my main app (a blog app). this is the error i get: django.core.exceptions.FieldError: Unknown field(s) (username) specified for User urls.py ... from quickblog import views as core_views from accounts import views as views_accounts ... url(r'^myaccount/$', views_accounts.view_profile, name='myaccount'), views.py (accounts app): from django.shortcuts import render, redirect from django.urls import reverse from accounts.forms import ( RegistrationForm, EditProfileForm ) from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth import update_session_auth_hash def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect(reverse('accounts:home')) else: form = RegistrationForm() args = {'form': form} return render(request, 'reg_form.html', args) def view_profile(request, pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user args = {'user': user} return render(request, 'profile.html', args) def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect(reverse('accounts:view_profile')) else: form = EditProfileForm(instance=request.user) args = {'form': form} return render(request, 'edit_profile.html', args) def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect(reverse('accounts:view_profile')) else: return redirect(reverse('accounts:change_password')) else: form = PasswordChangeForm(user=request.user) args = {'form': form} return render(request, 'change_password.html', args) This is my first … -
Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['cartadd/(?P<product_id>\\d+)/$']
I am creating an eCommerce webapp.I have two apps. Cart and Shop. But when I try to load my product page I get the following error. urls.py views.py detail.html Server -
Unable to override django template from 3rd party app
I'm trying to override the base forum template for django-machina. I've copied the board_base.html contents from github source into /app/forum/templates/machina/board_base.html. My settings file contains a templates section like: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), MACHINA_MAIN_TEMPLATE_DIR, ], #snip Django is definitely looking in that directory: if I set up a different view pointing to a nonexistent template file, then on the resulting error page the first path that Django reports trying is: /app/forum/templates/nothing.html (Source does not exist) What have I missed? Why can't I override that template? -
Update an attribute for all users in profile Django
I've a model: class GenerateCertificate(models.Model): username = models.OneToOneField(User, on_delete=models.CASCADE) cert_name = models.CharField( max_length=15, default='', blank=True, editable=False, help_text="<b><a>System Generated - Do not alter</a></b>") cert_password = models.CharField( max_length=20, default='', blank=True, editable=False, help_text="<b><a>System Generated - Do not alter</a></b>") key_name = models.CharField( max_length=15, default='', blank=True, editable=False, help_text="<b><a>System Generated - Do not alter</a></b>") def __unicode__(self): return unicode(self.username) I want to update the attributes cert_name, cert_password and key_name and set value '' in all of these attributes. It is easy to do it for one user through the following: for qs in queryset: username = str(qs.username) #get user data from database user = GenerateCertificate.objects.get(username__username=username) keyname = user.key_name certname = user.cert_name #deleting the user data from database GenerateCertificate.objects.filter(username__username=username).update( cert_name='') GenerateCertificate.objects.filter(username__username=username).update( cert_password='') GenerateCertificate.objects.filter(username__username=username).update( key_name='') but how to do it for all the users in the database? I am using Django 2.0.6 and Python 3.5 -
Django translation ( "en") does not work correctly
I want to be able to edit any text on the page in any language from .po files. In Polish, I replace the text without any problems, but in English the text is the same as in the template. as you can see in English the text is 'home' and it should be 'Welcome' EN DJANGO .PO FILE #: .\app\templates\app\layout.html:24 msgid "home" msgstr "Welcome" PL DJANGO .PO FILE #: .\app\templates\app\layout.html:24 msgid "home" msgstr "Strona główna" Settings.py LANGUAGE_CODE = 'pl' TIME_ZONE = 'UTC' USE_I18N = True LANGUAGES = ( ('en', _('English')), ('pl', _('Polish')), -
Adding a static form to a dynamic Formset
I am currently working on a Django project where the top three fields are static, and the bottom six fields have to have an add more button. Any ideas how I would go about this? I am not well experienced with js but am with python/Django. Thanks! -
Django i want to send an email to the drivers that are registered?
I am newbie and just see the documentation of sending mail . i wan to send an email to the drivers . after seeing their details if they are eligible i want them to send an email using thier email address . driver_email . please tell me how do i send a email. i had already set the settings.py email host user all the needs of send an email its working on my other app . but not working on this app . Views.py @csrf_protect def rentacar_carapp_sendmail(request): if request.POST: try: args['carapp'] = carapp = CarApp.objects.get(id=request.POST.get('carapp_id')) subject = "Please Register Your Car" from_email = settings.EMAIL_HOST_USER to_email = carapp.get('car_app_driver_id.driver_email') join_message = """Your booking is placed we will contact you later """ send_mail(subject=subject, from_email=from_email, recipient_list=[to_email], message=join_message, fail_silently=False) carapp.save() except: pass return HttpResponseRedirect('/mega-admin/rentacar/carapp-manager/') models.py class Driver(models.Model): class Meta(): db_table = "driver" verbose_name = "Driver" verbose_name_plural = "Drivers" ordering = ['driver_firstname', 'driver_lastname'] driver_firstname = models.CharField( max_length=64, blank=False, null=False ) driver_lastname = models.CharField( max_length=64, blank=False, null=False ) driver_email = models.EmailField( blank=False ) class CarApp(models.Model): class Meta(): db_table = "carapp" verbose_name = "Carapp" verbose_name_plural = "Carapps" car_app_driver_id = models.ForeignKey( Driver, on_delete=models.CASCADE, related_name='car_app_driver_key' ) car_app_type_of_car_wanted = models.TextField( blank = True, null = True )