Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to co-exist STATICFILES_FINDERS and STATIC_URL
I would use django on apache with this setting. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") in apache setting Alias /static/ /var/www/html/jrtweet/current/static/ However I installed django-compressor, so adding,this setting. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', ) However after adding this, browser can't access /static/ directory. I need to do some setting for co-exist STATICFILES_FINDERS and STATIC_URL setting?? -
Can anyone tell about how can I fix this error in django , AttributeError: module 'BRMapp.models' has no attribute 'objects'
BRMapp is project name. please see the code in below image : https://i.stack.imgur.com/v0gG0.jpg In cmd , showing error: books = models.objects.all() AttributeError: module 'BRMapp.models' has no attribute 'objects' Myrest of the code is absolutely correct.Please tell how can I correct this AttributeError.. -
Can I programmatically change in django crispy forms the StrictButton part of the helper?
I see this documentation: https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html?highlight=change%20helper%20in%20view#manipulating-a-helper-in-a-view and https://django-crispy-forms.readthedocs.io/en/latest/dynamic_layouts.html I'd like to change the button description in the view: form.py class GenericButtonForm(forms.Form): def __init__(self, *args, **kwargs): super(GenericButtonForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' #self.helper.form_action = 'catalog:ave-properties' self.helper.form_class = 'form-inline' self.helper.field_template = 'bootstrap4/layout/inline_field.html' self.helper.layout = Layout( StrictButton('I'd like to change this', type='submit', id='button-down-spinner', css_class='btn-info'), ) views.py @login_required def CheckAveView(request): template_name='catalog/check_AVE.html' if request.method == 'POST': GenericButtonForm_inst = GenericButtonForm() GenericButtonForm_inst.helper.form_action = reverse('catalog:ave-properties') # Can I change the butto descriprion? 'I'd like to change this' ave_props = check_AVE_query_json(sess) else: ave_props = '' GenericButtonForm_inst = GenericButtonForm() context = { 'GenericButtonForm_inst': GenericButtonForm_inst, 'ave_props': ave_props, } return render(request, template_name, context=context) Can I manipulate in the view the button description?: self.helper.layout = Layout( StrictButton('I'd like to change this', type='submit', id='button-down-spinner', css_class='btn-info'), Thanks, Luca -
Trouble in accessing the field value of Foreign Key in Django
class State(models.Model): name = models.CharField(max_length=30) slug = models.SlugField(allow_unicode=True, unique=True, editable=False) def __str__(self): return str(self.name) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) class Location(models.Model): place_name = models.CharField(max_length=256, primary_key=True) latitude = models.DecimalField(max_digits=19, decimal_places=16) longitude = models.DecimalField(max_digits=19, decimal_places=16) state = models.ForeignKey(State, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.place_name) class Case(models.Model): user = models.ForeignKey(User, related_name = 'Case', on_delete=models.CASCADE, null=True, blank=True) address = models.ForeignKey(Location, null = True, blank=True, on_delete=models.CASCADE, related_name='Case_Place') case_type = models.BooleanField(default=False) # True is Positive or False is Negative. def __str__(self): if self.case_type == True: return str(self.address) + "- Positive" else: return str(self.address) + "- Suspect" def get_absolute_url(self): return reverse('case:all') class Meta: ordering = ['-case_type'] I want to make get state, total(case_type), case_type group by state from Case. And when user clicks any state the following address, total(case_type), case_type group by address from Case is displayed. -
django apache integration missing module
I'm trying to setup my first Django project and I have some issues with the Apache integration. Here my file tree venv-django aci_project/ |_manage.py |_aci_project/ | |_ init.py | |settings.py | | urls.py | |_ asgi.py | |_ wsgi.py | |_aci_api/ |_ init.py |_aci_script |_admin.py |_apps.py |migrations/ | | init.py |_static --> css |_templates --> template html |_tests.py |_urls.py |_views.py Basically, the flow is the following: Browser --> aci_project --> urls.py --> aci_api --> views.py --> call scripts in aci_script If I run the command "python manage.py runserver" it's working fine. Now I'm trying to integrate my Django project with Apache but it's not working. This is my vhost file in Apache: <VirtualHost *:8000> ErrorLog /var/log/httpd/error_log CustomLog /var/log/httpd/access_log combine <Directory /var/opt/aci_project/aci_project/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIApplicationGroup aciweb01t.stluc.ucl.ac.be WSGIDaemonProcess aciweb01t.stluc.ucl.ac.be group=www-data python-path=/var/opt/aci_project WSGIProcessGroup aciweb01t.stluc.ucl.ac.be WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/opt/aci_project/aci_project/wsgi.py </VirtualHost> here my wsgi.py file in aci_project --> manage.py --> _aci_project import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aci_project.settings') application = get_wsgi_application() And this is the error I have in the apache logs: [Wed Apr 22 16:49:12.468252 2020] [wsgi:error] [pid 7818:tid 140205314995968] [remote 10.195.113.74:28031] mod_wsgi (pid=7818): Failed to exec Python script file '/var/opt/aci_project/aci_project/wsgi.py'. [Wed Apr 22 16:49:12.468453 2020] [wsgi:error] … -
Vue.js and django rest framework for implements a cascading dropdown list
I would need help building a request to my backend API. I currently have a form with a drop down list. The data in this list comes from this.$Http.get('/ quality/api/affaires/') Below this drop-down list, I have another list. This list, I would like it to be empty until the 1st is not selected, then it is implemented with data according to the selection above. Backend side (Django) I have 2 models which are "Affaires" and "AffairesOfs". I used Serialize and I can therefore request each of these models via api/affaires and api/affairesofs In the "AffairesOfs" model I have a foreignekey (idaffaire) on the id of the "Affaires" model. Finally, I would like my second list to be made up of all the “affairesofs” linked to the “Affaires” selected. For now, I have my 2 drop-down lists but I can't find a way to link the second to the first. I tried different methods found on the internet (with the use of v-model, ...) but could not achieve a result. I can't even get the value selected from the first list to display it in the console, or in a . i think I need a change event on the first … -
Unable to used Django-Filter in python 3.6 returns ImportError: cannot import name 'six'
I am new to Django framework and I am encountering an issue when I'm using Django-filter and enter it in INSTALLED_APPS it returns the following error: File "Programs\Python\Python36\lib\site-packages\django_filters\__init__.py", line 7, in <module> from .filterset import FilterSet File "Programs\Python\Python36\lib\site-packages\django_filters\filterset.py", line 10, in <module> from django.utils import six ImportError: cannot import name 'six' I am currently trying to solve the issue but still to no avail . Any help will be greatly appreciated. Thank you -
Form for updating model info is blank
I am trying to provide a form to update user info such as employment, location, birthday, interests. The form I tried to make will not show any of this info however, it just shows a submit button. user_info = models.UserInfo.objects.get(user=request.user) if request.method == 'POST': form = UserChangeForm(data=request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('login:login_view') else: form = UserChangeForm(instance=request.user) context = { 'user_info' : user_info, 'form ' : form } return render(request, 'account.djhtml',context) I'm pretty sure I need to use user_info but Im not to sure how to do that. If anyone can point me in the right direction i'd greatly appreciate it. Thanks <form method="post"action="{% url 'social:account_view' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> The djhtml I tried -
How to import pickled python object into Django view.py file
This file runs perfectly well on its own: import pickle with open('model.obj', 'rb') as f: model = pickle.load(f) print(len(model)) But what I really want to do is to use model, which is a very large stored python dictionary, in my Django views.py file, like so: from django.shortcuts import render from modeler.load_model import model def page(request): return render(request, 'page.html', {'model':model}) However, when I try this, I get the error below: File "C:\Users\mmm\PycharmProjects\MyProject\modeler\load_model.py", line 3, in <module> with open('model.obj', 'rb') as f: FileNotFoundError: [Errno 2] No such file or directory: 'model.obj' I don't understand why, because if I run the first file directly it works fine - the only extra step here is importing it into views.py (I tried including the entire load_model.py code within views.py at first, but got this error, so then tried it in this separate file and it worked on its own, so obviously the issue is that I don't know how to correctly load/import my python model objects or files within Django. -
How to dynamically route to a URL with ID of an element fetched using JQuery on Django
I am populating data(Customer order in my case) from database into a table using Django template tags. I have assigned the unique ID( order.id) to the id of "a" tag. On click of this "a" tag, I have written a function which fetches the id of the clicked button and then opens a modal dialog. Now I need the modal body to show the order.name dynamically and then give the user two options - 1. 'No', which closes the modal 2. 'Yes', which should route to views along with the id fetched. I am stuck here. html <div class = 'col-md-7'> <h4>ORDERS</h4> <hr> <div class = 'card card-body'> <a class = 'btn btn-primary text-white' href = "{% url 'createOrder' %}">Create Order</a> <table class = 'table table-sm'> <tr> <th>Product</th> <th>Date Ordered</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {% for order in orders %} <tr> <td>{{order.Product.name}}</td> <td>{{order.created_on}}</td> <td>{{order.status}}</td> <td><a href = "{% url 'updateOrder' order.id %}" style = "color: #005ce6;"><i class="fas fa-pen" style = "padding-left: 5mm;"></i></a></td> <td><a href = "#" class = 'delete' id = '{{order.id}}' style = "color: #b30000;"><i class="fas fa-times" style = "padding-left: 6mm;"></i></a></td> </tr> {% endfor %} </table> </div> </div> <script> $(".delete").click(function() { var id = this.id; $('#modelId').modal('show'); }); </script> <!-- … -
Automatically changing value in Django
Good evening! I am creating an app using Django to manage car rental service. I have a model Car, User and Order, which has a ForeignKey inheriting from Car. I created a form for allowing user creating an order. I want to automatically change the car status as 'Rented' (in Car model it is CharField with 3 choices). Can somebody help me to solve this problem? class Car(models.Model): STATUS = ( ('Dostępny', 'Dostępny'), ('Wypożyczony', 'Wypożyczony'), ('Inne', 'Inne'), ) marka = models.CharField(max_length=100) model = models.CharField(max_length=100) production_year = models.CharField(max_length=100) color = models.CharField(max_length=100) id_plate = models.CharField(max_length=100) status = models.CharField(max_length=100, choices=STATUS) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.marka + ' ' + self.model + ' (' + self.color + ')' class Order(models.Model): client = models.ForeignKey(Klient, on_delete=models.CASCADE) car = models.ForeignKey(Car, on_delete=models.CASCADE) date_ordered = models.DateField(default=datetime.now) date_return = models.DateField() date_added = models.DateTimeField(auto_now_add=True) That is my form: class OrderForm(ModelForm): class Meta: model = Order fields = ['client', 'car', 'date_ordered', 'date_return'] That's views.py: def createOrder(request): form = OrderForm() if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form': form} return render(request, 'namiejscu/order_form.html', context) -
Pagination in filtered detailview in Django?
def get_context_data(self, **kwargs): context = super(ProductCategoryView, self).get_context_data(**kwargs) #dropdown menu context['subs'] = ProductSubCategory.objects.filter(category=self.object) #sidebar menu sub_id = self.request.GET.get('sub_id') if sub_id: context['products'] = Product.objects.filter(category=sub_id) else: context['products'] = Product.objects.filter(category__in=context['subs']) return context I have this detailview. First two lines linked eachother and product items filtered by them too. I want to paginate the products only but not the dropdown and sidebar. Limit items with simple paginate_by * is possible? Or create listview with the same function? -
Django: how to edit 4 records at the same time in a table presentation?
I have a new Django project with specific constraints for displaying data to be edited? Until now, I had edit and update forms that 'works' for a specific record. I have a index.html form that display data of my model. Records are group by four records. What is expected, is: to display the same table in a edit/update form but with fields that can be modified have four records to edit prefilled with data of the four last line of the table Bras (based on date) When I valid modification, 4 new records are stored I do not really know how to do... models.py class Bras(SafeDeleteModel): """ A class to create a country site instance. """ _safedelete_policy = SOFT_DELETE_CASCADE bra_ide = models.AutoField(primary_key = True) pay_ide = models.ForeignKey(Pays, on_delete = models.CASCADE) # related country ran_st1 = models.IntegerField("Stratification variable 1", blank=True) ran_st2 = models.IntegerField("Stratification variable 2", blank=True) bra_00A_act = models.IntegerField("Arm A activated", default=0, null=True, blank=True) bra_00A_lib = models.CharField("Arm A label", max_length=50, null=True, blank=True) bra_00B_act = models.IntegerField("Arm B activated", default=0, null=True, blank=True) bra_00B_lib = models.CharField("Arm B label", max_length=50, null=True, blank=True) ... bra_log = models.CharField("User login", max_length = 50) bra_dat = models.DateTimeField("Date of settings") log = HistoricalRecords() index.html {% extends 'layouts/base.html' %} {% load … -
Django register url is falling in infinitive loop
So relevant part of urls.py: path('register/', views.register, name="register"), path('login/', views.login_user, name="login_user"), path('logout/', views.logout_user, name="logout_user"), Settings.py: LOGIN_URL="/auth/register/" HTML call: <p><a href="{% url 'auth:register' %}" class="btn btn-success">REGISTER»</a></p> But that url is returninh this: http://127.0.0.1:8000/auth/register/?next=/auth/register/%3Fnext%3D/auth/register/%253Fnext%253D/auth/register/%25253Fnext%25253D/auth/register/%2525253Fnext%2525253D/auth/register/%252525253Fnext%252525253D/auth/register/%25252525253Fnext%25252525253D/auth/register/%2525252525253Fnext%2525252525253D/auth/register/%252525252525253Fnext%252525252525253D/auth/register/%25252525252525253Fnext%25252525252525253D/auth/register/%2525252525252525253Fnext%2525252525252525253D/auth/register/%252525252525252525253Fnext%252525252525252525253D/auth/register/%25252525252525252525253Fnext%25252525252525252525253D/auth/register/%2525252525252525252525253Fnext%2525252525252525252525253D/auth/register/%252525252525252525252525253Fnext%252525252525252525252525253D/auth/register/%25252525252525252525252525253Fnext%25252525252525252525252525253D/auth/register/%2525252525252525252525252525253Fnext%2525252525252525252525252525253D/auth/register/%252525252525252525252525252525253Fnext%252525252525252525252525252525253D/auth/register/%25252525252525252525252525252525253Fnext%25252525252525252525252525252525253D/auth/register/%2525252525252525252525252525252525253Fnext%2525252525252525252525252525252525253D/auth/register/ What am I doing wrong? -
TypeError: 'BasePermissionMetaclass' object is not iterable
I got this problem when i was trying to do an authentication function.Anybody got solution? REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } -
Django system date time lapse
I am preparing a web project using django in python, but I have to make time lapse. If the current date is 22.04.2020, I want to get this date back and forth as I want. how can I do that. In short, how can I get the system date back and forth? -
Sphinx doesn't show docstring
is my first time using sphinx and I'm trying documenting a django project. I created a docs folder and launch the sphinx-quickstart commands. After that I've edited the conf.py adding: import os import sys import django sys.path.append(os.path.abspath('..')) os.environ['DJANGO_SETTINGS_MODULE'] = 'controller.settings' django.setup() Then I've created a modules folder where I've added all the modules of which I want the documentation. For example, the modules for the copycat app is: Copycat =============== Submodules ---------- Admin -------------------- .. automodule:: copycat.admin :members: :undoc-members: :show-inheritance: Apps ------------------- .. automodule:: copycat.apps :members: :undoc-members: :show-inheritance: Forms -------------------- .. automodule:: copycat.forms.py :members: :undoc-members: :show-inheritance: Models --------------------- .. automodule:: copycat.models :members: :undoc-members: :show-inheritance: urls ------------------- .. automodule:: copycat.urls :members: :undoc-members: :show-inheritance: Views -------------------- .. automodule:: copycat.views :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: copycat :members: :undoc-members: :show-inheritance: And, taking as an example the copycat forms file, I've added some docstring: class TransferRequestForm(forms.ModelForm): """ Docstring example """ class Meta: model = TransferRequest fields= ['view_count', 'time_span'] But when I create the documentation I get the right structure but I cannot see anywhere my docstring comment. What am I missing? -
django sites and showing id in admin editor
I'm using the Site module in django. In the admin interface, I see domain name and display name. I'd really like to see the primary key id, as well, however, since I specify the sites by SITE_ID. Now I could do this by editing ./venv/lib/python3.7/site-packages/django/contrib/sites/admin.py, but that's poor form in so many ways. I'd just add "id", thus: class SiteAdmin(admin.ModelAdmin): list_display = ('id', 'domain', 'name') search_fields = ('id', 'domain', 'name') I did the following in one of my models.py files, which helps in the shell but doesn't show up in admin: def site_name(self): return '{domain} ({id})'.format( domain=self.domain, id=self.id) Site.__str__ = site_name Any suggestion how to do this (or pointer on what I'm doing wrong that I think I want it)? -
Inject variables into Model Form CharField
Pretty quick question - Is it possible to inject variables into CharFields "initial" fields in Model forms on Django? I would like to pass the current year and some link the customer fills out in a previous form field (link) and have it populate the "message." subject = forms.CharField( widget=forms.TextInput(attrs={'placeholder': ('Subject')}), initial="Subject", required=False) link = forms.CharField() message = forms.CharField(widget=forms.Textarea, initial="Dear User, today is **datetime.now()** and here is **link**", required=False) -
How to run a python code on django containing script for opening webcam on browser
I want to run a python script on django. My python code is on hand detection, and I am not able to open webcam on web browser and take inputs from it. -
Django rest framework incorrect nested serialization
I started a new django rest framework project and bumped into an annoying problem. The nested serialization doesn't work as expected. Instead of serializing relationship models and returning serialized object it returns an extra "relationship" field in addition to defaul "attributes" json field. Here is my python 3.6 code: models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='User', null=True, blank=True) first_name = models.CharField('First name', max_length=50) last_name = models.CharField('Last name', max_length=50) phone_number = models.CharField('Phone number', max_length=15) activated = models.DateTimeField('Activated') def __str__(self): return f'<Profile {self.first_name.title()} {self.last_name.title()}>' serializers.py from rest_framework import serializers from .models import Profile from django.contrib.auth.models import User class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ('id', 'first_name', 'last_name', 'phone_number') class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('id', 'email', 'username', 'profile') views.py from rest_framework.views import APIView from rest_framework.response import Response from django.contrib.auth.models import User from .serializers import UserSerializer from .models import Profile class UserViews(APIView): def get(self, request, format=None): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) The answer I expect to get: { "data": [ { "type": "UserViews", "id": "1", "attributes": { "email": "", "username": "admin", "profile": { "id": 1, "first_name": "name1", "last_name": "name2", "phone_number": "+79999999999", } … -
post request and url not working on google app engine django project
I am hosting my blogging app on google app engine in a standard environment. the website deploys successfully. but when I try to go to any other URL like anirudhmalik.in to anirudhmalik/blog/list/ it shows me 500 server error on the server side I am using PostgreSQL instance and the logs message only show me the error projects/anirudhmalik-274008/logs/appengine.googleapis.com%2Frequest_log" but I couldn't get any hint from this message and none of the post requests isworking on the website and everything is working fine in a local server or my local machine you can check the website on anirudhmalik.in and you can also give suggestion is google app engine is good to host your Django project and other cheap college student type hosting service thankyou main.py from annyportfolio.wsgi import application app=application app.yaml file handlers:# This configures Google App Engine to serve the files in the app's static# directory.- - url: /static static_dir: static-storage/ # This handler routes all requests not caught above to your main app. It is# required when static routes are defined, but can be omitted (along with# the entire handlers section) when there are no static files defined. - url: /.* secure: always redirect_http_response_code: 301 script: auto env_variables: DJANGO_SETTINGS_MODULE: annyportfolio.settings … -
How to update templates automatically in Django?
Consider I am having a basic model like this: class Text(models.Model): msg = models.TextField() I'm rendering a template like: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> <h1>Messages<h2><br> {% for message in messages %} <a> {{forloop.counter}} - {{message}} <br> {% endfor %} </body> </html> With a corresponding views: from django.shortcuts import render from .models import Text def home(request): context = { "messages": Text.objects.all(), } return render(request, 'app/home.html', context) Assuming i am creating new objects of Text through admin page. If I save an object, I want to render it without refreshing the page. I don't have good knowledge on Javascript/jQuery/AJAX, but I'm aware that it is possible to acheive with the help of this. Can anyone guide me through on how to render the contents without refreshing the page? -
DRF how to filter user and product by Foreign key company?
How can I filter by Foreign key(company) to get Only those product which got same company and authorized user? I have these models: models: class User(AbstractBaseUser): first_name = models.CharField(max_length=254) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) class Product(models.Model): name = models.CharField(max_length=255) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) serializer class ProductSerializers(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' view class ProductViewSet(ModelViewSet): serializer_class = ProductSerializers queryset = Product.objects.all() permission_classes = [IsAuthenticated] -
How can I create a search box with drop down filter in Django or python
I just used Django Python about 1 month ago. Can anyone guide me just where can I learn this, Thank you