Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Select Function
I have 2 class views Account And Transaction What I want is whenever I click add transaction and enter the amount type as debit it should Account.Balance = Account.Balance - TransactionAmount and whenever amount type is credit it should Account.Balance = Account.Balance + TransactionAmount. My Template {% load static %} <!DOCTYPE html> <head> <meta charset="UTF-8"> <title>Order Management</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <div class="container"> <ol class="breadcrumb"> <li><a href="/home">Home</a></li> <li> &nbsp; / &nbsp; </li> <li class="active">Add Transaction </li> </ol> </div> {% block title %}{% endblock title %} {% block content %} {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} {% if submitted %} <p class="success"> Your message was submitted successfully. Thank you. </p> {% else %} <form action="" method="post"> <table> {{ form.as_table }} <tr> <td>&nbsp;</td> <td><input type="submit" value="Submit"></td> </tr> </table> {% csrf_token %} </form> {% endif %} {% endblock content %} Views def AddAccount(request, fk): if request.method == 'POST': form = AccountModelForm(request.POST) form.customer_id = 5 if form.is_valid(): cd = … -
Form adding new user missing 1 required positional argument in Django
I created a form to add a new user, but it throws an error _wrapped_view() missing 1 required positional argument: 'request'. This is the form: class NewEmployee(UserCreationForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'password1', 'password2', 'email', 'first_name', 'last_name') And this is my view: @login_required(login_url='./accounts/login/') def NewEmployee(request): if request.method == 'POST': form = NewEmployee(request.POST) if form.is_valid(): form.save() return redirect('backend') else: form = NewEmployee() return render(request, 'backend/new_employee.html', {'form': form}) -
Import Django settings from several files
There are lots of hints, why one cannot pull settings from multiple files easily, like so: import base import app1 import app2 import local neither of them sees the settings from the files before and cannot modify them. One solution is to import all the file in chain: local.py: import app2 app2.py: import app1 app1.py: import base It's clumsy. ==== Another solution was to merge all the files into a single one. I actually like this one. I would like to search multiple directories (OK, at least one) for *.py files, sort them by filename and import/merge them, so: base.py -> 000_base.py local.py -> zzz_local.py ensure that base is first, local is last, the order of the other ones do not matter. Is there some Django tool / framework / model, that implements this already or, at least, helps? Thanks -
How to redirect to a different page in Django when I receive an input from a barcode scanner?
The whole project is as follows: I'm trying to build a Django based web-app for my college library. This app when idle will be showing a slideshow of pictures on the screen. However when an input is received from the barcode scanner, it is supposed to redirect it to a different age containing information related to that barcode. I'm not able to figure out how to get an input from the scanner and only then redirect it to the page for 3 seconds containing the relevant information, after the interval, it should redirect back to the page containing the slideshow. -
I am having problem : loading static files in HTML code in a Django Project . As I know for a href link we use "{% static 'addressOfFile' %}"
'How to use django template language to load these images in data-zs-src attribute . if it was data-zs-src="images/b1.jpg" then it would be easy like data-zs-source="{% static 'images/b1.jpg' %}" . but I have double quatation inside single quatation . so it is not working . plz help me with right code -
How can I save cloned form elements as Json strings in Django forms?
I have a django project. In one of my forms, I have an attribute which its name is "count" and I have a combobox which its name is "type". I want to show the "type" combobox as many as the number entered in the "count" field. So I cloned the "type" combobox by using jquery clone() function. For ex; If I enter "5" to count field, my view saves only one of the value of combobox values. How can I send these combobox values as a Json string to backend view for saving in only one charField? Here is my jquery code: $(function(){ $("#id_form-0-baglama_sayi").on('change', function(){ var count = parseInt(this.value); for(var i = 0; i < count; i++){ $( "#id_form-0-baglama_sekil" ).clone().appendTo( "#div_id_form-0-baglama_sekil"); } }); }); Here is my view: if form.is_valid(): data_list = form.cleaned_data data_dict = data_list[0] label = list(data_dict.keys()) data = list(data_dict.values()) new_data = Data(author_id = user.id) for i in range(0, len(label)): setattr(new_data, label[i], data[i]) new_data.save() Thank you! -
Styles are missing in angular build while deploying Django
I was developed angular application and take build ng build --prod command before that, I added the "deployUrl": "/static/" inside the angular.json file. after that I copied dist folder files and paste it inside the django static folder. index.html files also changed based on the requirement, pages are working fine but "styles": [ "src/styles.scss", "node_modules/bootstrap/dist/css/bootstrap.min.css", "node_modules/font-awesome/css/font-awesome.css" ], this styles are missing. what can i do for this. any one help me. -
Setting up a dockerized python server on local machine gives Session data corrupted
I'm trying to set up a dockerized Python server named Bullet Train on my local machine: It has 3 components: A Postgres database A Python server A React frontend All of these 3 need to work together to get the server up and running, so this is the docker-compose file which sits at the top level of both the frontend and api-server: version: '3' services: db: image: postgres environment: POSTGRES_PASSWORD: password POSTGRES_DB: bullettrain ports: - "5432:5432" api: build: context: ./bullet-train-api dockerfile: docker/Dockerfile command: bash -c "pipenv run python manage.py migrate --noinput && pipenv run python manage.py collectstatic --noinput && pipenv run gunicorn --bind 0.0.0.0:8000 -w 3 app.wsgi && pipenv run python src/manage.py createsuperuser" environment: DJANGO_DB_NAME: bullettrain DJANGO_DB_USER: postgres DJANGO_DB_PASSWORD: password DJANGO_DB_PORT: 5432 DJANGO_ALLOWED_HOSTS: localhost ports: - "8000:8000" depends_on: - db links: - db:db frontend: build: context: ./bullet-train-frontend dockerfile: Dockerfile ports: - "8080:8080" This way, all the 3 components run in parallel. So far so good! Now to initialize it, I run the createsuperuser as stated here by following these steps: docker exec -it research_api_1 bash ## go to the context of the API server terminal run python manage.py createsuperuser ## run the createsuperuser command The command runs successfully and I … -
Django REST Framework pagination: Not found: GET /api/blog/list HTTP/1.1" 404 0
I am trying to implement simple pagination using Django rest frame work. But I am getting Status 404 Not Found in Postman. Custom urls.py included from base urls.py from django.urls import path from item.api.views import ( api_detail_item_view, api_create_item_view, ApiBlogListView ) app_name = 'item' urlpatterns = [ path('<slug_from_api_url>', api_detail_item_view, name="item_detail_api"), path('create_api/', api_create_item_view, name="item_create_api"), path('list', ApiBlogListView.as_view(), name="list"), ] serializers.py file: from rest_framework import serializers from item.models import ItemMaint class ItemMaintSerializer(serializers.ModelSerializer): class Meta: model = ItemMaint fields = ['name', 'itemDescription', 'active', 'slug'] views.py file: class ApiBlogListView(GenericAPIView): queryset = ItemMaint.objects.all() serializer_class = ItemMaintSerializer pagination_class = PageNumberPagination Settings.py file REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 1, } Thanks in advance. -
How to set a custom manager class parameter to required=False
I am writing an API to accept and save the user profile information. In total I want to accept 5 parameters from the user which are mentioned below. { "first_name":"", "last_name":"", "email":"", "password":"", "profile_picture":"" } Out of these 5 parameters first_name, last_name, email and password are mandatory and profile_picture is optional. In models.py I have mentioned profile_picture as an ImageField. models.py class Users(AbstractBaseUser, PermissionsMixin): """ This model is used to store user login credential and profile information. It's a custome user model but used for Django's default authentication. """ email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='profile_picture/', max_length=None, blank=True) is_active = models.BooleanField(default=True) # defining a custom user manager class for the custom user model. objects = managers.UserManager() # using email a unique identity for the user and it will also allow user to use email while logging in. USERNAME_FIELD = 'email' In serializers.py I have mentioned profile_picture as an ImageField with required=False. serializers.py class UserSerializer(serializers.Serializer): """ This is a serializer class to validate create user request object. """ class Meta: models = 'Users' email = serializers.EmailField(allow_blank=False) first_name = serializers.CharField(max_length=255, allow_blank=False) last_name = serializers.CharField(max_length=255, allow_blank=False) profile_picture = serializers.ImageField(max_length=None, allow_empty_file=True, use_url= False, required=False) … -
django environment pyhon manage.py runserver
trying to start a project with django. I downloaded django and virtualenv package and everything went well ( I followed the installing instructions ) but, when I trued ti run in the command line : python manage.py runserver it displays an error and says that django does not exist and something about PYHONPATH. does anybody know a wat to get it installed and start a project easily? some how no matter what I do nothing works. thanks -
AttributeError: type object 'Product' has no attribute 'Objects'
from django.db import models class Product(models.Model): CATEGORY = ( ('Indoor', 'Indoor'), ('Out Door', 'Out Door'), ) name =models.CharField(max_length=60) price =models.CharField(max_length=60) category =models.CharField(max_length=60, choices=CATEGORY) description =models.CharField(max_length=100) date_created =models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag) def __str__(self): return self.name from .models import * def products(request): products = Product.Objects.all() return render(request, 'Accounts/products.html', {'Products ': products}) -
how can i implement django oscar "categories" functionality(Parent, childs) in the Django oscar RESTFUL API?
In the oscar dashboard, I can make any root category, I can make children under a category. This functionality I am able to explore in the oscar Restful API. But I want to inherit the dashboard functionality, where we can make any category relative to another category. for example- I have 2 categories. 1) cat 1 a)subcat1 2)cat 2 now if I have to make subcat1 as a child of cat2 I can easily select from the dropdown and set 'subcat1' to cat2, in the oscar dashboard. But how can I do the same using Django oscar restful API? Please let me know. I have checked and found out that "category" model uses the Materialized Path trees, to achieve this functionality, how can I use this to achieve the treebeard functionality for adding the root nodes, adding children, and updating the categories under different categories etc? this is the request data I receive from the client side. { "id": 104, "url": "http://localhost:8000/api/admin/categories/104/", "breadcrumbs": "Cat1 > subcat1", "name": "subcat1", "description": "My new one test Desc", "slug": "subcat1", "parent": "Cat1", "children": "http://localhost:8000/api/admin/categories/Cat1/subcat1/", #here parent slug will be the name of parent category this category belongs to, if it is a parent category, … -
Django: Best way to extend auth_views.LoginView to do an extra check before allowing login to pass, only for login view
I've been trying to figure out the best way to add a single if statement to the baked in contrib.auth.LoginView from Django, to check if the login process should continue. I have in urls.py: from django.contrib.auth import views as auth_views urlpatterns = [ ... url(r'^login/$', auth_views.LoginView.as_view(), name='account_login'), ... ] My task at this point is to check whether a user can log in, by checking their license, using a function that receives a License model instance: def check_license(lic_obj): file_contents = lic_obj.decrypt_license() expiry_date = file_contents['expiry_date'] expiry_date = dateutil.parser.parse(expiry_date) time_now = utc.localize(datetime.datetime.utcnow()) if expiry_date < time_now: users = User.objects.all() for user in users: user.remove_all_sessions() # If license is invalid, redirect to License page return HttpResponseRedirect(reverse('get_license')) # Otherwise, keep going with login, not sure how to go about this either, # depends on how extending LoginView works pass For clarity, a license is just an encrypted bit of JSON with some license related properties, one of which is the license's expiration date. That whole part of the code works, I'm just not sure how to have that check_license() function be run on login, before returning whether the login is successful or not. I was toying with adding a custom middleware class, but that … -
request.user.id is null in ModelViewSet
getInstructor is my repository method, which gets instructor related with user id. @action(methods=['get'], detail=False) def instructor_detail(self, request): response_data = {} instructor = InstructorRepository.getInstructor(request.user.id) response_data["data"] = {"user_id": request.user.id, "detail": instructor.get("detail")} When I test that method with an id, it works. The problem is, request.user.id is always null, even there's no login problem related with JWT based auth. What should I check? -
How to check value getting none in modelserializer
I am having one issue I am having two serializers class PetSerializer(ModelSerializer): pet = AnimalSerilaizer (read_only = True) fields = ('id', 'pet') class Meta: model = Pet class AnimalSerializer(ModelSerializer): name = SerializerMethodField() color = SerializerMethodField() category = SerializerMethodField() photo = SerializerMethodField() class Meta: model = Animal fields = ('id', 'name', 'color', 'category', 'photo') def get_name(self, animal): return '{} {}'.format(animal.first_name, animal.last_name) def get_color(self, animal): return animal.color def get_category(self, animal): return animal.category def get_photo(self, animal): return animal.photo My Issue is When I am calling Pet Serializer if there is any object I am getting values..... If there is no objects I am getting none I need to change the response the "none" in string format . -
How to provide different pages to user accounts after login (Django Project)?
I am currently working on a django web app for an email broadcast service and was wondering how I would provide the different outboxes for the different users, so I can display which messages each user has sent in their outbox.I am working with an html template by Ra-themes. -
How to search for a field in django model which is present in another model
I have a model question , submissions , users submissions has many to many relationship with users and questions So basically submissions has the following fields: questions users time score is_solved When displaying questions to the user I am also displaying whether that particular question has been solved by the user or not. So, if is_solved is true I will display "solved" I am returning all questions to my html page as well as all the submissions user has made and I'm using a loop for question in questions // check if solved // display solved // else do nothing end for My question is how do I check for submissions.solved for each question in the loop -
How to aggreagte Django data model and render them in a table
My model contains a daily campaigns data. A campaign equal to an insertion_order(variable in the models) I would like to aggregate data from my mdel (like summing columns by insertion_order. from django.db import models class TabSource(models.Model): date=models.DateField() dsp=models.CharField(max_length=30) advertiser=models.CharField(max_length=100) insertion_order=models.CharField(max_length=300) insertion_order_id models.IntegerField() strategy_name=models.CharField(max_length=300) creative_name=models.CharField(max_length=400) spent_budget=models.DecimalField(null=True, max_digits=2) impressions=models.IntegerField() clics=models.IntegerField() conversions=models.IntegerField() post_clics_conversions=models.IntegerField() post_view_conversions=models.IntegerField() def __unicode__(self): return "{} {}".format(self.dsp, self.insertion_order) -
django shell freezes when running client.get(reverse)
So I was trying to learn django and going through the tutorials when something weird happened. On the testing views part of the tutorial, I was asked to run a client in shell and I tried it but at some point my console freezes. Here is the code I've been running on the console: PS D:\Users\rrocha\OneDrive\Documents\Material de Estudo\Django\mysite> python manage.py shell Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.test.utils import setup_test_environment >>> setup_test_environment() >>> from django.test import Client >>> client = Client() >>> response = client.get('/') Not Found: / >>> response.status_code 404 >>> from django.urls import reverse >>> response = client.get(reverse('polls:index')) The console stops responding when I run the last line. Does anyone have any idea of what I might be doing wrong? -
Gunicorn service fails to start
Gunicorn not starting Hi, I expect this is not the right subreddit for this unfortunately, but becuse it is a django application I've come here as a starting point. But for some reason, gunicorn service will not start on one of my servers. The gunicorn.service and the gunicorn.socket files are identical and in identical locations (I am building a staging server so it must be as close to the other one as possible, the other one is running fine). Can anyone see what might be the issue gunicorn.service: #!/bin/sh [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=pcc Group=nginx WorkingDirectory=/home/rob/myproject ExecStart=/home/rob/anaconda3/envs/django_env/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application [Install] WantedBy=multi-user.target gunicorn status: (django_env) [rob@pcc-home-page run]$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: disabled) Active: failed (Result: exit-code) since Wed 2020-03-11 12:45:25 UTC; 13s ago Process: 1466 ExecStart=/home/rob/anaconda3/envs/django_env/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application (code=exited, status=203/EXEC) Main PID: 1466 (code=exited, status=203/EXEC) Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: Started gunicorn daemon. Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: gunicorn.service: main process exited, code=exited, status=203/EXEC Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: Unit gunicorn.service entered failed state. Mar 11 12:45:25 pcc-home-page.novalocal systemd[1]: gunicorn.service failed. Some extra info: Server is running CentOS, Django is purely running … -
Django - check if two password hashes are of same raw password
I want to keep track of user password change history, and display a warning if their current password is used by them before. To note, I don't want to prevent a user from setting a password if it is used before, I want to let them set the password, but just display a warning afterwards. So what I'm looking for is NOT a password validator. I know that while Django saves user passwords in the db, it creates a hash of the password, using a random salt. So 2 hashes of the same password will not be the same. Still, is it possible to tell if 2 different password hashes are created with the same raw password as the input? -
Django template - iterate a list of tuples, each tuple is a string, dictionary
I have a dictionary that has been turned into a sorted list, which creates the below: monthly_spend_provider = sorted(monthly_spend_provider.items(), key=lambda item: item[1]['cost'], reverse=True) monthly_spend_provider [ ('PROVIDER A', {'cost': Decimal('10000'), 'symbol': '£'}), ('PROVIDER B', {'cost': Decimal('9000'), 'symbol': '$'}), ('PROVIDER C', {'cost': Decimal('8000'), 'symbol': '$'}), ('PROVIDER D', {'cost': Decimal('7000'), 'symbol': '£'}), ] now im trying to access the data in the tuples in a Django template thus far unsucessfully. I thought the below would of worked but it hasn't {% for provider in monthly_provider_country %} {% for data in provider %} <h3>{{ provider }} {{ data.symbol }} {{ data.cost|currency }}</h3> {% endfor %} {% endfor %} can I do this in a template or is there a way to turn the sorted list back into an easier format to output into a template? Thanks -
How to add model form field in the constructor?
I am trying to add a field in a ModelForm but only if a certain condition is met, which is passed through the constructor, so I can't just do: class MyForm(models.ModelForm): class Meta: model = MyModel fields = ['myfield'] I know I can manually add it like this: class MyForm(models.ModelForm): def __init__(self, condition, *args, **kwargs): if condition: self.fields['myfield'] = forms.CharField() But that would be missing attributes from the model definition (max_length, help_text, validators...), not to mention the actual initial and data values if the instance exists. PS: yes I'm on Django 1.8, don't ask why. -
Django Model validation based on a field value of another Model
I have this Django model: from accounts.models import Account class BankOperation(models.Model): created_at = models.DateTimeField(auto_now_add=True) account = models.ForeignKey(Account, on_delete=models.CASCADE) operation_import = models.FloatField(default=0.0) I want to make sure that the operation_import is not higher than account.balance what is the official way to this? I have seen some answers talking about overriding the save() method but others advise against it. should i add a pre-save signal and throw some kind of exception? Is there a way to create a field validator that accepts parameters? so maybe something like: def validate_bank_operation_import(value, account_balance): if value > account_balance: raise ValidationError("Bank operation import is higher than account balance!") and inside my model i change the field to: operation_import = models.FloatField(default=0.0, validators=[validate_bank_operation_import]) But can i pass parameters to a validator? if yes, how do I do it? perhaps there is another to do this validation!