Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to defaultly return image.url when we get model Object?
I want my model object to always return image.url of field image. My model: class Content(models.Model): ... avatar = models.ImageField(upload_to=file, blank=True, null=True) I want something like: class Content(models.Model): ... def get_avatar(self): # some default func for returning fields return self.avatar.url It have to work like this, When I get the object: content = Content.objects.get(pk=1) print(content.avatar) And it should print the path: /media/uploads/dsadsadsa.jpg Briefly, I want something that will change the return of model field. -
installing cx-oracle and dev-tools on centos
We have a (python2.7/django-1.10) project working on Ubuntu 14.04. Since the end of 14.04 is near, we are migrating to CentOS(7) for a particular reason. The error I am getting is below when I run pip install -r requirements.txt Installing collected packages: cx-Oracle, Django, python-openid, requests, oauthlib, requests-oauthlib, django-allauth, django-angular, sqlparse, django-debug-toolbar, django-debug-toolbar-request-history, django-debug-toolbar-template-profiler, django-debug-toolbar-template-timings, djangorestframework, execnet, greenlet, gevent, gunicorn, meld3, pyasn1, pyOpenSSL, ndg-httpsclient, ntlm-auth, pytz, xmltodict, requests-ntlm, pywinrm, sh, supervisor Running setup.py install for cx-Oracle ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-JZMDHk/cx-Oracle/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-stOsUC/install-record.txt --single-version-externally-managed --compile: running install running build running build_ext building 'cx_Oracle' extension creating build creating build/temp.linux-x86_64-2.7-11g gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/u01/app/oracle/product/11.2.0/xe/rdbms/demo -I/u01/app/oracle/product/11.2.0/xe/rdbms/public -I/usr/include/python2.7 -c cx_Oracle.c -o build/temp.linux-x86_64-2.7-11g/cx_Oracle.o -DBUILD_VERSION=5.2.1 unable to execute gcc: No such file or directory error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-JZMDHk/cx-Oracle/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-stOsUC/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-JZMDHk/cx-Oracle/ Then after some fiddling, I tried β¦ -
Custom Forms to upload images in Django
I am creating an educational application where there is a page for teacher to register a ask for students. The problem I wanted was a field where the teacher was able to enter text and image. I've searched richtexts for django, but they only work in admin and the teacher does not have admin permission. Is it possible to customize a form in django that sends text and images? -
how to get specific users from django user in another model
I have this model called UserTypes in this model i use User as OneToOne field and UserTypes model is inline with User model. I created this model to give the user a status just like we do is_staff=True. now i want to display all the users whose staff_status = "Delivery Boy" in another model called Order which is in another app in the same project model.py(app1) class UserTypes(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) staff_choices = ( ('', ''), ('Admin', 'Admin'), ('Chef', 'Chef'), ('Delivery Boy', 'Delivery Boy'), ) staff_status = models.CharField(max_length=15, choices=staff_choices, default=staff_choices[0][0]) def __str__(self): return self.staff_status model.py(app2) class Order(models.Model): name = models.CharField(max_length=60) email = models.EmailField(max_length=60,default=None, blank=True) mobile_no = models.CharField(max_length=13, default=None) address = models.CharField(max_length=150) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status_choices = ( ('In Queue', 'In Queue'), ('Processing', 'Processing'), ('Ready', 'Ready'), ('Delivered', 'Delivered'), ('Paid', 'Paid'), ('Cancelled', 'Cancelled'), ) status = models.CharField(max_length=15, choices=status_choices, default=status_choices[0][0]) total = models.DecimalField(max_digits=10, decimal_places=2,default=0) class Meta: ordering = ('created', ) def __str__(self): return 'Order {}'.format(self.id) def get_total(self): return sum(item.get_cost() for item in self.items.all()) -
Django: How to check if data is correct before saving it to a database on a post request?
I would like to be able to parse the data from a post request in my django rest api project by sending it to my function that will return true or false if the number is valid before saving it to the database and if it's wrong send a custom bad request message to the client that did the request. I've been told I can overwrite the create method todo this but I'm not sure how to go about it. My code so far looks like this: class Messages(models.Model): phone_number = models.CharField(max_length=256, default='') message_body = models.CharField(max_length=256, default='') created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.phone_number + ' ' + self.message_body + ' ' + self.created def save(self, force_insert=False, force_update=False, using=None, update_fields=None): # I assume this is where I would do the check before saving it but not sure how? example would be like: # if numberValid(self.phone_number): # then save to the database # else: # then send back a bad request? super(Messages, self).save(force_update=force_update) send_sms(self.phone_number, self.message_body) def delete(self, using=None, keep_parents=False): super(Messages, self).delete(using=using, keep_parents=keep_parents) So basically just would like some direction on how to solve this problem. Even helpful links would be appreciated. I did look on stackoverflow but was not successful, maybe β¦ -
Django-filter: filtering by model property
I read on several places that it is not possible to filter Django querysets using properties because Django ORM would have no idea how to convert those into SQL. However, once the data are fetched and loaded into memory, it shall be possible to filter them in Python using those properties. And my question: is there any library that allows the querysets to be filtered by properties in memory? And if not, how exactly must the querysets be tampered with so that I can write this feature from scratch? And how to include django-filter into this? -
Is the request data garbage collected at the end of the request-reply cycle?
I am running a django API (drf) via gunicorn, as a wsgi application. The API is handling sensitive information (passwords and other secrets) which need to be cleared from system memory (ram). My understanding is that all the data coming in the API request will be garbage collected using the normal reference counting mechanism: once the request has been processed and gunicorn has received the reply, no more references to the request exist and it will be thus completely garbage collected. The same will apply to any object created during request processing: all references to it will be removed after the request has been processed. The only way in that this assumption is broken is if I do any of the following: store references to the request in a global object create cyclical references to the request object In the case of 2, the gc module will be able to detect the references and remove them. I can even trigger that manually with gc.collect() The first problem can be avoided by simply being careful not to store references in global objects. I have two questions: Are there other things I should be careful about regarding data persistence in memory? How β¦ -
how can create for instance : popular post , similar post , best price post and etc in Django?
I'm beginner in Django and i didn't get how can set for example : like eCommerce site have best product and similar product and ... in my project . i search a little about that . for similar post i know have to have tag in common but i don't know how to use it ? for example : i want to have have best product or high price product in detail page of each product 1. can i set a query like this : product_detail_view = get_object_or_404(Product,id=id) best_product = Product.object.filter(price = ??????????) context { 'product_detail_view': product_detail_view , 'best_product':best_product } return render (... ) what i have to right instead of ???? and i want to know this is correct or whole thing i did was wrong? or i have to set a query set in models if i have to do this how i show it in template ? please help me i have a big problem with understand this situation ? models.py class Product(models.Model): title = models.CharField(max_length=120) car = models.CharField(max_length=120) tag = TaggableManager() slug = models.SlugField() description = models.TextField(blank=True,null=True) price = models.DecimalField(max_digits=50,decimal_places=2) acitve = models.BooleanField(default=True) timefield = models.DateTimeField(auto_now_add=True,auto_now=False) updated = models.DateTimeField(auto_now_add=False,auto_now=True) hits = models.IntegerField(default=0) image = models.ImageField() tnx. -
How do I prevent the no 'get' attribute error when validating a form?
I have a class in views.py and when I run the code I get the following error: object has no attribute 'get' Can anyone help? class currencyconvertGBP(): def __init__(self, *args, **kwargs): login_id = '###############' api_key = '####-####-####-####' environment = currencycloud.Config.ENV_DEMO client = currencycloud.Client(login_id, api_key, environment) def GBPconvert(request): if request.method == "POST": form = Convert_Form_GBP(request.POST) if form.is_valid(): sell_currency = form.cleaned_data.get('sell_currency') buy_currency = form.cleaned_data.get('buy_currency') amount = form.cleaned_data.get('amount') form = Convert_Form_GBP() form.save() print(sell_currency) print(buy_currency) print(amount) -
Figure out which user Django code is running under
I have Ubuntu as an ec2 instance on AWS, where I hosted a Django application using Apache2 and mod_wsgi. In my code I am trying to get the username through os.environ['USERNAME'] statement, which returns a KeyError: 'USERNAME', how can I get the username? I want that username because I need to set permissions for a sqlite datebase file, since I cann't know the username, therefore cann't set the permissions on that file. -
Generic detail view ProfileDetail must be called with either an object pk or a slug in the URLconf
Im trying to get all the post by a single user and display it using DetailView and also i want to pass the username of the user on the url. this is my urls.py: from django.urls import path from .views import ProfileDetail from . import views urlpatterns = [ path('<str:username>/', ProfileDetail.as_view(), name = 'profile'), ] this is my views.py: from django.views.generic import (DetailView) from django.shortcuts import render , redirect, get_object_or_404 from django.contrib.auth.models import User from blog.models import Post class ProfileDetail(DetailView): model = Post template_name = 'users/myprofile.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author = user).order_by('-date_posted') I have a class based view almost exactly just like this one and it is working. But this one always gives me this AttributeError: Generic detail view ProfileDetail must be called with either an object pk or a slug in the URLconf. -
Django logging not working at all levels with a valid config?
I have a valid django config in my settings.py, i know this as the file path is taken into account for the RotatingFileHandler. My problem is that logs of logging.DEBUG are not printed to the file. My settings and file in which the logger is run are below: # settings.py DJANGO_LOG_LEVEL = logging.DEBUG DEFAULT_LOG_PATH = 'foo/logs/foo.log' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': 'TEST {asctime} {module} {levelname} {message}', 'style': '{' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'default': { 'level': DJANGO_LOG_LEVEL, 'class': 'logging.handlers.RotatingFileHandler', 'filename': DEFAULT_LOG_PATH, 'formatter': 'standard' }, }, 'loggers': { 'kapsule': { 'handlers': ['default'], 'level': logging.DEBUG, }, }, } # foo.py logger = logging.getLogger("foo.monitor") logger.debug('debug') # nothing logger.info('info') # printed fine logger.warning('warning') # printed fine logger.error('error') # printed fine logger.critical('critical') # printed fine Why is this happening? -
How to Raise DoesNotExist - Django SoftDelete?
I have a Abstract Model SoftDelete like follow. class SoftDelete: is_deleted = models.BooleanField(default=0) deleted_at = models.DateTimeField(null=True) def delete(self): self.is_deleted = True self.deleted_at = timezone.now() self.save() class Meta: abstarct = True Whenever model gets deleted i set is_deleted to True and updating the timestamp deleted_at, and created the custom manager to override initial queryset which return only non deleted fields(is_deleted=False). But lets say i have a Employee model which uses the SafeDeleteModel for soft delete, after deleting the model like Employee.objects.get(pk=1).delete() when i call employee.refresh_from_db(),its not raising DoesNotExist, but updates the value of is_deleted, deleted_at as expected, what mistake i made here, why its not raising DoesNotExist? -
how to set or change the object value of model which shares one to one relationship with another model
I have two models which shares one to one relationship. I want to change/set the one of the model object value in another model in relationship. I have two models Guest, and Room which shares one to one relationship status: in the Room model i have a field 'room_status' and it contains multiple values '('available', 'reserved', 'maintenance')' . When 'Room' assigned to 'Guest', field 'room_status' should be set to 'reserved'. -
Pull data from Postgres, and in show it in a template
I am new to Django, all i am trying to do is pull a table from postgres database and post it in html, when i do a runserver, it has to display all the records from the table, since i am testing i only used 4 colummns in the Html.py Models.py: from django.db import models from django.contrib.gis.db import models #class Shop(models.Model): class Anchor(models.Model): # site_cd_name = models.CharField(max_length=100) # site_lat = models.FloatField(max_length=100) # site_long = models.FloatField(max_length=100) record_type = models.CharField(max_length=2, null=True) unique_system_identifier = models.DecimalField(max_digits=9,decimal_places=0, null=False) uls_file_number=models.CharField(max_length=14,null=True) ebf_number=models.CharField(max_length=30, null=True) call_sign=models.CharField(max_length=10, null=True) partition_area_idnumeric=models.DecimalField(decimal_places=0,max_digits=9, null=True) lower_frequency=models.DecimalField(decimal_places=8,max_digits=16, null=True) upper_frequency=models.DecimalField(decimal_places=8,max_digits=16, null=True) def_und_indicator=models.CharField(max_length=1,null=True) defined_partition_area=models.CharField(max_length=6,null=True) class Meta: db_table = 'mf' def __unicode__(self): return "%s %d %s %s %s %d %d %d %s %s" %(self.record_type,self.unique_system_identifier,self.uls_file_number,self.ebf_number,self.call_sign, self.partition_area_idnumeric,self.lower_frequency,self.upper_frequency,self.def_und_indicator,self.defined_partition_area) Views.py: from django.shortcuts import render, get_object_or_404, render_to_response from django.http import HttpResponse from django.views import generic from django.contrib.gis.geos import fromstr from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.geos import Point from .models import Anchor from django.template import RequestContext # Create your views here. def index(request): model= Anchor context_object_name= "Anchors" data = Anchor.objects.all() # record_type1 = queryset.record_type template_name="Anchors/index.html" context = { 'context_object_name': context_object_name, } # html = "<html><body>Room 1 will be used by %s</body></html>" % record_type1 return render(request, 'index.html', context=context) Index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> β¦ -
'related_name' works if create an object without saving?
I have 2 django models related with a ForeignKey. So, I can create a parent object and different childs objects. I cannot save the objects, but I need get the 'related_name'. How I can do it? # create objects parent = ParentModel(**serializer_in.validated_data) child = ChildModel(**serializer_in.validated_data) # relate objects child.parent_field = parent # try get childs print(parent.child_set.all()) # is empty. why? My related_name get an empty queryset. Why? -
How to run django in a subpackage
My project results are as follows, django in automl/service, in automl/service/worker/suggester.py file has an import from automl.core import util and this file imported by views.py, when I run python service/manage.py runserver will raise the exception from automl.core import util ModuleNotFoundError: No module named 'automl' how to solve this problem, does django can not run in a sub package? βββ automl β βββ __init__.py β βββ core β β βββ __init__.py β β βββ base.py β βββ example β β βββ __init__.py β β βββ demo.py β βββ service β βββ __init__.py β βββ manage.py β βββ master β β βββ __init__.py β β βββ urls.py β βββ settings.py β βββ worker β β βββ __init__.py β β βββ admin.py β β βββ apps.py β β βββ exceptions.py β β βββ models.py β β βββ suggester.py β β βββ tests.py β β βββ urls.py β β βββ views.py β βββ urls.py β βββ wsgi.py βββ bin βββ build.sh βββ ci.yml βββ conf β βββ log_config.json βββ docs -
how to create a field in django model using values of other fields of same model?
i wants to create a field name:total which have the total price of all the productsquqantity. what i want is how can i do total = pricequantity in django model. As you can see there can be more more than one products. I have join the OderItem model with Order through tabularinline. class OrderItemInline(admin.TabularInline): model = OrderItem raw_id_fields = ['product'] class OrderAdmin(admin.ModelAdmin): list_display = ['id','name', 'mobile_no','address','status', 'created'] list_editable = ['status'] list_per_page = 15 list_filter = ['status'] search_fields = ('id',) inlines = [OrderItemInline] admin.site.register(Order, OrderAdmin) class Order(models.Model): name = models.CharField(max_length=60) email = models.EmailField(max_length=60,default=None, blank=True) mobile_no = models.CharField(max_length=13, default=None) address = models.CharField(max_length=150) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status_choices = ( ('In Queue', 'In Queue'), ('Processing', 'Processing'), ('Ready', 'Ready'), ('Delivered', 'Delivered'), ('Paid', 'Paid'), ('Cancelled', 'Cancelled'), ) status = models.CharField(max_length=15, choices=status_choices, default=status_choices[0][0]) class Meta: ordering = ('created', ) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(MenuVariant, related_name='order_items', on_delete=models.CASCADE, default=None) size = models.CharField(max_length=20, default=None) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) # total = models.DecimalField(max_digits=10, decimal_places=2,default=0) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity -
How to fix the exclude with Q & Q in Django ORM
I have a simple query with filter and exclude. Exclude for Q & Q not working. Below is the query that I am using. start_date = (datetime(time.localtime().tm_year, time.localtime().tm_mon, 1) - timedelta(1)).replace(day=1) data = models.Test.objects.filter( is_deleted=False).exclude(Q(status__in=[1,2,3]) & Q(modified_at__lt=start_date))\ .select_related('created_by')\ .prefetch_related('name') I want the exclude to work. If I use exclude twice, I'm getting the result. -
Django urls vs wagtail pages urls
Lets's say that i have a wagtail page /home/offers,and i created a django router like: urlpatterns = [path('home/offers', offers.as_view())] Which one will take the precedence? assuming that the wagtail offers page differs from the django view. -
Comparing Date to Minimum Future Value in Other Model
I have two django models that define: Item = A set of items with an expiry date. Event = A set of events that have a start and end date. My aim is that when the item is displayed, its expiry date is shown conditionally formatted, based on whether that item expires before the next event's end date (so warning when it's due to expire.) The problem becomes, how best to manage this feat? If I was directly accessing the database, I'd be using subqueries to get the minimum end date still in the future, and then comparing that to the expiry date on an if basis to swap the formatting. From research, I'm coming to the conclusion that this is best handled in the view logic, rather than trying to set a method in either of the models, but I don't know how best to get this to splice together so I can return the value of my minimum future date and my itemlist object from the Item model. The current view is pretty simple at this stage (it will have more filtering options later): def itemlist(request): item_list = Item.objects.all return render(request, "itemlist.html", {'item_list': item_list}) but I cant see β¦ -
Have a problem using Django 2.2 with PyMySQL
I'm currently using Django on Google App Engine - Standard Environment python3 Follow the document on google - https://cloud.google.com/python/django/appengine since google app engine can't run mysqlclient, document recommend to use PyMySQL instead. However, Django release new update 2.2 which make PyMySQL Problem and error occur state that Django require mysqlclient 1.3.13 or higher to run django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3." Anyone have better solution than stick with Django 2.1.8? Thank you -
Usint data from one Django application in another
I have a Django blog site. It contains two applications: blog and pages. The blog app lists all blog items as follows: models.py: class News(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) thumb = models.ImageField(blank=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('news_detail', args=[str(self.id)]) views.py class NewsListView(ListView): model = News template_name = 'news_list.html' news_list.html {% extends 'base.html' %} {% block title %}News{% endblock title %} {% block content %} {% for news in object_list %} <div class="card" style="width: 300px; display: inline-block; margin: 5px; vertical-align: top;"> <div class="card-header"> <span class="font-weight-bold"> <a href="{% url 'news_detail' news.pk %}" style="color:black">{{ news.title }}</a> </span> &middot; <span class="text-muted">by {{ news.author }} | {{ news.date }}</span> </div> <div class="card-body"> {% if news.thumb %} <p align="center"><img src="{{ news.thumb.url }}" /></p> {% endif %} <p>{{ news.body | linebreaks | truncatewords:30 }} <a href="{% url 'news_detail' news.pk %}">Full story</a></p> </div> <div class="card-footer"> {% if user.is_authenticated %} <a href="{% url 'news_edit' news.pk %}">Edit</a> <a href="{% url 'news_delete' news.pk %}">Delete</a> {% endif %} </div> </div> {% endfor %} {% endblock content %} My pages app has home.html: {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block content %} <div β¦ -
How to query for overlapping date ranges?
I have members who are for a limited time assigned to a team. Members can be assigned to multiple teams. The members create worklogs on a day. Worklogs are assigned to a member, the member is assigned to a team. The intermediate table Membership stores the assignment dates of team members. I need to query all worklogs related to a specific team during e.g. the first quarter of 2019. The team members could've joined and left during the quarter and only the worklogs during their team assignment should be considered. class Teamuser(models.Model): key = models.CharField(max_length=200, primary_key=True) fullname = models.CharField(max_length=200) class Team(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=200) members = models.ManyToManyField(Teamuser, through='Membership') class Membership(models.Model): id = models.IntegerField(primary_key=True) memberid = models.IntegerField(null=False, blank=False) teamuser = models.ForeignKey(Teamuser, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) dateFrom = models.DateField(null=True, blank=True, default=None) dateTo = models.DateField(null=True, blank=True, default=None) class Worklog(models.Model): worker = models.ForeignKey(Teamuser, on_delete=models.PROTECT) day = models.DateField(null=True, blank=True, default=None) effort = models.IntegerField() comment = models.TextField(null=True) I expect an output of all Worklogs a Teamuser created during the timeframe (Q1 2019) while being assigned to the queried team (e.g. only January 2019). -
Kindly suggest Django-Oscar beginner tutorials
Kindly suggest Django-Oscar beginner tutorials, except the documentation, where I can get step by step guide and explanation on using it and customising models and the already present Oscar apps and the templates? As I want to understand it's workflow first.