Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How could I work with Django simultaneously with my friends?
I need your help with Django. How can I work in team in Django? And what instruments I will have to have? -
how can I translate content by calling a locale file in template?
so I'm trying to translate the content of a website using locale files based on the language chosen by the user from a drop-down menu but I can't figure out how to call a locale file or translate in templates. I mean in views we write translation.activate(lang) but how to do it in html templates? I want something as: if($("#select").val('spanish')){ get_local_file.name("es") } <div class="language"> <p id="lang">Languages:</p> <select id="select"> <option value="english">English</option> <option value="spanish">Spanish</option> <option value="arabic">Arabic</option> </select> </div> -
Django-filter and restframework pagination infinitely appends query
I have a viewset with settings looking like below class JobPostViewSet(viewsets.ModelViewSet): ... filter_backends = (DjangoFilterBackend,) filterset_class = filters.JobPostFilter pagination_class = DefaultCursorPagination My filter is as below class JobPostFilter(FilterSet): class Meta: model = models.JobPost fields = { 'company__type': [ 'in' ], 'approval_status': [ 'exact' ], 'sex': [ 'in' ], 'education': [ 'in' ], 'business_strategy': [ 'in', ], 'base_salary': [ 'in' ], 'settlement_support': [ 'in' ], 'scout_royalty': [ 'in' ], 'mortgage': [ 'in' ], 'db_availability': [ 'in' ], 'experience': [ 'in' ] } When I send a pagination request to http://localhost/api/paginate?approval_status=true I get additional ?approval_status=true appended to the URL every time I paginate. For example nextLink value from first pagination from django returns http://localhost/api/paginate?approval_status=true&approval_status=true&cursor=xxx. The next pagination returns http://localhost/api/paginate?approval_status=true&approval_status=true&approval_status=true&cursor=xxx and so on, infinitely adding existing query parameters. How do I make sure that query params don't get duplicated? -
Send element id from div to javascript file
I am trying to trigger a file input using javascript. I am using Django formset and I have obtained the id of the input fields current my Javascript functions looks like: $(document).ready(function(){ $("#show-image-upload-inputs").click(function(){ $("#image-upload-div").toggle(); }); function open_input (id,input_id) { $(this.id).on("click", function () { $(this.input_id).trigger("click"); }); } }); And in my HTML I am passing them to the function, using onclick: <div id="file-0-selector" class="add-image" onclick="open_input(this.id,document.getElementById('id_form-0-image'))"><i class="mt-2 fas fa-plus fa-5x"></i></div> However, when I click on it I do not see the upload box opening, I was wondering how I can achieve this. I have acquired the image input fields form my formset and the id seems to be correct. Thanks in advance. -
Error of "Command 'pip' not found" when trying to install requirements.txt
I'm trying to do: pip install -r requirements.txt on an AWS server. I recently pulled a git commit. I get this error: Command 'pip' not found, but can be installed with: sudo apt install python-pip So I tried entering: sudo apt install python-pip install -r requirements.txt and then sudo apt install python-pip -r requirements.txt But both attempts gave me this error: E: Command line option 'r' [from -r] is not understood in combination with the other options. What is the correct command to install this? Thank you. -
How to set cursor nextLink domain correctly in Django app behind nginx
I have nginx config as below location /api { rewrite /api/(.*) /$1 break; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://rest; proxy_redirect off; } it's trimming out the /api/ part of the url to send to django app. The initial request works fine; however, the nextLink sent from django app pagination does not include the /api/ part. So for example if I send the first request to http://localhost/api/paginate django should send http://localhost/api/paginate?cursor=xxx under nextLink but I get http://localhost/paginate?cursor=xxx instead. How do I overcome this problem at the nginx level?