Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Download link from ForeignKey model
I would like to create an attachment on every post of my blog. Then I've do this: class FileUpload(models.Model): name = models.Charfield(max_length=70) file = models.FileField() def __str__(self): return self.name def get_absolute_url(self): return reverse("single_file", kwargs={"pk": self.pk}) class BlogPost(models.Model): title = models.Charfield(max_length=70) . . . attachment = models.ForeignKey( FileUpload, on_delete=models.CASCADE, related_name="related_attachment", null=True, blank=True, ) Inside the template of a single post I've put this: {% if blogpost.attachment %} <hr> <div> <a class="btn btn-info" href="{{ attachment.get_absolute_url }}" rule="button"> Download </a> </div> {% endif %} But I see that the href is empty and I can't download the attachment. The if condition work fine because the button didn't appear if the post don't have the attachment. What is the right way to put a download link inside my download button? -
Django Admin multiple inline validation upon submit
I'm trying to validate 2 inlines upon submit. The validation is a qty cannot be 0 if both inlines are zero and will allow if 1 of the qtys is greater than 1. Any suggestions on how to capture both form values upon submit and flag a validation error based on the logic above? Code Flow class AInlineForm(forms.ModelForm): qty = forms.IntegerField(min_value=0) class Meta: model = A exclude = ['created'] def __init__(self, *args, **kwargs): super(AInlineForm, self).__init__(*args, **kwargs) self.fields['qty'].initial = 0 class BInlineForm(forms.ModelForm): qty = forms.IntegerField(min_value=0) class Meta: model = B exclude = ['created'] def __init__(self, *args, **kwargs): super(BInlineForm, self).__init__(*args, **kwargs) self.fields['qty'].initial = 0 class BInline(admin.TabularInline): model = B extra = 1 max_num = 1 form = BInlineForm class AInline(admin.TabularInline): model = A extra = 1 max_num = 1 form = AInlineForm class OrderAdmin(admin.ModelAdmin): inlines = [AInline, BInline] -
Data not showing on template
This is the first time I'll be implementing a Class Based View on a real project but the data is not showing on the template. <div class="container"> <h4 class="heading-decorated text-center mt-5">Our Volunteers</h4> {% for volunteer in volunteers %} <div class="row row-30 text-center mb-5"> <div class="col-sm-6 col-md-3"> <figure class="box-icon-image"><a href="#"><img class="rounded" src="{{volunteer.volunteer_image.url}}" alt="" width="126" height="102"/></a></figure> <p class="lead">{{volunteers.volunteer_name}}</p> </div> </div> {% endfor %} </div> views.py class VolunteerListView(ListView): model = Volunteers context_object_name = 'volunteer' template_name = 'add_my_language/home.html' models.py class Volunteers(models.Model): volunteer_image = models.ImageField(upload_to='media/volunteers') volunteer_name = models.CharField(max_length=255, blank=False) def __str__(self): return self.volunteer_name Did I miss anything? -
Django adds https:// in all my static files. This is after integrating S3
After integrating s3 and adding my static url all my static files add a http:// in the url <link rel="stylesheet" href="https://http://bucket_name.s3.amazonaws.com/static/css/styles.css"> STATIC_URL='https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) -
AJAX request to a Django server stays on stalled Chrome
I have a simple django server with the Django Rest API installed. My problem is that when I make a simple query using AJAX the query stays stalled by Chrome: If I make this request disabling Chrome's cache (with the dev tools options) it loads without any problem. Here is the ajax query I use: $.ajax({ type:"GET", dataType:"json", beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Token '+global_api_token);}, url:url, error: function(result) { console.log(result) }, success: function(result){ console.log(result) } }); Does any know why this is happening? -
Django formset errorlist 'This field is required'
I am creating a formset with django which contains children information. I am using createview (CBV) for this. The form is displayed properly, it has functionality of adding children and removing children all working properly. But, when i click on submit, form_invalid is called instead of form_valid. To know this issue i printed form.errors and i saw following errors <ul class="errorlist"><li>deal_id<ul class="errorlist"><li>This field is required.</li></ul></li><li>child_name<ul class="errorlist"><li>This field is required.</li></ul></li><li>son_or_daugher<ul class="errorlist"><li>This field is required.</li></ul></li><li>child_age<ul class="errorlist"><li>This field is required.</li></ul></li><li>child_education<ul class="errorlist"><li>This field is required.</li></ul></li><li>child_occupation<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Below is my code Template :- {% extends "forms_app/base.html" %} {% load static %} {% block title %}{% endblock %} {% block content %} <h2>Profile</h2> <hr> <div class="col-md-4"> <form action="" method="post">{% csrf_token %} <table class="table"> {{ childrens.management_form }} {% for form in childrens.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} … -
Get not all values but specific values of field in another model with one to one field
I have two models. 1. courses 2. First Year Here is course Model class Courses(models.Model): class Meta: verbose_name_plural = 'Courses' year_choices = [ ('----', '----'), ('First Year', 'First Year'), ('Second Year', 'Second Year'), ('Third Year', 'Third Year'), ('Fourth Year', 'Fourth Year'), ('Minor', 'Minor'), ] year = models.CharField(max_length=50,default='----',choices=year_choices) course_code = models.CharField(max_length=10, default='', validators=[MinLengthValidator(1)]) Here is FirstYear Model class FirstYear(models.Model): class Meta: verbose_name_plural = '1. First Year' course = models.OneToOneField(Courses, default='', on_delete=models.CASCADE) title = models.CharField(max_length=100,default='') def __str__(self): return '{}'.format(self.title).capitalize() I'm new to Django. When I run this code all of the course code is returning. But I don't need that. My question is I have to invoke the course_code field only if it is first year and not all year. Please help me here. Thank you. -
Django 2.2 set ModelChoiceField initial value without id/pk
I have a GET based search, passing a few search terms and paging info through the query string. I can grab the items from the query string without any issues, but passing them back to the template via the SearchForm to preserve the search is proving to be difficult. items/?search=foo&category=bar&page=1&pageSize=20 forms.py class SearchForm(forms.Form): search = forms.CharField(*) category = forms.ModelChoiceField(queryset=Items.objects.all(), *) *simplified for brevity In the view, I can retrieve all the values or their defaults from the query string, and I can even set the value for the search field, but the ModelChoiceField is the one I am struggling with. I can set an initial value, but not based on the select text... views.py class ItemList(View): template_name = 'items.html' def get(self, request): items = Item.objects.all() form = SearchForm() search = request.GET.get('search') category = request.GET.get('category') page = int(request.GET.get('page', 1)) pageSize = int(request.GET.get('pageSize', 20)) if category != None: #non working: #form.fields['category'].initial = category #working by setting a value form.fields['category'].initial = 1 items.filter(category__name=category) if search != None: form.initial['search'] = search items = items.filter(field__icontains=search) context = { 'form': form, 'items': items } return render(request, self.template_name, context) I tried various methods of trying to retrieve the value/id from the form.category field unsuccessfully. I would hate … -
How to publish django web to local server?
I am now using django to develop a web page but I found that I have no idea to publish it. As I am a really new to web programming, I don't even know what the key words I should search for, but I am asked to write a web program and no one in the company can help me with this. I know in my company, the company website is publish on the local server with only the html files. Therefore, if I want to publish the whole django project, how can I do it? or where can I have those information to look for? My main goal is to publish it to the intranet and also can interact with other pages that were not developed by django. For example, in the nav bar, there will be one link to the webpage that designed by django. Thank you. -
python manage.py runserver command not working [duplicate]
This question already has an answer here: Django runserver error, new installation, first time user of Django 2 answers python manage.py runserver not working and showing errors that are shown in image: enter image description here Kindly suggest a solution -
Django: How to conditionally define fields in a model mixin?
In my back-end (API) site, there are certain fields that are common to most models, but not all. I have been using mixins for those fields so that I can include them for the models they apply to, and omit them from the ones they don't. For example: class AddressPhoneModelMixin(models.Model): address = models.TextField( verbose_name=_('Address'), blank=True, null=True, ) country = models.ForeignKey( Country, on_delete=models.SET_NULL, verbose_name=_('Country'), blank=True, null=True, ) phone_number = PhoneNumberField( verbose_name=_('Phone'), blank=True, null=True, ) mobile_number = PhoneNumberField( verbose_name=_('Mobile Phone'), blank=True, null=True, ) fax_number = PhoneNumberField( verbose_name=_('Fax'), blank=True, null=True, ) class Meta: abstract = True But I have other such mixins, and when a model needs to include all fields, the model definition gets to be quite long: class Client(AddressPhoneModelMixin, DateFieldsModelMixin, models.Model): And I now have other "common" fields I want to add, so it's only going to get worse. I want to keep all these common fields in one place for DRY, but also in case anything changes about a field, I only have one place to make the changes. My idea is to have one mixin called CommonFieldsModelMixin, so that I will have only one mixin to include in the model definition. But for those models that don't need certain … -
Specify aws named profile S3Boto3Storage
I am using S3Boto3Storage for uploading django images to s3. I have multiple profiles in my local. Can I specify profile name with S3Boto3Storage ? -
What effective technique can I apply to use the get_initial method twice to solve the problem stated below?
I have created 3 models A,B, and C that are linked to each other using foreign key. Model "B" is linked to Model "A" using OneToOne relationship and Model "C" is also linked to Model "B" using "OneToOne" relationship. I then used then "get_initial()" method to set the initial id_field for the form of model "B" using the foreign key conection with model "A". I later repeated the same "get_intial()" to set the initial id field for the form of model "C" using its foreign key connection with B. This worked as projected. How ever upon deleting a record instance in Model "B" with its id=7 as obtained from an instance in model "A", and re-creating a new record in model "B" using that same id=7. When ever I call the get_initial() method form "C" with the id=7 from model "B", I recieve an error message "matching query does not exist." And when I, increment the called id by 1, I get the correct result of the query. I went further to delete 4 more records in model "B" and recreated them with their ids as passed by model "A". And realized when ever I called the get_initial() method to … -
Allow Blank FileField in Django
I have a model where one of the fields is a FileField. The file that should be attached here is not available at the time of creating the Order - so it should be allowed for the user to create an Order without attaching a file here. If you see the code below - I feel like I have setup the model properly to allow this field to be blank, but when I try to submit an Order, I get an error "The 'order_file' attribute has no file associated with it." So what am I missing? models.py class Orders(models.Model): ... order_file = models.FileField(upload_to='web_unit', default=None, null=True, blank=True) def __str__(self): return self.reference since I have default=None, null=True, blank=True I expected that this would work without uploading the file at time of creating the Order object. -
Type Error on uploading image files through django admin
I've created a personal website/blog with python django, and as an admin, I want to create instances of that blog based on the django model and display it to the html page accordingly. That model basically consists of a Title field, TextArea field, and Image field. My app is currently deployed on Heroku, and I'm serving images using AWS S3 Buckets. Locally, when I create a blog instance through the django admin it is successful, but on the deployed app on Heroku, I'm getting this error: expected string or bytes-like object and this is what appears in the console was loaded over a secure connection, but contains a form that targets an insecure endpoint 'http://dpaste.com/'. This endpoint should be made available over a secure connection. I'm unsure if the error has to do with the image field or the entire instance of the blog model. Any ideas on how to approach this? -
Django Many to Many query set relation has unexpected result
When running a filter against a many-to-many relation the result of the field contains unexpected results according to the filter. Note The is_current Foo and Bar will have at most one True for a group of Foo/Bar. Meaning Foo has several that are False ie. not current and same with Bar. I've tried 4 variations Normal filter: just listing out fields to filter Boolean value as True/1 on the filter Q filter prefetch_releated and Q filter # model.py class Bar(Model): is_current = BooleanField() text = CharField(max_length=32) class Foo(Model): is_current = BooleanField() name = CharField(max_length=32) bar = ManyToManyField(Bar) # views.py def index(request): # when viewing the bar objects from the filter result # it will contain bar objects that are both is_current = True & False return Foo.objects.filter(Q(is_current=1) & Q(bar__is_current=1)) The query output looks like this: SELECT app_foo.id, app_foo.is_current, app_foo.name FROM app_foo INNER JOIN app_foo_bar ON (app_app.id = app_foo_bar.bar_id) INNER JOIN app_bar ON (app_foo_bar.bar_id = app_bar.id) WHERE (app_foo.is_current = True AND app_bar.is_current = True) If I modify the query and run it in the dbshell I get what I expected. SELECT app_foo.id, app_foo.is_current, app_foo.name, app_bar.text FROM app_foo INNER JOIN app_foo_bar ON (app_app.id = app_foo_bar.bar_id) INNER JOIN app_bar ON (app_foo_bar.bar_id = app_bar.id) … -
How to bined a detailview field to a form field in django and save into database
I am building this simple system for online voting, where people can vote but will have to pay for their vote cast.My current challenge is how to bined a selected candidate on a page and allowing voters to enter number of votes they went to cast for that candidate on the same page I have tried using SingleObjectMixin but am having problem saving the form in database. And also how can i prepopulate the select candidate to a model field name Nominee model.py class Award(models.Model): STATUS_PUBLISHED = ( ('Closed', 'Closed'), ('Opened', 'Opened'), ) slug = models.SlugField(max_length=150) name = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='award_images') status = models.CharField(max_length=20, choices=STATUS_PUBLISHED, default='Closed') def __str__(self): return self.name class Category(models.Model): Award = models.ForeignKey(Award, on_delete=models.CASCADE) category = models.CharField(max_length=100,) slug = models.SlugField(max_length=150) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.category class Nomination(models.Model): Fullname = models.CharField(max_length=120) Category = models.ForeignKey(Category, on_delete=models.CASCADE) votes = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=150) image = models.ImageField(upload_to='nominations_images') def __str__(self): return self.Fullname class VoteAmount(models.Model): Nominee = models.ForeignKey(Nomination, on_delete=models.CASCADE) votes_amount = models.IntegerField(default=0) def __str__(self): return self.votes_amount views.py from django.views.generic import ListView, DetailView, CreateView from .models import Award, Category, Nomination, VoteAmount from .forms import VoteAmountForm from django.urls import reverse from django.http import HttpResponseForbidden from django.views.generic import … -
Django REST Framework Deep Dive - Where is it determined that an enpoint needs an auth token
general django question for those who are more experienced than myself, I'm reading through the code posted for a tutorial on thinkster.io: https://github.com/howardderekl/conduit-django/tree/master/conduit/apps There's an endpoint pertaining to the User model authenticion/models.py that requires an Authorization header for it to return user information defined here in authentication/views.py: class UserRetrieveUpdateAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) renderer_classes = (UserJSONRenderer,) serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(request.user) return Response(serializer.data, status=status.HTTP_200_OK) My question is how/where is it (supposed to be) determined that an endpoint requires this Authorization. My thought is that it is tied to the permission_classes variable stated in the UserRetrieveUpdateAPIVIiew class above. I dug into the package location where this was imported from (from rest_framework.permissions import IsAuthenticated), but that doesn't appear to contain anything pertaining to an HTTP header: class BasePermissionMetaclass(OperationHolderMixin, type): pass class BasePermission(metaclass=BasePermissionMetaclass): """ A base class from which all permission classes should inherit. """ def has_permission(self, request, view): """ Return `True` if permission is granted, `False` otherwise. """ return True def has_object_permission(self, request, view, obj): """ Return `True` if permission is granted, `False` otherwise. """ return True ... ... ... class IsAuthenticated(BasePermission): """ Allows access only to authenticated users. """ def has_permission(self, request, view): return bool(request.user and … -
Whenever I try to load a static file, it gives error 404 not found
Whenever I try to load a static file, it gives error 404 not found. However when checking what directory it looks in it shows /account/login/static/accounts/style.css, when account/login isn't even a directory. The error message is Not Found: /account/login/static/accounts/style.css I've searched everywhere and can't find how to change the directory. Here is the settings.py file: STATIC_URL = '/static/' LOGIN_REDIRECT_URL = '/accounts' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] Here is my accounts/urls.py: from django.contrib.auth.views import LoginView from django.urls import path from accounts import views app_name = "users" urlpatterns = [ path('', views.home, name='home'), path('login/', LoginView.as_view(template_name='accounts/login.html'), name="login") ] Here is my tutorial/urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('accounts.urls')) ] And here is my view.py: from django.shortcuts import render, HttpResponse def home(request): return render(r[enter image description here][1]equest, "accounts/login.html")[enter image description here][1] Here is a image of my directory/files: https://i.stack.imgur.com/vdk0X.png -
In Django, how can I build a set of criteria from a list?
I'm using Python 3.7 and Django. Is there a way I can rewrite the below so taht I just execute one query instead of a bunch? def get_articles_with_words_in_titles(self, long_words): result = {} for word in long_words: qset = Article.objects.filter(title__icontains=word.lower()) result.extend( qset ) return result I want to get a unique list of the Article objects that have at least one of the words in them. -
Cannot add CSRF token to XMLhttpRequest for Django POST request
CSRF token is not being added to the header of the XMLhttpRequest. To make sure all the other code works, I've tried using a GET request to the server and everything works as it should. However when I add the CSRF token to the header the code stops running when adding the header. // [PROBLEM CODE] // Initialize new request const request = new XMLHttpRequest(); const currency = document.querySelector('#currency').value; request.setRequestHeader({'csrfmiddlewaretoken': csrftoken}); // [<---HERE] request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); // [<---HERE] request.open('POST', '/convert'); // [THIS WORKS] // Initialize new request const request = new XMLHttpRequest(); const currency = document.querySelector('#currency').value; request.open('GET', '/convert'); request.send(); When I take out the two problem lines of code, setRequestHeader and make a POST request. The error message I get is "Forbidden (CSRF token missing or incorrect.): /convert" -
Dinamically Filtering based on foreign key in Django Admin View
Question regarding admin view editing models. I can't figure out how to dinamically filter a the foreign keys of a TabularInLine model based on the foreign key of the currently edited model. models.py: from django.db import models class A(models.Model): name = models.CharField(blank=False, max_lenght=50) class B(models.Model): fkA = models.ForeignKey(A, on_delete=models.CASCADE) name = models.CharField(blank=False, max_lenght=50) class C(models.Model): fkA = models.ForeignKey(A, on_delete=models.CASCADE) fkB = models.ForeignKey(B, on_delete=models.CASCADE) name = models.CharField(blank=False, max_lenght=50) admin.py: from django.contrib import admin from .models import A, B, C class BInline(admin.TabularInLine): model = B class CInline(admin.TabularInLine): model = C @admin.register(A) class AAdmin(admin.ModelAdmin): inlines = [BInline, CInline] admin.site.register(B) admin.site.register(C) The thing is, I want that in the admin edit view of A, at the inline section of C the dropdown which includes B to list only the models that are associated with the currently edited A model through the foreign key. As it is it lists all the available models in my database. I hope I was clear in my explanation and that anyone is kind enough to help me. Thanks! -
Calling a Django-Rest API from a Django Form
I built a Django-Rest API with an APIView that uploads a file to a folder of a web server. This API is working with Postman as shown in the pictures below. Now, I am working on calling this API from the below HTML form Issue I am facing: the file sent via the form returns the following error "file": [ "No file was submitted." ] Below the code of my application index.html <form action="/file/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input id="audio_file" type="file"/> <input type="submit" value="Upload File" name="submit"/> </form> views.py class IndexView(TemplateView): template_name = "index.html" log = logging.getLogger(__name__) log.debug("Debug testing") def post(self, request): # TODO: fix, empty file error returned after calling post method # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: # https://docs.djangoproject.com/en/2.2/ref/forms/api/#binding-uploaded-files form = FileForm(request.POST, request.FILES) # check whether it's valid: if form.is_valid(): form.save() # redirect to the same URL: return HttpResponseRedirect('/App/index/') # if a GET (or any other method) we'll create a blank form else: form = FileForm() return render(request, 'index.html', {'form': form}) class FileView(views.APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request): … -
Yubikey OTP via Yubicloud not working in DJANGO behind nginx
Using the package django-otp-yubikey to provide Yubikey 2FA for the admin panel in a DJANGO application works without any problems when using GUNICORN, but as soon as we using GUNICORN and NGINX in front of it, the package doesn't work anymore. Tried contacting different versions of the Yubicloud API (1, 1.2, 2). Also tried contacting them with SSL disabled / enabled. This is the nginx configs: location /...../ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/../.../...sock; allow X.X.X.X; deny all; } Getting a 504 gateway timeout when NGINX is in front of the django application, making me believe it might be blocking a the request made to the yubicloud servers. -
Filtering data before rendering- django-filters
I am using django-filters, and i want that data only with status = 1 should be displayed. I will not be showing status in my diplayed table. filters.py class ActiveSimFilter(django_filters.FilterSet): type = django_filters.CharFilter(field_name='name', lookup_expr='icontains') phone_number = django_filters.CharFilter(field_name='phone_number', lookup_expr='icontains') class Meta: model = Sim fields = { } order_by = ["type"] def get_initial_queryset(self): return Sim.objects.exclude(sim_status=1)