Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django can't write or read media to/from disk on Rasbian, Raspberry Pi 3B
So previously everithing was fine when I was running the project from my laptop(Antergos) like so: sudo python manage.py runserver. Without sudo it fails to write and read media files. I'm currently running Django on Raspbian in virtualenv as pi user. If I try running the command with sudo as far as I understand it tryes to run from the global pip libraries and it throws errors. I tried changing permisions the bad way sudo chown -R 777 /project_root_directory but this did not hellp. There are tutorials for configuring it using Apache Ngnx but that does not hellp becouze I don't have var/www.I am running from Django developement server. Can someone point me in the right direction? If aditional information about my project is needed please specify. -
Django rest framework attach data to models
I am trying to attach data to one of my models. The issue I am having is that the model doesn't have the field in question. Here is my model: from rest_framework import serializers from games.models import Game class GameSerializer(serializers.ModelSerializer): class Meta: model = Game fields = ('id', 'name') In this case, games have the idea of characters... Which there are many characters per game. However, I don't want to add characters to the game model. Here is the characters model: from django.db import models from django.utils import timezone from games.models import Game class Character(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) def __str__(self): return self.name class Meta: db_table = "characters" I want an endpoint where I can get characters by the game id. Basically, I want to return just the characters for an endpoint like games/1/characters. How can this be done? Seems like I have to query the database with the game id and then serialize the output with a character serializer, but I am unsure how to go about it. Perhaps I don't even need the game model for this? -
staged updating of model instances and related keys for concurrent access
I have a Django model with some related keys that needs to be updated one or more times (both the model instances and its related keys). But when one or more updates are done, user may opt to cancel all the updates or keep them. It is all or none and no intermediate changes needs to be preserved. And when one user is editing it the other users can only read it and should be able to see the last committed changes. What is the best way to achieve this in Django ? Thanks. I have thought of 2 options: 1.0 Temporary copy of instance 1.1 Method: create a new model instance with new related keys from the original model instance/related keys. And make all the changes to this new copy. And when user finalizes then overwrite the contents of original instance with new instance and delete the new instance, update the related keys etc. If user cancels the changes, then just delete the new instance. 1.2 Cons: requires special handling for many keys like autogenerated keys, related keys etc. Doesn't seem to automatically handle when new related keys are added. 1.3 Pros: very localized change without impacting my entire … -
Login and authentication functionality in Django REST API and React Native
One of my projects I have developed backend API using Django REST Framework and mobile app using React Native. I have done the following things: When the users log in I store their username in local (mobile) database. When users post data I send the username to server reading from local database along with the POST data. I check whether the user is logged in or not using the username and then process the request. My question is: am I doing it in the right way? If no then what are the right procedures to do this kind of authentication checking? -
Click in a dropdown option and show an specific field in Django
I have the following situation, I have this model: class Profile(models.Model): DEVELOPER = 1 MARKETER = 2 ACADEMIC = 3 INFLUENCER = 4 COMMUNITY_MEMBER = 5 ROLE_CHOICES = ( (DEVELOPER, 'Developer'), (MARKETER, 'Marketer'), (ACADEMIC, 'Academic'), (INFLUENCER, 'Influencer'), (COMMUNITY_MEMBER, 'Community Member'), ) user = models.OneToOneField(User) account_type = models.ForeignKey(AccountType, default=AccountType.FREE) role = models.PositiveIntegerField(choices=ROLE_CHOICES, null=True, blank=True) github_profile = models.URLField(blank=True, null=True) linkedin_profile = models.URLField(blank=True, null=True) And now what I want to do is that if the user clicks in the dropwdown the Developer option, the github_profile should appear, otherwise it should keep hide. I know this is a conditional thing, however I'm brand new in Django and I'm not pretty sure how to achieve it. -
Is there a way to hide an object in a queryset in Django models?
Like you see the codes below, I'm manually using an attribute status in Store model to show my stores in HTML Templates. The problem is the more codes I make, the more repeating codes happen. I'm trying to find a way to avoid those inefficient repetitions. Is it possible to set up in models.py to show only active stores to be shown in HTML templates? I'm asking this because I've already done a similar thing to this. I have a string type attribute, but I need it in a list format in my templates, so I made a function to call it only with a list format. But, I can't figure out how to hide inactive stores in the same way. Can anyone give me some suggestins for this? models.py class Store(models.Model): status = models.CharField(max_length=20, choices=( ('active', 'Active'), # ('Stored value', 'Label shown on the UI') ('inactive', 'Inactive'), ), default='inactive') ... HTML Templates {% if store.status == 'active' %} ... Show store {% else %} ... Do not show store {% endif %} -
Django, Form Resubmit on refresh page?
I am developing a django app, when i submit the form its works correctly but when i refresh the page the form resubmit the data again to the database i have tried everything i can but can't seem to get this to work right my view def _article(request, article_id): try: article = Article.objects.get(pk=article_id) related_articles = Article.objects.filter(tags=article.tags).exclude(pk=article.pk)[:4] context['article'] = article context['related_articles'] = related_articles context['comments'] = article.comments_set.all().order_by('-date')[:4] if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.cleaned_data['comment'] article.comments_set.create(comment=comment) return render(request,'blog/article.html',context) else: form = CommentForm() context['form'] = form return render(request,'blog/article.html', context) except Exception as e: #write error to file return render(request,'blog/404.html') -
I want to use django-postman app and edit in it
How to use django-postman app! after i install it and add it to the installed_app in settings.py but when i run http://127.0.0.1:8000/messages/ i got this error TemplateDoesNotExist at /messages/inbox/ base.html Request Method: GET Request URL: http://127.0.0.1:8000/messages/inbox/ Django Version: 2.0.4 Exception Type: TemplateDoesNotExist Exception Value: base.html Exception Location: C:\Users\Abdalla\AppData\Local\Programs\Python\Python36\lib\site- packages\django\template\backends\django.py in reraise, line 84 Python Executable: -
Django OneToOne Error
Assume the class: class M(models.Model): rel = models.OneToOne(X,on_delete=models.CASCADE) Now if I want to access an instance M through instance x of X I would write: x=X.objects.all().first() x.m However, when there doesn't exist an instance of M related to x, it throws an error. How do I make it return None instead of an error. -
How to complete the order?
Please tell me how to do that when buying goods cleared basket. And there is a problem that without re-authorizing can not make more than 1 order (throws to complete the purchase of the last product) The essence of the work: after pressing the checkout button, the goods are sent to the orders and the next field is filled in the address, after the address the final form comes out, where it is indicated how much and what was bought (here and throws at the next order). In General, I do not know how to complete the order. carts:home {% extends "base.html" %} {% block content %} <h1>Cart</h1> {% if cart.products.exists %} <table class="table cart-table"> <thead> <tr> <th>#</th> <th>Название: </th> <th>Цена: </th> </tr> </thead> <tbody class='cart-body'> {% for product in cart.products.all %} <tr class='cart-product'> <th scope="row">{{ forloop.counter }}</th> <td><a href='{{ product.get_absolute_url }}'>{{ product.title }}</a> {% include 'carts/snippets/remove-product.html' with product_id=product.id %} </td> <td>{{ product.price }}</td> </tr> {% endfor %} <tr> <td colspan="2"></td> <td><b>Subtotal</b> $<span class='cart-subtotal'>{{ cart.subtotal }}</span></td> </tr> <tr> <td colspan="2"></td> <td><b>Total</b> $<span class='cart-total'>{{ cart.total }}</span></td> </tr> <tr> <td colspan="2"></td> <td><a class='btn btn-lg btn-success' href='{% url "cart:checkout" %}'>Checkout</a></td> </tr> </tbody> </table> <div class='cart-item-remove-form' style='display:none'> {% include 'carts/snippets/remove-product.html' %} </div> {% else … -
Django views.py cache page not working
I am trying cache page which takes about minute to load on django 2.0.3, there is no Model involved. I set memcached as in settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } and middleware as 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', I verified if memcached is set properly like >>> from django.core.cache import cache >>> cache.set('test', 'testvalu1') >>> cache.get('test') 'testvalu1' And I set views.py as @cache_page(60*5) def index(request): When I go to url http://127.0.0.1:8000/testurl/ which calls index take about minute to load but I can see css/js files loaded (from memory cached) but not the testurl/. Am I missing something? -
How to display 2 queryset list Frond end?(Django ListView get_queryset)
Hi guys, I got 2 queryset list expired_item and queryset in Django ListView, but I don't know when item is expired(queryset is empty), how to display another list expired_item on frond end, I pasted my code as below: class ABCListView(ListView): model = ABC ordering = ('name', 'skill_course') context_object_name = 'abcs' template_name = '' def get_queryset(self, **kwargs): # Omitted ...... ...... # Omitted expired_item = list(ABC.objects.filter(pk__in=aa).exclude(pk__in=z)) queryset = Permit.objects.filter(pk__in=z) return queryset And my html file of abc.html as below: {% extends 'base.html' %} {% block content %} <nav aria-label="breadcrumb"> </nav> <h2 class="mb-3">My Items list</h2> <div class="card"> <table class="table mb-0"> <thead> <tr> <th>Name</th> <th>Department</th> <th>Status</th> <th></th> </tr> </thead> <tbody> {% for a in abcs %} <tr> <td class="align-middle">{{ a.name }}</td> <td class="align-middle">{{ a.department.get_html_badge }}</td> <td class="align-middle badge badge-pill badge-danger">{{ a.status }}</td> </tr> {% empty %} {% endfor %} </tbody> </table> </div> <h2 class="mb-3">My Expired Items list</h2> <div class="card"> <table class="table mb-0"> <thead> <tr> <th>Name</th> <th>Department</th> <th>Status</th> <th></th> </tr> </thead> <tbody> {% for b in expired_item %} <tr> <td class="align-middle">{{ b.name }}</td> <td class="align-middle">{{ b.department.get_html_badge }}</td> <td class="align-middle badge badge-pill badge-danger">{{ a.status }}</td> </tr> {% empty %} {% endfor %} </tbody> </table> </div> <div class="card-footer"> Thanks so much for any advice! -
Django ModelForm - Get value from ManyToManyField
I need to get the selected value(s) of year from the PreceptorForm. I can get the internal_tel using post.internal_tel but I can't do that with year because it's a ManyToManyField. I need something like preceptor.year.add(post.year) but it gives me an error. What is the best way to do it? models.py class Year(models.Model): year_number = models.IntegerField(choices=YEAR_CHOICES) division = models.CharField(choices=DIVISION_CHOICES, max_length=1) def getStudents(self): results = Student.objects.filter(year=self) return results def __str__(self): return "{}-{}".format(self.year_number, self.division) class Preceptor(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) internal_tel = models.IntegerField(blank=True) year = models.ManyToManyField(Year,blank=True,related_name='preceptores') def getYear(self): results = self.year.all() return results def __str__(self): return "{} {}".format(self.user.first_name, self.user.last_name) forms.py class PreceptorForm(ModelForm): class Meta: model = Preceptor fields = '__all__' exclude = ['user'] views.py def register_user(request): if request.method == "POST": form = PreceptorForm(request.POST) username = request.POST['username'] password = request.POST['password'] sec_pass = request.POST['sec_password'] email = request.POST['email'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] if form.is_valid(): if password == sec_pass: user = User.objects.create_user(username, email, password) user.is_active = True user.first_name = first_name user.last_name = last_name user.save() print "form" post = form.save(commit=False) post.user = user preceptor = Preceptor(user=user,internal_tel=post.internal_tel) preceptor.save() preceptor.year.add() preceptor.save() return redirect('/') else: form = PreceptorForm() return render(request, 'register.html', {'form': form}) -
Posting data to Django with Ajax, jQuery
I would like to submit the html5 geolocation data to the django admin backend. However I am not sure if the javascript, jQuery and ajax is set up correctly in the index.html javascript . I am able to display the latitude and longitude in the html page but am unable to post the data to django. Is there someone kind enough to help correct where I might have gone wrong. I have been working on it for a week being a newbie. Would truly appreciate any help. Thank you. index.html {% extends 'ajax/base.html' %} {% block body %} <p>Click the button to get your coordinates.</p> <button onclick="getLocation()">Get Your Location</button> <p id="demo"></p> <button type="button" id="btn_submit" class="btn btn-primary form-control">Submit</button> <script> var x = document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; } $(document).ready(function(){ $('#btn_submit').on('click', function(){ $.ajax({ type: "POST", url : "insert", data: { latitude: $position.coords.latitude, longitude: $position.coords.longitude, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(){ alert("Saved Data!"); } }); }); }); </script> {% endblock %} base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"> {% … -
Reduce time Django session is stored?
I am currently using cached database-backed sessions in my project. However, the default expiration time for each session is too long and I still have some in my database dating back to April. I am running a cronjob for clearsessions every night but it is still storing way too much data. Is there a way to reduce the default expiration time for databse-backed sessions in Django to...like a week? -
Django check if the user that is logged in is the user that created a record
I have a Django model that records the user who created a record. I want to display a button on a template only if the user logged in is the same as the user on the record. I want to do something similar to: {% if user.is_authenticated and (request.user.is_superuser or request.user == task.user) %} where task is the record. How can I do this? -
list_of_post() got an unexpected keyword argument 'slug'
I am following a tutorial, but this tutorial's django version is different form mine which is 2.0.5. So,I got this issue: list_of_post() got an unexpected keyword argument 'slug' Request Method: GET Request URL: http://127.0.0.1:8000/blog/a-test/ Django Version: 2.0.5 Exception Type: TypeError Exception Value: list_of_post() got an unexpected keyword argument 'slug' Exception Location: /Users/sumeixu/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response, line 126 Python Executable: /Users/sumeixu/anaconda3/bin/python Python Version: 3.6.3 Python Path: ['/Users/sumeixu/djangotest', '/Users/sumeixu/anaconda3/lib/python36.zip', '/Users/sumeixu/anaconda3/lib/python3.6', '/Users/sumeixu/anaconda3/lib/python3.6/lib-dynload', '/Users/sumeixu/anaconda3/lib/python3.6/site-packages', '/Users/sumeixu/anaconda3/lib/python3.6/site-packages/aeosa'] Server time: Thu, 7 Jun 2018 15:00:29 +0000 blog/view.py def post_detail(request,slug): post = get_object_or_404(Post,slug=slug) template = 'blog/post/post_detail.html' return render(request,template,{'post':post}) post_of_detail.html {% extends 'blog/post/base.html' %} {% block title %}{{post.seo_title}}{% endblock %} {% block content %} <h2>{{ post.title }}</h2> <p>Written by {{post.author }} on {{post.published}}</p> <hr> {{posts.content} {% endblock %} list_of_post.html {% extends 'blog/post/base.html' %} {% block title %}List of blog post{% endblock %} {% block content %} {% for posts in post %} <h2><a href="{{posts.get_absolute_url}}">{{ posts.title }}</a></h2> <p>Written by {{ posts.author }} on {{ posts.published}}</p> <hr> {{ posts.content}} {% endfor %} {% endblock %} blog/urls.py from django.conf.urls import url from django.urls import path from . import views app_name = 'blog' urlpatterns =[ path('',views.list_of_post,name='list_of_post'), path('<slug:slug>/',views.list_of_post,name='post_detail') ] I am sorry if this is too simple. But I am still a programmer beginner. Just … -
How to fill a Django custom multiplechoicefield with choices
I have a form with a search box that uses jQuery to fill a multipleChoiceField. I need to use a custom multipleChoiceField so I can control the validation and only check if the choice exists, not if it was one of the original choices as a modelMultipleChoiceField with a queryset would. However, the custom multipleChoiceField renders on the page as empty until you enter something in the search box to fill it with choices via jQuery. I would like it to render with a few choices to begin with instead. class ArticleMultipleChoiceField(forms.MultipleChoiceField): def __init__(self, *args, **kwargs): super(ArticleMultipleChoiceField, self).__init__(*args, **kwargs) include_articles = [article.id for article in Article.objects.order_by('-sub_date')[:5]] self.choices = Article.objects.filter(id__in=include_articles).order_by('-sub_date') In this form, I get the error "Article object is not iterable". I have also tried changing that self.choices to self.data, self.queryset, and self.initial, and in all those 3 cases, I keep getting an empty multiple choice field instead. How can I use a queryset to provide the initial set of choices here? Here is the form it is used in: class StorylineAddArticleForm(forms.Form): articleSearchBox = forms.CharField(label="Search to narrow list below:") include_articles = [article.id for article in Article.objects.order_by('-sub_date')[:5]] articles = ArticleMultipleChoiceField() def __init__(self, *args, **kwargs): super(StorylineAddArticleForm, self).__init__(*args, **kwargs) self.fields['articleSearchBox'].required = False self.helper … -
How to get field value in template Django
I want to show some specific fields in my template from the value of another field. I'm rendering fields manually. models.py OPTIONS = ( ('YES', 'Yes'), ('NO', 'No'), ) question = models.CharField( max_length=2, choices=OPTIONS, verbose_name="Are you employed now?") company_name = models.CharField( max_length=30, blank=True) info.html <strong>{{ form.question.label_tag }}</strong> {{ form.question }} {% if form.question.value == "YES" %} <!-- I want to do something like this and then rendering others fields --> <strong>{{ form.company_name.label_tag }}</strong> {{ form.company_name }} {% endif %} The if statement above doesn't work for me, is there a way to get that? Thanks a lot. -
Iterate and set Class Attributes - Python Django
Is it possible to set class attributes outside of the __init__ function, as a class attribute (rather than an instance attribute). I want to do something like this: class Trades(): def __init__(self): for i in range(24): setattr(self, f'Hour_{i}', 0) but for a django model, e.g. something like: class Trades(models.Model): date = models.DateField() Hour_0 = models.FloatField() Hour_1 = models.FloatField() for i in range(24): setattr(models.Model, f'Hour_{i}', models.FloatField()) But that doesn't work. Is there another way I can iterate it, or do I have to manually assign each Hour_X a FloatField ? -
Django How to redirect to 404 page if url patterns don't match
I am developing a blog with django,I want to redirect users to 404 page in case url patterns do not match. I know how to redirect to the 404 page when search queries to the database do not match i want to be able to do this when a url do not match any define in urlpatterns. How can i achieve this with django. -
Django get model field verbose name doesn't recognize model
I am implementing a function that receives a model and a list of field names, and must return a list with the verbose names of such fields, but I get an error when using model._meta.get_field. This is the function: def get_titles(model, fields): titles = [] for field in fields: title = model._meta.get_field[field].verbose_name titles.append(title) return titles And this is the traceback I get: Internal Server Error: /es/general/catalogs/ Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/IntellibookVenv/lib/python3.6/site-packages/django/views/generic/base.py", line 89, in dispatch return handler(request, *args, **kwargs) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/Intellibook/GeneralApp/utils.py", line 55, in get return HttpResponse(get_catalogs(request)) File "/Users/hugovillalobos/Documents/Code/IntellibookProject/Intellibook/GeneralApp/utils.py", line 29, in get_catalogs 'titles': get_titles(Country, CountrySerializer.Meta.fields)}, File "/Users/hugovillalobos/Documents/Code/IntellibookProject/Intellibook/GeneralApp/utils.py", line 47, in get_titles title = model._meta.get_field[field].verbose_name TypeError: 'method' object is not subscriptable [07/Jun/2018 15:04:17] "GET /es/general/catalogs/ HTTP/1.1" 500 77597 -
How to Beautify rss feed in django?
I generate rss feed for my website using Django. I using below code for generate feed. class getTenderfeeds(Feed): title = "Tender Links" link = "/rss-tender/" description = "Tender link feeds" def items(self): return CareerTenderCT.objects.order_by('-cart_created_datetime')[:3] def item_title(self, item): return item.cart_title def item_description(self, item): return item.cart_desc def item_link(self, item): return '/view/12/'+ item.cart_absolute_url After that in url.py call this class. url(r'^rss-tender/', getTenderfeeds()), When i open this url the UI part is look like below image. But i want to change beautify in xml, like below image. -
Python: Default value in for loop
The for loop has 3 iterations (and will be more soon). Is it possible to define a standard value for assign_organizer after the second loop? [...] name = ['Super Bowl 2018', 'Jon Summer 2019', 'Jon Summer 2020', ] slug = ['super-bowl-2018', 'jon-summer-2019', 'jon-summer-2020', ] first_organizer = Organizer.objects.all().first() last_organizer = Organizer.objects.all().last() assign_organizer = [first_organizer, last_organizer, ] for i in range(len(name)): Event.objects.create( organizer=assign_organizer[i], name=name[i], slug=slug[i], status='on_sale', short_description=lorem, additional_information=lorem_long, venue_name=lorem, venue_address=lorem, start_date='2018-05-26 18:12:58.556925+02', end_date='2018-05-26 18:12:58.556925+02', facebook_event_link=lorem, banner=lorem, ) -
Django : Object didn't load in HTML template
I'm making my Django website and I'm getting an issue according to my first website template (my homepage). Environment : Django 2.0.1 Python 3.5 MariaDB 10.1 Issue : When I can access to my Django Homepage, it should display an image, according to my view but I get nothing. I get my picture only if I go somewhere else and I come back to the homepage. My code : My models.py class Photo(models.Model) : Nom = models.CharField(max_length=50, verbose_name="Nom de l'objet", blank=False) Date = models.DateField() ... Image_upload = models.ImageField(upload_to='Media/', width_field=None, height_field=None, verbose_name="Image") My views.py : from django.shortcuts import render from Photographies.models import Photo def Accueil(request): photo = Photo.objects.all().order_by('-Date')[0] return render(request, 'Accueil.html', {"photo": photo}) My HTML template : <!-- This script lets to define homepage template for "Accueil" --> {% extends 'Base_Accueil.html' %} {% load staticfiles %} {% load static %} {% block content %} <div id="content"> <br></br> <div id="content-1"> <div id="presentation-title"> <p>Petit mot de l'Astrophotographe & Développeur du site</p> </div> <div id="presentation-text"> <p> Je vous souhaite la bienvenue sur mon site dédié à l'Astrophotographie. A travers votre parcours sur celui-ci, vous allez découvrir ma passion pour la photographie des objets de l'Univers. Du Soleil, notre étoile, aux galaxies les plus lointaines …