Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calculate stock quantity
I have two models containing different types of transactions that i want to use as the base for calculation of quantities for my products, but I have a hard time making a query that works. class Transaction(models.Model): ... transaction_type = models.PositiveIntegerField(choices=TYPE_CHOICES, db_index=True) date = models.DateTimeField(auto_now_add=True, db_index=True) comment = models.CharField(max_length=255, blank=True, null=True) status = models.PositiveIntegerField(choices=STATUS_CHOICES, default=1, db_index=True) ... class TransactionItem(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) product = models.ForeignKey(product, on_delete=models.CASCADE related_name="product") stock_location = models.ForeignKey(warehouse_stock_locations, on_delete=models.CASCADE, verbose_name="Lagerplats", related_name="stock_location", blank=True, null=True) qty = models.IntegerField(default=0, blank=True, null=True) unit_cost = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) so I want to collect the quantities in all transactions that have the status "2", which is equal to a completed inventory count, goods delivery, while status=1 and status=3 are ignored. I'll then sum all qty in TransactionItems and display on the respective product detail pages. I've looked at various examples of queries, but they all lead me to an error. Could you point me in the right direction? -
Django admin: How to pass django model objects from js?
I have a model "Bank" in models.py class Bank(models.Model): # bank_id = models.AutoField(name='ID', primary_key=True) name = models.CharField(max_length=50) def __str__(self): return self.name I have registered the same in admin.py @admin.register(Bank) class BankAdmin(admin.ModelAdmin): search_fields = ['name'] class Media: js = ('js/custom_script.js',) I want to pass the bank DB objects to 'custom_script.js' Is there a way to do that? -
Django creating new object when url is being entered
I have a django post here def post(self, *args, **kwargs): self.object = self.get_queryset() approve_or_reject = self.request.POST.get('approve', None) book_pk = self.request.POST.get('data_pk', None) loan = self.request.POST.get('mark_loan', None) cancel = self.request.POST.get('mark_cancel', None) reserve_book = self.model.objects.filter( pk=book_pk, recipient=self.get_object(), ) if loan == 'loan': titles = Title.objects.get(pk=book_pk) for title in titles.titlecopy_set.filter(in_rental=False): for status in title.title.reservedbooks_set.filter(recipient=self.get_object()): status.mark_loan = False status.save() break title.rental_set.create( recipient=self.get_object(), borrowed_on=timezone.now(), librarian=self.request.user.manager, ) title.in_rental = True title.save() break This is working when I am saving a Reserve Book however after that when Im refreshing the url(not the f5) it creates another one. Any idea what went wrong here? thanks -
How to create a serializer for wizard view
I am facing creating an API.... In web we are used django vizard view .... At the final submission only the data need to store in the web ... Here is a sample model : class Users(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) job = models.CharField(max_length=255, blank=True) age = models.CharField(max_length=255, blank=True) facorite_pet = models.ForeignKey( "PetDetails", on_delete=models.SET_NULL, blank=True, null=True) class PetDetails(models.Model): user = models.ForeignKey( Users, on_delete=models.CASCADE, blank=True, null=True) pet_name = models.CharField(max_length=255, blank=True) pet_color = models.CharField(max_length=255, blank=True) pet_category = models.CharField(max_length=255, blank=True) I need to save both users and PetDetails in a single post method For example if a person filling the forms first he need to enter his perosnal details and then he need to enter the pet details . At a time a persons can add multiple pets ... For a person James having two pets one is cat and another is dog .... So in Pet Details we have two objects one for cat and one for dog .... So how to create and save it in a single post method in drf -
Importing Module in django
the module importing in celery.py from celery import Celery the module importing in redis.py from redis import StrictRedis what's my problem? Django allow the file name the same with the third-party package name. How the django to import the modules that name is the same with the file name. If I do that without django, the program will be broken down and the error "The module cannot import name Celery was not found" will be raise. -
How to reverse serializers like models in ForeignKey?
In models: class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True, related_name='product') class SubCategory(models.Model): sub_category_name = models.CharField(max_length=50) sub_category_img = models.ImageField(upload_to='sub_category_img') In serializers: class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ['url', 'id', 'name', 'price', 'sub_category'] class SubCategorySerializer(serializers.HyperlinkedModelSerializer): product = ProductSerializer(many=True) class Meta: model = SubCategory fields = ['url', 'id', 'sub_category_name', 'sub_category_img', 'product'] Using models, I can get access to Products.sub_category for a single queryset and also SubCategory.product reverse query using related_name in ForeignKey. Using serializers, I can get access the ProductSerializer queryset using SubCategorySerializer but can't access SubCategorySerializer from ProductSerializer. I only get the url for sub_category when use ProductSerializer. How can i reverse both in api endpoints? I tried, in serializers, class ProductSerializer(serializers.HyperlinkedModelSerializer): sub = SubCategorySerializer() class Meta: model = Product fields = ['url', 'id', 'name', 'price', 'sub_category', 'sub'] class SubCategorySerializer(serializers.HyperlinkedModelSerializer): product = ProductSerializer(many=True) class Meta: model = SubCategory fields = ['url', 'id', 'sub_category_name', 'sub_category_img', 'product'] It's not working. How can I get both queryset like models? -
Statring a new Django web project on repl.it
I recently found repl.it as an online python ide but I am having a problem with creating a new Django web project. This platform is very easy and featureful but for Django, it only has a ready to use template that does not work. Is there any resource out there to learn from? The repl.it website and its forum are not helpful at all. -
How can I obtain just one JSON object with the three models information combined?
How can I pass the foreign key values from my model to my serialised json object? Now I have this three models, class Fleet(models.Model): fleet_id = models.IntegerField('Id flota', primary_key=True, unique=True) fleet_name = models.CharField('Nombre flota', max_length=20, unique=True) def __str__(self): return self.fleet_name + ' ' + str(self.fleet_id) class Device(models.Model): dev_eui = models.CharField(max_length=16, primary_key=True, unique=True) producer = models.CharField(max_length=20) model = models.CharField(max_length=20) dev_name = models.CharField(max_length=20, unique=True) fleet_id = models.ForeignKey(Fleet, on_delete=models.CASCADE) def __str__(self): return self.dev_eui class DevData(models.Model): data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False) frequency = models.IntegerField() data_1 = models.FloatField() data_2 = models.FloatField(null=True, blank=True) dev_eui = models.ForeignKey(Device, on_delete=models.CASCADE) #hay que saber porque añade _id def __str__(self): return self.dev_eui And what I'm doing is call my view function in my JS code to obtain some data like this. def getData(request): ctx = {} if request.method == 'POST': select = int(request.POST['Select']) data = DevData.objects.order_by('dev_eui','-data_timestamp').distinct('dev_eui') nodes = Device.objects.all() fleets = Fleet.objects.all() data = loads(serializers.serialize('json', data)) nodes = loads(serializers.serialize('json', nodes)) fleets = loads(serializers.serialize('json', fleets)) ctx = {'Data':data, 'Nodes':nodes, 'Fleets':fleets} return JsonResponse(ctx) And inside my js file I filter it with some if else conditionals. This works well, but I'm sure I can do it directly in my view but I don't know how. How can I obtain just one JSON object … -
Show child nodes by parent id - Django application
In my application user schedules a meeting. He/she chooses date, and each date has fixed meeting hours like: 14:00, 15:00, 16:00, 17:00 and 18:00. These hours must be choosen from select box just after date selected. So, I want to fill select box with hours when date selected. But the problem is that I don't know with which technology should I do that: with Django, or AJAX. There are my codes: note: I can leave everything fixed, but if for example 14:00 at 03/02/2020 is selected by user, for others this hour at 03/02/2020 must be disabled. models.py: class MeetingHour(models.Model): hour = models.TimeField() def __str__(self): return str(self.hour) class Meeting(models.Model): participant_name = models.CharField(max_length=50) participant_email = models.EmailField(max_length=50) meeting_date = models.DateField() meeting_hour = models.ForeignKey(MeetingHour, on_delete = models.CASCADE) is_scheduled = models.BooleanField(default=False) def __str__(self): return self.participant_name views.py: def index(request): context = { 'meetings': Meeting.objects.all(), 'meetinghours': MeetingHour.objects.all() } if request.method == "POST": meeting_date = str(request.POST.get('date')) meeting_hour = str(request.POST.get('hour')) converted_meeting_date = datetime.strptime(request.POST.get('date'), "%m/%d/%Y").date() if meeting_date else None converted_meeting_hour = datetime.strptime(request.POST.get('hour'), "%H:%M:%S").time() if meeting_hour else None hour, _ = MeetingHour.objects.get_or_create(hour = converted_meeting_hour) Meeting.objects.create( meeting_date = converted_meeting_date, meeting_hour = hour, is_scheduled = True ) return render(request, 'index.html', context) html: <form method="POST" action={% url 'index' %}> <div class="form-group"> <label for="date">Date</label><br … -
How can i show and update users own data from a django app
i have a login system & registration system. when user reg himself the information is stored in admin. I want that when a user login into the app the user can change his details like username first name etc. Just like we do in instagram. Im new to the django and python please answer me anyone? -
PLY Maintaining State Between Requests (Django REST Framework)
I am using PLY to parse some user input, building up an SQL query as a string which will be returned to the user. The problem I am having is that the parser is maintaining state between requests, so the next user has their SQL query appended to the previous user's. I have worked around this by being careful to manually reset the string between requests, however I want to figure out how to stop state being maintained between requests? -
What is difference between objects.all().annotate and objects.annotate?
Currently I am practicing for annotate and have some confusion regarding below code. >>> b = Book.objects.all().annotate(upper_name = Upper('name')) >>> b[0].name 'Book1' >>> b[0].upper_name 'BOOK1' >>> ba = Book.objects.annotate(upper_name = Upper('name')) >>> ba[0] <Book: Book1> >>> ba[0].name 'Book1' >>> ba[0].upper_name 'BOOK1' I am getting same output when not using all() so what is difference between using Book.objects.all() and 'Book.objects.annotate()'. How doing annotate() on Book objects without all() provide all Book objects. I have read Django documentation but not able to find any answer. Thanks. -
i have list of product with filter function already, how to add pagination?
the function below has filter already. How to add pagination in django? def product_list_view(request): qs = Product.objects.all() title_query = request.GET.get('title') if title_query != '' and title_query is not None: qs =qs.filter(title__icontains = title_query) context = { 'queryset':qs, } return render(request, "products/product_list.html",context) -
How to generate unique serial number with alert message after each form submission on django?
on views.py i have used from django.contrib import messages messages.success(request, 'Form submitted successfully.') and on templates <div> {% if messages %} {% for message in messages%} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} </div> <div class="row"> {% block content %}{% endblock %} </div> its working fine but I actually want to generate unique serial number like SK(date)(year)(serial_number) of this format ,can you please help me with this? -
Serializer in django doesn't have any data
>>> user = User.objects.create_user(username = "testusername", password = "testpassword") >>> user_serializer = UserSerializer(user) >>> user_serializer UserSerializer(<User: testusername>): >>> user_serializer.is_valid() Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/user/Virtual Environments/project/lib/python3.6/site-packages/rest_framework/serializers.py", line 228, in is_valid 'Cannot call `.is_valid()` as no `data=` keyword argument was ' AssertionError: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance. >>> user_serializer.data {} The UserSerializer is: class UserSerializer(serializers.Serializer): def create(self, validated_data): return User.objects.create_user(**validated_data) def __str__(self): return f"Username: {self.data['username']} Password: {self.data['password']}" class Meta: model = User fields = ['username', 'password'] I don't understand what's going wrong. The user_serializer.data is empty. Any help would be appreciated -
Adding first_name, last_name fields to django "add user" user interface
Default "Add User" Interface In this interface I want to add first name and last name field. I know those fields are already present as optional fields in django.contrib.auth.models User model, but they don't show up in UI. Also to make those fields required, is it necessary to override existing User model? I am new to this and have a feeling that doing so would not be a good idea. All help is appreciated! -
unable to write test for django model containing custom model field
I have a model for users where in the field for password is a custom field. This model works fine but i'm not able to run tests for the model. my model from core_engine.CustomModelFields import * class Users(models.Model): username = models.EmailField(unique=True) name = models.CharField(max_length=100) password = EncryptedField(max_length=500) in my core_engine.CustomModelFields.py file from account_engine.crypto import * class EncryptedField(CharField): def from_db_value(self, value, expression, connection, context): value = Password.decrypt(str(value)) return value.decode("utf-8") def to_python(self, value): if not value: return None return value #Only need to decrypt if password already encrypted. try: if Password.encrypt(Password.decrypt(value)) == value: value = Password.decrypt(str(value)) return value.decode("utf-8") except: return value def get_db_prep_save(self, value, connection): value = Password.encrypt(str(value)) return value and finally in accounts_engine.crypto.py file i have import base64, hashlib from django.db import models from Crypto import Random from Crypto.Cipher import AES BS = 16 pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) unpad = lambda s : s[0:-s[-1]] class Password(models.Model): def encrypt( raw ): mysecretpassword = 'somepassword' KEY = hashlib.sha256(mysecretpassword.encode('utf-8')).digest() raw = pad(raw) iv = Random.new().read( AES.block_size ) cipher = AES.new( KEY, AES.MODE_CBC, iv ) return base64.b64encode( iv + cipher.encrypt( raw ) ) def decrypt( enc ): mysecretpassword = 'somepassword' KEY = … -
unauthorized_client: Grant type 'authorization_code' not allowed for the client. Django -auth0 -login
I'm developing an app with django and when I try to use auth0 for the login I get: "error": { "message": "Grant type 'authorization_code' not allowed for the client.", "oauthError": "unauthorized_client", "type": "oauth-authorization" } I have configured my public key and private key, the login url, and in auth0 i have configured the urls. Additionally I notest that the mistake might be when I'm asking the access_token because i'm getting a http 403 error when i'm accessing to the auth0.com/oauth/token. Meanwhile the server sends me this "GET /complete/auth0?redirect_state=y8oPFziJ01BmdGaRbsRJZod3GZ4dP0hW HTTP/1.1" 500 116725 -
how to sum elements of a models and return the total in a django template?
I'm new to Django and after spending a lot of time on this (and still being stuck) I thought to ask for some expert help! In this small project, what I'm trying to achieve is a webpage that returns the total amount in GBP of a user's investments (only cash investments for now). I have created some python scripts to get the FX rates. I'm trying to sum up all the amounts in GBP however I'm stuck! I don't know whether I should do this in the model (Cash) or in the view and how to then show it in the template(cash_list.html). Your help would be really appreciated. Workings below models.py from django.db import models class fx_table(models.Model): eur_to_gbp_pair = 'EUR/GBP' aud_to_gbp_pair = 'AUD/GBP' usd_to_gbp_pair = 'AUD/USD' eur_to_gbp = models.FloatField(default=0) aud_to_gbp = models.FloatField(default=0) usd_to_gbp = models.FloatField(default=0) date_time = models.CharField(max_length=264,unique=True,default='') class Cash(models.Model): reference = models.CharField(max_length=128) amount = models.FloatField(default=0) currency = models.CharField(max_length=128) forms.py from django import forms from fx_rates_app.models import Cash from fx_rates_app.models import Shares class NewUserFormCash(forms.ModelForm): class Meta(): model = Cash fields = '__all__' #You want to be able to change all the fields class NewUserFormShares(forms.ModelForm): class Meta(): model = Shares fields = '__all__' Python script import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','fx_rates_project.settings') import django django.setup() … -
Student Seeking Programming Advice
I am a high school student, and I have just finished 4 free youtube courses on python, along with a "beginners guide to python" book, and I am a little lost. I understood the language quite well and enjoyed learning it. My question is: what do I have to learn in order for me to start designing and building things with python. Just to be clear, I am not talking about complicated things such as websites or machine learning applications. I am talking about simple games and apps so that I can form a better understanding of software development through practical experience. I honestly thought this is where the course and book would get me by now. I feel like my understanding of python is great (for a beginner). I understand all of the fundamental terms and definitions of the language, and I can answer questions other students may have about directories, methods, strings and so on without trouble. I just have no idea where to begin designing and building real things that can test my knowledge as a programmer. I understand that I have a lot to learn. I just have no discernible vision as to how I can … -
Django Rest Framework: How to send data to request.data
Im building a simple api in Django Rest Framework using class based views and the documentation mentions request.data (https://www.django-rest-framework.org/tutorial/2-requests-and-responses/) from rest_framework.views import APIView class myView(APIView): def post(self, request): print(request.data) When I try to send post requests either with curl: curl --data param1=val1&param2=val2 url djangos browser interface with post (using formatted url and the post option Advanced Rest Client (chrome add on) The data of all three appears to end up in request.query_params. When I try to print request.data, however I get an empty response {} I could just use request.query_params, Im just curious as to how one would get data to go to request.data since it is talked about in the documentation -
UnboundLocalError at /cart/slug/ local variable 'product' referenced before assignment
I am trying to use a link to add items to a cart but it keeps saying that I am referencing the variable before it assigned. views.py: def view(request): cart = Cart.objects.all()[0] products = Product2.objects.all() context = { "cart": cart, "products": products } template = "cart/view.html" return render(request, template, context) def update_cart(request, slug): cart = Cart.objects.all()[0] try: product = Product2.objects.get(slug = slug) except Product2.DoesNotExist: pass except: pass if not product in cart.products.all(): cart.products.add(product) else: cart.products.remove(product) return HttpResponseRedirect(reverse("cart")) models.py: class Product2(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() slug = models.SlugField() def __str__(self): return self.name html: {% for product in products %} <div> <h1>{{ product.name }}: ${{ product.price }}<a href='{% url "update_cart" product.slug %}' class ='pull-right'>Add to Cart</a></h1> </div> {% endfor %} I had it working for a second but I created a new table in the database, changed the name where applicable, and now it doesn't work. -
Am having troubles with django-parler after i had applied migration to translations, it won't show Products fields in admin site
this is my setting for translations in the models.py file, django-parler won't show fields for Products in the admin site after I had synch migrations. from django.db import models from django.urls import reverse from parler.models import TranslatableModel, TranslatedFields class Category(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200, db_index=True), slug = models.SlugField(max_length=200, db_index=True, unique=True) ) class Meta: # ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) class Product(TranslatableModel): translations = TranslatedFields( name = models.CharField(max_length=200, db_index=True), slug = models.SlugField(max_length=200, db_index=True), description = models.TextField(blank=True) ) category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) #class Meta: # ordering = ('name',) # index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) I have registered the model in the admin.py file but it won't show the fields for products all I get is the translations fields. from django.contrib import admin from .models import Category, Product from parler.admin import TranslatableAdmin @admin.register(Category) class CategoryAdmin(TranslatableAdmin): list_display = ['name', 'slug'] def get_prepopulated_fields(self, request, obj=None): return {'slug': ('name',)} @admin.register(Product) class ProductAdmin(TranslatableAdmin): list_display = ['name', 'slug', 'price', 'available', 'created', 'updated'] list_filter = ['available', 'created', … -
Cannot override custom field __init__ and make migrations, throws error
I was attempting to create a custom model field and use it in a model as the docs demonstrate for BetterCharField shown here (you might have to scroll a bit down): https://docs.djangoproject.com/en/3.0/howto/custom-model-fields/#custom-database-types My code in my models.py is as follows, almost verbatim from the docs example: from django.db import models # Create your models here. class BetterCharField(models.Field): def __init__(self, max_length, *args, **kwargs): self.max_length = max_length super().__init__(*args, **kwargs) def db_type(self, connection): return "char({})".format(self.max_length) class MyModel(models.Model): my_field = BetterCharField(25) However, when trying to run python manage.py makemigrations with this models.py file, I get the following error every time: Traceback (most recent call last): File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/db/migrations/state.py", line 413, in from_model fields.append((name, field.clone())) File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 512, in clone return self.__class__(*args, **kwargs) TypeError: __init__() missing 1 required positional argument: 'max_length' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/dark_knight/test/venv/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 142, … -
Python - DRF returns number of rows but not the data or structure
i'm new in Python and Django programming and i have this issue with a test API that i'm doing for learning purposes. My problem is that when i make a get request to my API i got the following response: [ {}, {} ] The directory hierarchy of my app is this (as you can see, i've created a module for my django Models) ── __init__.py ├── __pycache__ ├── adapters.py ├── admin.py ├── apps.py ├── managers.py ├── migrations ├── models │ ├── __init__.py │ ├── car.py ├── serializers.py ├── tests.py ├── urls.py └── views.py so, in models/init i have: from .car import * in models/car.py: class Size(models.Model): description = models.CharField(max_length=200, null=True, blank=True) height = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) width = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) in serializers.py: class SizeSerializer(serializers.Serializer): class Meta: model = Size fields = ['description'] in views.py: class SizeList(APIView): def get(self, request, format=None): size = Size.objects.all() serializer = SizeSerializer(size, many=True) return Response(serializer.data) In my db table i have 2 records and the app is returning 2 empty objects, i assume that the connection to my db is working ok because when i had just one, the API was returning just 1 empty object. What can be causing this? I …