Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin on subdomain
In a django project I'm working on I have an admin page. For cosmetic reasons I want admin.domain.com to point to domain.com/admin. My server runs apache2. I tried two things using mod_proxy and mod_rewrite: <virtualHost *:443> <Location /> ProxyPass "domain.com/admin/" ProxyPassReverse "domain.com/admin/" <Location> "other settings not relevant for this question" </virtualHost> and <virtualHost *:443> RewriteEngine on RewriteCond %{HTTP_HOST} ^admin2\.sun\.snt\.utwente\.nl [NC] RewriteRule ^(.*)/?$ https://dev.sun.snt.utwente.nl/admin/$1 [L] "other settings not relevant for this question" </virtualHost> Using the mod_proxy virtualhost I get the error Page not found (404) Request URL: "domain.com/admin/admin/" Using the mod_rewrite virtualhost I do not get an error, but get redirected to domain.com/admin//. This works regardless of the double slash on the end. The url in the browser is however no longer admin.domain.com. These stackoverflow questions are relevant, but do not give the answer I seek, either because they answer a slightly different answer or because of other constraints in the project. Django admin on different domain Serving Django admin site on subdomain Using subdomains in django Possibly relevant: My settings have a file structure like in the answer of Django to use different settings.py file based on subdomains. I run django 2.1 using wsgi in apache2. Actual question: How do … -
Populating Django Template with Variables and Database Data?
I'm using Django to create an application with different types of words / terms. On one page, you may have the title "Terms" and then a list of terms. On another page, you have the exact same thing but for phrases (header, list of phrases). Essentially, the format and type of information on each page should be the same. Right now, for each page, I have a .html page/template that calls the view and populates the page with term or phrase information. Is it possible to do something like this --> I store all the headers and lists in a database or XML file and write a function somewhere that says, for each piece of info, use this template to create a new page? I think I understand how to populate the pages with different info (by manipulating views), but the "create a new page" part is throwing me off. Does Django have a built in functionality for this, or do I have to write a separate python script to generate html files? That would also mean dynamically updating the urls.py file. That doesn't seem like a good/secure idea. Template example: {% extends "profile/base.html" %} {% block content %} <div … -
How to Shuffle Posts from Entire Database in DJango?
The views.py file has the following code: def index(request): post = Product.objects.all() context = { "post":post } return render(request, "index.html", context) And my template has the following code: <div class="features_items"><!--products --- features_items--> <h2 class="title text-center">Your Product Feed</h2> {% for p in post|slice:":50" %} <div class="col-sm-4", id="items"> <div class="product-image-wrapper"> <div class="single-products"> <div class="productinfo text-center shadow p-3 mb-5 bg-white rounded" style=" border-style: solid; border-width:0.1px; color: #E0E0E0;"> <a href="{{ p.product_url }}"><img src="{{ p.product_image }}" alt="" /></a> <h6 style="color: #666663"> {{ p.product_price }} &#2547; </h6> <a href="{{ p.product_url }}"> <p>{{ p.product_name|truncatewords:5 }}</p></a> <a href="#" style="color: #06c1bc;"><span class="glyphicon glyphicon-heart-empty"></span> Like</a> <a href="{{ p.product_url }}" style="color: #06c1bc; padding-left: 10px"><span class="glyphicon glyphicon-eye-open"></span> Detail</a> </div> </div> <div class="choose"> <ul class="nav nav-pills nav-justified"> {# <li><a href="#" class="btn btn-info btn-lg"><span class="glyphicon glyphicon-heart"></span> Like</a></li>#} {# <li><a href="#" class="btn btn-info btn-lg"><span class="glyphicon glyphicon-thumbs-down"></span> Unlike</a></li>#} </ul> </div> </div> </div> {% endfor %} </div> I want to show products coming from database are random (shuffled), not ordered by their ID. What change should I bring to my code? -
Django viewflow - create->pending->publish->edit->pending->publish
I am using django viewflow to create a publishing process: user creates an object it goes into a review process and its status is pending (it is not visible to the public) when it is reviewed and approved it gets published and becomes publicly visible. if user edits this same entity it goes into the review process again, but the old data is still visible to the public The part for creating and make it public is easy, but the part with editing not so much, if I want the old data to still be visible to the public. I was thinking to stop saving an object on pre_save and save it just into the process model. But I did not manage to make it work. How can this be done with django viewflow? Any thoughts? -
Best Python, IDE and Django combination for Analytics + UI project
I need guidance for the right combination of Python 3.8, IDE, and Django. I am building an analytics application that has some graphical presentation of the data. I prefer using IDE like VS Code; or any other suggestion. Since I want to focus mostly on the logic part of the application, and less on the UI and other aspects; Using Django for "rapid" web development sound alluring. Please suggest what IDE can best for easy UI and graphics presentations and where I can focus on the complex logic/analytics part. I am a part-time, learn as I need/as I go on hobbyist programmer. Thanks -
django admin base.css cannot be found
I have an openedx instance which works fine with just an strange issue. for those who aren't familiar with openedx it's a learning management system written in django. The issue: trying to access django admin from http://mydomain.tld/admin shows the login page properly but with two static files, unfortunately one of them (base.f4e3330c1326.css) is not on the file system and the request for its loading ends with a HTTP 404 Not Found response. looking at the static directory, there are 3 related files: ├── base.5af66c1b1797.css ├── base.css ├── base.d01c565630c2.css caclulating the base.css md5 checksum: user@host: ~$ md5sum /edx/var/edxapp/staticfiles/studio/admin/css/base.css 5af66c1b1797cb8f865b443cea0dcc17 /edx/var/edxapp/staticfiles/studio/admin/css/base.css using django shell to retrive the path to the files: >>> from django.contrib.staticfiles.templatetags.staticfiles import static >>> static('admin/css/base.css') '/static/studio/admin/css/base.f4e3330c1326.css' I have collected static files more than ten times but it doesn't fixed. my similar instance somewhere else has not this problem and I'm realy confused with it. could you please help me to debug this? PS: I don't know about webpack but I think they started to use it recently and I think it should have some relation to my issue... -
Extract WAV audio file from video after uploading on web, using FFMPEG in django
i am trying to find the way to extract audio wav file from mp4 video file that is uploaded by the user on web, using ffmpeg.I am working on Django framework .I found diferent solution but nothing work in my case.I will appreciate any help related to my situation . Secondly if I will find to extract audio then where I should save it in my project. 1.I tried it with "Django-ffmpeg" but it didn't convert and was stuck with 'pending conversion' message. 2.Then I tried with import subprocess subprocess.call('ffmpeg -i filename.mp4 filename.wav') but I face this error message My code is I here: def validate_file_extension(value): import os from django.core.exceptions import ValidationError ext = os.path.splitext(value.name)1 # [0] returns path+filename filename = os.path.splitext(value.name)1 # [0] returns path+filename valid_extensions = ['.mp4'] if not ext.lower() in valid_extensions: raise ValidationError(u'Unsupported file extension.') else: import subprocess subprocess.call('ffmpeg -i filename.mp4 filename.wav') Thanks -
Unable to save the data from a modelform
my models is something like this. models.py class Guest(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) mobile = models.PositiveIntegerField(validators=[MaxValueValidator(9999999999)]) def __str__(self): #"""String for representing the Model object.""" return f'{self.first_name}, {self.last_name}, {self.mobile}}' forms.py from django import forms from .models import Guest import datetime class GuestForm(forms.ModelForm): class Meta: model=Guest fields='__all__' def clean_date_of_admission(self): data = self.cleaned_data['date_of_admission'] #check if a date is not in the past if data < datetime.date.today(): raise ValidationError(_('Invalid date - admission date is past')) return data views.py from django.shortcuts import render from django.views.generic import ListView, CreateView, UpdateView from django.urls import reverse_lazy from .models import Guest from .forms import GuestForm def add_guest(request): if request.method=="POST": form = GuestForm(request.POST) if(form.is_valid()): guest_item = save(commit=False) guest_item.save() else: form = GuestForm() return render(request,'pgmanagement/guest_form.html',{'form':form}) guest_form.html <h2>Guest Form</h2> <form method="POST" action="" > {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="save"></input> </form> urls.py from django.urls import path, include from . import views urlpatterns = [ path('add/',views.add_guest, name='guest_add'), ] admin.py from django.contrib import admin from pgmanagement.models import Guest admin.site.register(Guest) OUTPUT: Whatever the data i am trying to add. it doesn't adding to the model(database) not even it is not throwing any error. Everything seems okay but not adding to the database. any suggestions please. -
Object not saving to 2 users
I have a form that saves a Booked model instance. When submitted, the form works fine and saves data to one user (the current logged in one). I want the form on submit to save the data to 2 users; one that is currently logged in, and the lesson, which was created by another user (their user is attached to the lesson instance). I have tried saving the form, then adding these users in my view, but that didn't work. I feel like the problem lies in my model or view formulation, and would appreciate any help with it. models.py class Booked(models.Model): users = models.ManyToManyField(User) booked_instrument = models.CharField(max_length=255, blank=True) booked_length = models.CharField(max_length=255, choices=length_list, blank=True) booked_date = models.DateField(null=True, blank=True) booked_time = models.TimeField(null=True, blank=True) views.py def book_lesson(request, lesson_id): if request.user.is_authenticated and request.user.time_zone: activate(request.user.time_zone) else: deactivate() lesson = Lesson.objects.get(id=lesson_id) if request.method == 'POST': form = BookedForm(request.POST) if form.is_valid(): book = form.save(commit=False) book.save() book.users.add(request.user) book.users.add(lesson.user) messages.success(request,'Lesson was successfully booked!') return redirect('/student/upcoming-lessons') else: form = BookedForm() form = BookedForm() context = {'form' : form, 'lesson' : lesson} return render(request, 'view/book_lesson.html', context) HTML <form action="{% url 'view:book_lesson' lesson.id %}" method="POST" autocomplete="off"> {% csrf_token %} <div class="hidden"> {% load tz %} {% timezone user.time_zone %} <p><span id="start">{{ … -
Django 2.1 - linking user to related model
I am creating a Django project, and I want to create profiles of two different user types as a separate model. They will have a OneToOneField relationship with the logged-in user. class UserMusician(models.Model): ... class UserFan(models.Model): ... I have seen two different ways of doing this. One, per the Django 2.1 docs shows passing in the User model, i.e.: from django.contrib.auth.models import User class UserMusician(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Whereas other examples, such as the Two Scoops of Django book, suggest passing settings.AUTH_USER_MODEL, i.e.: from django.conf import settings class UserMusician(models.Model): user = models.OneToOneField(settings.AUTH.USER.MODEL) Can anyone tell me what the differences are and what are the advantages and disadvantages to either? I would like to for these profiles to be generated in the database when a user account is created, one or the other. (As a 'nice to have', I'd like to allow a UserFan at a later point to become a UserMusician if they decide to switch) -
Django: The view services.views.addcardView didn't return an HttpResponse object. It returned None instead
After a user logs in, I want to perform a check to see whether the user had filled the AddCardForm the previous time, which is a form of the Card_detail model. If it was filled the user will be redirected to show_saved_card url. Otherwise, he'll be made to fillup the form. I wrote this view. After logging in, if i had not filled the form first time, I am getting this error: The view services.views.addcardView didn't return an HttpResponse object. It returned None instead. My app name is services. def addcardView(request): if Card_detail.objects.filter(user = request.user).exists(): return redirect('show_saved_card') else: if request.method == "POST": form = AddCardForm(request.POST) if form.is_valid(): card = form.save(commit=False) card.user = request.user card.save() return redirect('profile_complete') else: form = AddCardForm() return render(request, 'services/addcard.html', {'form': form}) Even if I remove this line: if Card_detail.objects.filter(user = request.user).exists(): return redirect('show_saved_card') else: I'm getting the error! -
Django: Updating only changed values in a form
I have a model with 10 fields. Through a modelform I show only 8 of them on the template for the user to edit. The problem is that when I save the form data It changes all non shown fields to empty. It seems like you HAVE to show ALL the fields in the template. I´m trying to get the list of changed_data and then use the update_fields with it, it doesn´t work. How can I achieve this? What I´m doing wrong? Thanks in advance! The view if request.method == "POST": perfil_cliente_form = EmpresaForm(request.POST, instance=contactos) if perfil_cliente_form.is_valid(): cliente = perfil_cliente_form.save(commit=False) campos_editados = perfil_cliente_form.changed_data cliente.FechaModi = date.today() cliente.save(update_fields=campos_editados) -
Django 2 register confirmation email directs to homepage instead of login page
I am setting up my Django 2.1 application so that when a user registers, they first are sent a confirmation email with a link to click on to activate the account. So far I have managed to set it up (with the help of another post) and everything works up until the point of clicking on the activation email. When I copy and paste the link into the browser, it directs me to the main landing page, not the login page. Is anybody able to look over my views and see if there is something missing? def register_view(request): if request.method == 'POST': # Post request. form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() mail_subject = 'Activate your account.' current_site = get_current_site(request) uid = urlsafe_base64_encode(force_bytes(user.pk)).decode() token = account_activation_token.make_token(user) activation_link = "{0}/?uid={1}&token{2}".format(current_site, uid, token) message = "Hello {0},\n {1}".format(user.username, activation_link) to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: # Get request. form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) def activate(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64).decode() user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): # … -
Django APIRequestFactory patch asking all fields
views.py class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer test_views.py class TestBookViewSet: @pytest.fixture def request_factory(self): factory = APIRequestFactory() return factory def create_book(self, request_factory): req = request_factory.post('api/v1/books', { 'name': 'test_from_test', 'isbn': '123-456789012', 'country': 'india', 'number_of_pages': 26, 'authors': ['test1'], 'publisher': 'pub1', 'release_date': '2019-05-26' }, format='json') resp = views.BookViewSet.as_view({'post': 'create'})(req) return resp def test_update(self, request_factory): self.create_book(request_factory) req = request_factory.patch('api/v1/books', {"name": "updated_name"}, content_type='application/json') resp = views.BookViewSet.as_view({'patch': 'update'})(req, pk=1) print(resp.data) assert resp.status_code == 200 assert resp.data['message'] == "The book test_from_test was deleted successfully." The resp.data in test_update gives following error. Whereas when I test the API in postman it accepts partial inputs. {'isbn': [ErrorDetail(string='This field is required.', code='required')], 'country': [ErrorDetail(string='This field is required.', code='required')], 'number_of_pages': [ErrorDetail(string='This field is required.', code='required')], 'publisher': [ErrorDetail(string='This field is required.', code='required')], 'release_date': [ErrorDetail(string='This field is required.', code='required')], 'authors': [ErrorDetail(string='This field is required.', code='required')]} Happy to provide more details in serializers.py and models.py if required. -
Django Identifying Class Based View and Form Multiple Models
I'm on my second Django project. On my first project I used all generic views, with only the most basic forms tied directly to a custom user model using UpdateView. In this project I'm trying to implement user profile functionality. My custom user model has some extra dummy fields just so I can manipulate the data. This I refer so as the CustomUser model. I also have a UserAddress model containing addresses since a user can have more than one address. I have tried looking for other questions, and I get similar questions, but there is always something missing: Django class based views - UpdateView with two model forms - one submit Using Multiple ModelForms with Class-Based Views Multiple Models in a single django ModelForm? Django: multiple models in one template using forms I've spent the last day or two looking for the "Django way" of doing what I want to do and have had no luck. My initial thought was that I could use a single template, fed with two ModelForms wrapped in a single <form> tag. The view would then process each form and update the CustomUser model and create or update the UserAddress models. I have figured … -
self-referencing ForeignKey with default value None
How can I set a default value on a self-referencing ForeignKey field in a django Model? class MyModel(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField('') master = models.ForeignKey('self', default=None) When saving without informing the master the error below occurs ValueError: save() prohibited to prevent data loss due to unsaved related object master -
how can i remove image in Class based UpdateView in django
I have a post update form in which i have imagefield. i want to know how can i remove already selected image when i update a post. so after updating the post will not have any image (if i leave image input empty on update it will show the already selected image on update). Here's image field: <div class="custom-file"> <input type="file" name="{{field.html_name}}" id="{{field.id_for_label}}"> <label class="custom-file-label" for="{{field.id_for_label}}">Choose file</label> </div> -
What are the differences: Django, Apache, AWS
I'm studying web and confused about the concepts of Django, Apache, and AWS. I have an experience of developing web backend with Django and AWS. Django handled the interactions between web browser and server. AWS enabled the clients to share the same server and data. But, what is Apache? This wasn't considered during the development. According to my research, Apache is web server application. But, I can't tell the exact difference of it with AWS. Does AWS include Apache? Please help me make sure what Apache is. Thanks :) -
How to add space and $ in front of column in django-tables2
I have two dollar columns in my django table, however, I don't like the spacing and the fact that it's right next to the preceding column. I also want to add a dollar symbol. How can I add this? Right now it looks like this: Price1Price2 345.09 154.35 I'd like it to look like this: Price1 Price2 $345.09 $154.35 My django table is basic: class PriceTable(tables.Table): class Meta: model = Price template_name = 'django_tables2/bootstrap.html' sequence = ('service', 'price1', 'price2') exclude = ("comments") attrs = {"class": "paleblue"} Those columns are defined like this in models.py: price1 = models.DecimalField(max_digits=6, decimal_places=2, blank=True) price2 = models.DecimalField(max_digits=6, decimal_places=2, blank=True) One futher question, is there a django-tables2 table description function or something to easily add info about the table, under the table? -
how to use embed code of any hosting server without showing icon?
how to use embed code of any hosting server without showing icon and other server information? Basically I want to only video...?I'm using Django. -
cross join in sqlalchemy 1.3
I can't understand how to connect two tables with cross join. Earler, at sqlalchemy version 1.1.4 I do it this way: A = Table1.sa B = Table2.sa my_query = A.query().join(B, literal(True)) But after updating to version 1.3 it's raise exception: sqlalchemy.exc.InvalidRequestError: Can't determine which FROM clause to join from, there are multiple FROMS which can join to this entity. Try adding an explicit ON clause to help resolve the ambiguity. I'm understand that it's mean that I have to do something like that: my_query = A.query().join(B, A.fireign_key_id = B.id) But table A haven't foreign key to table B. How to connect two tables with cross join and without foreign key? Thanks. -
Overriding get_context_data() is not working in child view
I am trying to override get_context_data() in a child class-based view to send more contextual data to the template, but it doesn't work. As a sample I am sending a test variable, but it is not rendered in the template. class ProductList(LoginRequiredMixin, View): template_name = 'product/product_scroll.html' def get(self, request, *args, **kwargs): #... return render(request, self.template_name, data) class Feed(ProductList): template_name = "product/feed.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['test'] = 'sometestinfo' return context But in the template: <p> Prueba: {{test}} </p> is empty. -
Django postgres query results getting different results for different database fields
I have 2 simple tables, in PostgreSQL Table 1 (which saves number in Varchar) class Numbers_char_model(models.Model): number = models.CharField(max_length=256, blank=True, null=True) Table 2 (which saves number in integer) class Numbers_int_model(models.Model): number = models.IntegerField(blank=True, null=True) Data in both tables are same id number 1 -> 0 2 -> 20 3 -> 40 4 -> 70 5 -> 110 6 -> 150 When i hit below queries both gives different results def number_query(request): ax_int = Numbers_int_model.objects.filter(number__lte='20') ax_char = Numbers_char_model.objects.filter(number__lte='20') ax_int output --> 0,20 ax_char output --> 0,20,110,150 can some one clear this -
Error when generate mobile_number in Django-seed
I tried to generate a fake phone number with Django-seed: def create_users(): """Creates user object""" logger.info("Creating users") seeder = Seed.seeder() seeder.add_entity(User, 4, { 'mobile_number': PhoneNumber.from_string("+41 79 123 45 67"), 'email': lambda x: seeder.fake.email(), 'is_superuser': False, 'is_staff': False, 'is_active': True, }) seeder.execute() I also tried this: 'mobile_number': "+43 79 123 XX XX" Whatever i try i got this error: File ".../python3.6/site-packages/django_seed/seeder.py", line 60, in guess_field_formatters formatter = field_type_guesser.guess_format(field) File ".../python3.6/site-packages/django_seed/guessers.py", line 107, in guess_format raise AttributeError(field) AttributeError: users.User.mobile_number Can anyone point out what I'm missing ? -
Get context data in Update View modal in Django
I have a template called Profile settings which contains multiple forms like Education CreateView, Education UpdateView and Education ListView. I'm using bootstrap modals to display these forms. Hence the they share same template. Education CreateView and ListView are working fine. Problem is whenever I want to update an education form, it loads the update form but does not display existing values in fields. Models class Profile(models.Model): phone = models.CharField(max_length=11, null=True, blank=True) education = models.ManyToManyField(Education, null=True, blank=True, related_name="education") full_name = models.CharField(max_length=30, null=True, blank=True) class Education(models.Model): degree = models.CharField(max_length=100, null=True, blank=True) school = models.CharField(max_length=100, null=True, blank=True) edu_start_date = models.DateField(null=True, blank=True) edu_end_date = models.DateField(null=True, blank=True) View class EducationUpdate(UpdateView): model = Education form_class = EducationForm pk_url_kwarg = 'pk' context_object_name = 'edu' template_name = "profile_settings.html" def get_success_url(self): return reverse_lazy('users:profile_settings', args = (self.request.user.profile.id,)) def get_object(self): pk = self.kwargs.get('pk') return get_object_or_404(Education, id=pk) def get_context_data(self, **kwargs): c_object = self.get_object() context = super(EducationUpdate, self).get_context_data(**kwargs) context['degree'] = c_object.degree context['school'] = c_object.school context['edu_start_date'] = c_object.edu_start_date context['edu_end_date'] = c_object.edu_end_date print('context: ', context) return context class ProfileSettingsView(UpdateView): model = Profile form_class = ProfileSettingsForm pk_url_kwarg = 'pk' context_object_name = 'object' template_name = 'profile_settings.html' def get_success_url(self): return reverse_lazy('users:profile_settings', args = (self.object.id,)) def get_object(self): pk = self.kwargs.get('pk') return get_object_or_404(Profile, id=pk) def get_context_data(self, **kwargs): context = super(ProfileSettingsView, …