Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Catch exception when adding to manytomany field in django
So I am adding a list of items to my manytomany field. If item1 already exists in myModelInstance.myM2MField, it does not add it again. myItems = [item1, item2] try: myModelInstance.myM2MField.add(*myItems) except Exception as e: return e I would like to catch the list of items which were not added and return it. Is that possible? -
Annotating a QuerySet in ListView: Django
I am learning Django by building an example app in which I have student users who can sign up for Study sections. For each student user I have a ListView which creates a table list of all of the relevant study sections for them. Each Study model is related to a Detail model which contains the details of the study section such as location and start time. For each Study I would like to add values of the associated Detail such as location and start time, but I am having trouble figuring out how to pass this information into the template from the ListView. models.py class Study(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='studies') name = models.CharField(max_length=255) condition = models.ForeignKey(Condition, on_delete=models.CASCADE, related_name='studies') def get_details(self, study): details = study.details.all().order_by('start_date') return details def __str__(self): return self.name class Detail(models.Model): study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='details') Location = models.CharField('Detail', max_length=255) start_date = models.DateField('event start date', default=datetime.date.today) end_date = models.DateField('event end date', default=datetime.date.today) start_time = models.TimeField('event start time', default=now) end_time = models.TimeField('event end time', default=now) description = models.TextField(blank=True) def __str__(self): return self.Location views.py @method_decorator([login_required, student_required], name='dispatch') class StudyListView(ListView): model = Study ordering = ('name', ) context_object_name = 'studies' template_name = 'classroom/students/study_list.html' def get_object(self): return self.request.user.studies def get_context_data(self, **kwargs): … -
How do I open up and run a Django server on a Microsoft OS?
I am fairly new to the world of coding and am looking to learn. I have been taking some online classes on Lynda.com and learned how to fire up a Django server but once I fire it up and come back later to work on it I am having trouble firing the server back up. Can you help? I am working with CMD in a Microsoft 10 OS. Thanks -
Search and Pass Data Segue to New Scene
I'm trying to search my postgresql database in ViewController A, and have the query results displayed in my tableview in ViewController B. Does anyone know of the best tutorial for passing search data between view controllers for an instance like this specifically? In other words, I'd search in one scene, and the next scene displays the results of my search (rather than searching in TableView). -
How to sending email with django using gmail
I am trying sending email for password reset but it giving me following error. SMTPSenderRefused at /account/password_reset/ (530, b'5.7.0 Must issue a STARTTLS command first. x20sm7511321wme.6 - gsmtp', 'webmaster@localhost')...... here is my code. EMAIL_USE_TSL = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'user@gmail.com' EMAIL_PASSWORD = '*******' EMAIL_PORT = 587 -
Setting initial values on MultipleChoiceField based on presence of related items
I've got 2 models. They are related to one another. models.py class Car(models.Model): model = models.CharField() manufacturer = models.CharField() class MyCar(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) car = models.ForeignKey(Car, on_delete=models.CASCADE) Within a form, I've got a MultipleChoiceField that shows all instances of Car as choices. forms.py cars = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): super(CarForm, self).__init__(*args, **kwargs) self.fields['cars'].choices = [(t.id, t) for t in Cars.objects.all()] When the user submits the form, for each instance of Car that was selected, a related instance of MyCar is created. When the user navigates back to the form, I want to set initial values on the 'cars' field based on the user's instances of MyCar that already exist. self.fields['cars'].initial = [(t.id, t) for t in Cars.objects.filter(?????)] Thanks so much for your help! -
Is there a way to exclude / override one of included URL paths?
I need to exclude or override one of included url paths. I have used the django.contrib.auth package to implement registration and login as well as password recovery, but I decided to implement password changing myself. However, the url paths don't seem to be easily overriden. This is my urls.py file: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('accounts/password_change', views.PasswordChangeView.as_view()), path('accounts/', include('django.contrib.auth.urls',)), path("", views.index, name="index"), ] I thought that including this path('accounts/password_change', views.PasswordChangeView.as_view()), line before the one with the include operation would solve the problem, but it seems that the pattern matching function traverses the included urls first, and only then checks the remaining urls. Is there an elegant way to solve this? -
One optional plus one required slug parameter in same django URL
I have two models City and Category. for simplicity's sake they are functionally identical: models.py class City(models.Model): name = models.CharField(max_length=50) slug = AutoSlugField(populate_from='name') class Meta: ordering = ['name'] def __str__(self): return self.name def get_absolute_url(self): return reverse('cities', args=[self.slug]) class Category(models.Model): name = models.CharField(max_length=50) slug = AutoSlugField(populate_from='name') class Meta: ordering = ['name'] def __str__(self): return self.name def get_absolute_url(self): return reverse('categories', args=[self.slug]) the one distinction is for the purposes of the url or view I'm trying to build there's one city, but there can be multiple categories within a city. what I'm looking to do is make the city slug a required slug in the url path (view parameter), but category an optional, second slug so users can select a category if they want to filter further (or not, with default being no filter category ) my attempt: urls.py url(r'^c/(?P<slug>[-\w]+)/(?P<category>[-\w]+)/?$', views.city, name='city'), views.py def city(request, slug=None, category=None): city = None if slug is None else get_object_or_404(City, slug=slug) category = None if tag is None else get_object_or_404(Category, slug=category) if category: # foo context = { 'city': city, 'category':category, } return render(request,'city.html', context) and I'm encountering two issues: Issue #1 - is there a way to make the category parameter optional so that app.com/c/city/ is … -
"Manage isn't accessible via model Instances" error on template rendering
I have a model namely President and there is list() on views.py: from .models import President def list(request): return render(request, 'president/list.html', {'President': President}) The following is list.html: {% for p in President.objects.all %} <li>{{p}}</li> {% endfor %} But the error "Error during template rendering: Manager isn't accessible via President Instances." occurs. How can I solve the problem? -
Django Template Tags and Meta-Programming: Is there any way of modifying a variable's name before calling its context?
Suppose in views.py I have a variable (i.e., changing) number of forms or types of objects in my context. (I'll just use the word 'forms' for simplicity). context = { 'form_0': form_0, 'form_1': form_1, 'form_2': form_2, 'form_3': form_3, # ... and so forth } Let's suppose that I have no way of knowing how many forms are in my context at any given time. Is it at all possible to do the following with template tags: {% for i in (number of forms in context) %} {{ form_i }} <-- where i is equal to the number i in the loop --> {% endfor %} Here the end result would translate to: {{ form_0 }} {{ form_1 }} {{ form_2 }} ... and so forth I'm doubtful that this is at all possible, but if it is, I would find it quite helpful. -
Getting NoReverseMatch even though my pk has the right value
I'm getting a NoReverseMath error even though what I'm trying to passthrough has a primary key. I've tested just displaying the primary key, and it is the correct key, but when I try to use it in the url it says there is no primary key. {% url 'thread_page' pk=notif.content_object.ancestor.pk %} This is the line I'm using. When I use {{notif.content_object.ancestor.pk}} It will show me the primary key, so I'm not sure what's going on here. Template error: In template /Users/winglee/Documents/Learning Python/jellyfish/jellyfish/forum/templates/forum/base.html, error at line 39 Reverse for 'thread_page' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried: ['thread/(?P<pk>[^/]+)/$', 'thread/(? P<pk>[^/]+)/$'] 29 : <a class="navbar-item">Documentation</a> 30 : <div class="navbar-end"> 31 : <div class="buttons"> 32 : {% if user.is_authenticated %} 33 : <p class="blurb">Welcome, <a href=" {% url 'profile_page' pk=user.pk %}">{{user.username}}</a></p> 34 : <a id="notif" class="button"> {{unread.count}} &nbsp<i class="fas fa-bell"></i></a> 35 : <div id="notiftray" class="inactive"> 36 : {% for notif in notifs %} 37 : <div class="card u-padding"> 38 : {% if notif.content_type.model == 'post' %} 39 : <a href="{% url 'profile_page' pk=notif.actor.pk %}">{{notif.actor}}</a> posted a reply in <a href=" {% url 'thread_page' pk=notif.content_object.ancestor.pk %} "> {{notif.content_object.ancestor}}</a> 40 : {% elif notif.content_type.model == 'likedislike' %} 41 : <a href="{% url … -
Processing Results from futures.ThreadPoolExecutor python
I am using multi threading method with futures.ThreadPoolExecutor for getting results from 1000 of urls in my Django application, this is working well but one clarification i want is will it be correct to process the data then and there once we receive 1st response and about to recieve 2nd response and so on ? Saving whole json response from 100 URLS and then processing one by one also looks in-correct. Can some one suggest what would be best way of doing it ? My Question is related to below discussion. A very simple multithreading parallel URL fetching (without queue) -
How to use Django Model computed property into a Django Manager Model?
I trying to use my django model computed property into a custom manager in order to achieve a custom result. But django is allowing just to use the normal properties into manager. I already tried to add @property to my computed property but is not working. This my code: class Produto(models.Model): nome = models.CharField(max_length=100) fabricante = models.ForeignKey('Fabricante', on_delete=models.PROTECT) frete_ipi = models.DecimalField(decimal_places=2, max_digits=10) price = models.DecimalField(decimal_places=2, max_digits=10) cost_price = models.DecimalField(decimal_places=2, max_digits=10) @property def real_cost_price(self): p = (self.cost_price * self.frete_ipi) + self.cost_price return round(p, 2) And i'm trying to use the "real_cost_price" into my manager and is not working. class EstoqueCentroManager(models.Manager): def total_venda(self): total = self.all().aggregate(valor=Sum(F('quantidade') * F('produto__real_cost_price'), output_field=FloatField())) return total How can i use this computed property "real_cost_price" into my manager? Or there another work around to achieve this kind of result? Thanks! -
Celery .delay() works synchronously, not delaying
I have a Django project with Celery background and periodic tasks. I started worker process a year ago, and periodic tasks work well. However, I just found that calling asynchronous functions main server code doesn't work, apply_async()/delay() lead to synchronous executing of a function just like without using them. How can I solve the problem? Here is my Celery settings file: import os from celery import Celery from django.conf import settings broker_url = 'amqp://<user>:<password>@localhost:5672/{project}' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings') app = Celery('<project>', broker=broker_url) app.config_from_object('django.conf:settings') app.conf.update ( CELERY_TASK_SERIALIZER='json', CELERY_ACCEPT_CONTENT=['json'], CELERY_RESULT_SERIALIZER='json', CELERYD_HIJACK_ROOT_LOGGER=False, BROKER_URL=broker_url, CELERY_RESULT_BACKEND='djcelery.backends.database.DatabaseBackend', CELERY_ALWAYS_EAGER=True, ) And this is my test code: from general.celery import app from time import sleep @app.task def fun(): for i in range(5): print('Sleeping') sleep(2) print('Awake') def test(): print('Begin') fun.apply_async(countdown=10) print('End') It leads to the immediate output: Begin Sleeping ... I also checked Celery's inspect: from celery.task.control import inspect print(inspect().stats()) It described the following states: { 'broker': { 'failover_strategy': 'round-robin', 'ssl': False, 'transport': 'amqp', 'heartbeat': 120.0, 'transport_options': {}, 'insist': False, 'alternates': [], 'connect_timeout': 4, 'userid': '<user>', 'hostname': '127.0.0.1', 'login_method': 'AMQPLAIN', 'port': 5672, 'uri_prefix': None, 'virtual_host': '<project>' }, 'total': {}, 'prefetch_count': 8, 'clock': '2299', 'pool': { 'put-guarded-by-semaphore': False, 'max-concurrency': 2, 'max-tasks-per-child': 'N/A', 'writes': { 'avg': '0.00%', 'inqueues': { 'total': 2, 'active': 0 … -
Django rest framework serializer - Serialize single model field multiple times
I would like to serialize one related field multiple times in output json. The first should contain pk of related object, and the second representation should be hyperlink. Any fancy way how to do it? I know SerializerMethodField, but I find it non-elegant approach. My models: class Person(models.Model): first_name = models.CharField() ... class Order(models.Model): title = models.CharField() person = models.ForeignKey(Person, related_name='orders') What I want: Serialize my Order model like this: { "title": "Alice in wonderland", "person": 1, # represents persons's primary key "person_url": "/person-detail/1" } What I tried / My serializer: class OrderSerializer(serializers.ModelSerializer): person = serializers.IntegerField() person_url = serializers.HyperlinkedRelatedField( view_name='user-profile', lookup_field='pk' ) read_only_fields = ('__all__',) class Meta: model = Order fields = [ 'title', 'person', 'person_url' ] But it this case Django was logically bitching about missing person_url field in database. How to proceed? -
Django ListView queryset for available items
So I want to display all available items for any given date, shouldn't be that hard but somehow I ran into a problem concerning related items. Let's say we have the following models, a model to store all bookings and a model with the Item. Then I would create ListView to retrieve all items available between any given dates. I override the queryset to retrieve the data filled in by the user. This seems to be working but there's an issue, even though I check if the "form_start_date" or "form_end_data" are in conflict with existing bookings, when a single Item has multiple bookings it does not work. example Bookings for item #01: 01-04-2019 to 01-11-2019 01-18-2019 to 01-25-2019 When I check for availablity for 01-14-2019 to 01-17-2019, item #01 is not available, what am I missing here? It looks like it is blocked between 01-04-2019 to 01-25-2019... models.py class Booking(models.Model): item = models.ForeignKey('Item', on_delete=models.SET_NULL, null=True) start_date = models.DateField() end_date = models.DateField() class Item(models.Model): name = models.CharField(max_length=20, unique=True) views.py class AvailableItems(generic.ListView): model = Item def get_queryset(self): form_start_date = self.request.GET.get('start_date') form_end_date = self.request.GET.get('end_date') bookings = ( (Q(booking__start_date__lt = form_start_date) & Q(end_date__gt = form_start_date)) | (Q(booking__start_date__lt = form_end_date) & Q(end_date__gt = form_end_date)) ) … -
How to get Nginx to serve Django static files in Elastic Beanstalk Docker single container
I've successfully deployed my app to AWS Elastic Beanstalk and set up Nginx. However I am unable to serve the static files(My project is an API and I need them for Django Admin site only). I run python manage.py collectstatic --no-input in my dockerfile entrypoint script. This is in my settings.py: STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)),'static') STATIC_URL = '/static/' https.conf: server { listen 443; server_name localhost; location / { proxy_pass http://docker; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static/ { alias /code/static/; } } I am aware of this setting for python platform, however as I am using a generic Docker single container platform, this option is not available. option_settings: "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/" Does anyone have any recommendations? -
Django 500 error for not-existing url in Debug=False
I'm using Django 2.1.3 in python 3.6.7. assume that I have this URL path: path('admin/', admin.site.urls) If I navigate to /ad while the DEBUG = True, I see normal Django 404 error page: But if I make DEBUG = False then the server shows up the 500.htm to me instead of 404.html for invalid URL /ad (that matches none of the URL patterns). The 404.html is showing up for a valid URL that raises 404 error. (like when a not-existing object query occurs with get_object_or_404 function) here is my /templates directory structure: /templates 400.html 403.html 404.html 500.html index.html ... So, How should I tell Django to show 404 error in production (in addition to development) if the request URL matches none of the URL patterns? Note: According to docs, if I have a 404.html in the root templates directory, this 404.html will be used with the default error handler. -
django_filters custom method field name
When I run this code I get [invalid name]: in the filters popup in django rest-framework views. I would like to display the name "find" instead. How can I set this name? class MyModelFilter(filters.FilterSet): search_name = filters.CharFilter(field_name='name', lookup_expr='icontains') find_anywhere = filters.CharFilter(method='look_anywhere') def look_anywhere(self, queryset, name, value): return queryset.filter(Q(name__icontains=value) | Q(description__icontains=value)) class Meta: model = MyModel fields = {'search', 'find_anywhere'} when calling /api/mymodels/?find_anywhere=something it works fine. It is only the name of the filter in the DRF views: -
Django, how to make view and models both skinny?
everyone has an approach for the size of views and models in MVC, I wonder if I want to have both view and models skinny, what should I do in Django? -
Attach permissions and groups to custom User model created from BaseUserAdmin
Been at this for a couple of hours and seem to get nowhere. I have a custom User model. In django admin, it is working well but I couldn't find the way to attach the user to groups and individual permissions, as it is done in the default User model of django. Below is my current code, which is cleaned a bit. My custom User model is: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email'), unique=True, max_length=255) first_name = models.CharField(_('firstName'), max_length=30) date_joined = models.DateTimeField(_('dateJoined'), auto_now_add=True) is_staff = models.BooleanField(_('staff'), default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'email'] class Meta: verbose_name = _('user') verbose_name_plural = _('users') Which is working fine. But in the Admin page, I want to attach/assign a user to a specific group as well as selected permissions, just it is done in the default User model of django. My admin.py is like this: from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from members.forms import UserAdminCreationForm, UserAdminChangeForm from members.models import User class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserAdminChangeForm add_form = UserAdminCreationForm # The fields to be used in displaying the User model. # These override the … -
How to create a search engine that generates images of ingredients for a particular meal?
I am using Django to create a web application where it includes a search engine that allows users to input a meal and the search engine provides the ingredients for the meal in images. So far, I have implemented ElasticSearch as my search engine. However, now I have the issue of gathering data of the images for the list of ingredients for the particular meal. How would I get the data? -
<mark> Html tag not working while rendering Html to pdf
I am generating a pdf from the html page . The mark highlighting tag was working fine in the html page but when i render to pdf the mark tag is not working but other css and html tag are working fine. My html code looks like this <!DOCTYPE html> <html> <head> <title>Report</title> <style> div.long-text{ max-width:100%; word-wrap: break-word; padding: 1rem; } html, body { max-width: 100%; } p { word-wrap: break-word; } body, input { margin: 5; font: .9em Verdana, 'Lucida Grande', Geneva, Lucida, sans-serif; } </style> </head> <body> <div> {% for i in text %} {% if i.0 == '0'%} <mark>{{i}}</mark> {% else %} {{i}} {% endif %} {% endfor%} </div> </body> </html> The output is like this: Please help figure out the solution. -
csrf token is missing in ajax
I am trying to build a ajax powered like button, but the ajax code is not working. views.py def like_button(request,postid): postresult=get_object_or_404(post,id=postid) if postresult.user_like.filter(id=request.user.id).exists(): postresult.user_like.remove(request.user) else: postresult.user_like.add(request.user) noresdat=postresult.totallikes response_data_to_dump={'success': True,'likes':noresdat} data = json.dumps(response_data_to_dump) return HttpResponse(data, content_type='application/json') while template is as follows:- {% for p in result %} <div class="SpriteContainer"> <a class="postlike" href="/like/{{ p.id }}"><img src="{%static "/images/icons/heart.png" %}"/></a> <p class="nolike" style="display: inline-block;">{{ p.totallikes }}</p></div> {% endfor %} <script> var csrftoken = $("[name=csrfmiddlewaretoken]").val(); $(".postlike").click(function(e){ e.preventDefault(); var $this = $(this); var url = $(this).data("action"); $.post(url, function(response){ if(response && response.success==true) $this.next(".nolike").text(response.likes); }); }); -
In flask if we change our database do we need to change our code also?
I have query about flask over django: As we know in django no matter whatever database we use(mongodb,mysql,postgres) we just need to write Djnago-ORM query to work with database. Just example: we have one django model: class User(models.Model): name = models.CharField(max_length=256) and we can get records using: User.objects.values() And it will give us all the records from User models. if we change our database also we don't need to change any thing in our code. except using these two commands. python manage.py makemigrations python manage.py migrate Then it will take care of everything. So, my queston is if we are using mysql in flask and in future we are changing our database to mongodb do we need to change our codes. Actually i am good at Django and don't have any idea about flask. So any clarification will be helpful for me , Thanks,