Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to POST an entity specifiying an integer foreign key in django rest framework
I am building a chat application with django rest framework and I m currently working on messages. This are my models: from django.db import models from django.contrib.auth.models import User class Message(models.Model): text = models.CharField(max_length=500) datetime = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE); I am using the Django auth User model. This is my ModelViewSet for the messages: class MessageViewSet(ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer And these are my serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username'] class MessageSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Message fields = '__all__' And this is my API: The code I've written so far works really well for the GET functionally I want. I want for each message to get the username of the user it belongs to. But now I want the following thing: when I POST a new message, I want to me able to specify with user it belongs to by specifying the user's id. Right now I have only the "text" field in the POST section. I need to add a "user" field which takes in an integer (the user primary key) to specify which user the message belongs to. How should I refactor my code in … -
Override Djange ImageField extension validation
Understand I can add a validator to Django's ImageField validators to restrict file extension types like below. But in terms of the error messages which are displayed via upload on Admin -- I'm still seeing the standard file type list (via PIL allowed types), if I upload a non-image type. If I upload an image type which is not in my custom allowed_extensions below, I see my custom message. How can I override Django's default ImageField handling, and show my custom error message no matter what type of file is uploaded (e.g. when any file other than .png is uploaded per below example)? class MM(models.Model): file_extension_validator = FileExtensionValidator( allowed_extensions=['png'], message='File extension not allowed. Allowed extensions include .png' ) image = models.ImageField( help_text='Upload images only (.png).', validators=[file_extension_validator], max_length=255, blank=False, null=False ) -
Using Python, how can I add attributes to Say in a Gather?
I am saying some text in a Gather. I would like to change the speech rate and I see that I can do this with Prosody, but I don't know how to implement this in Python (Django). Here is something I tried that didn't work: resp = VoiceResponse() with resp.gather(input='DTMF Speech', action=my_url, method='GET', num_digits=1) as g: g.say('Hello', voice='Polly.Amy-Neural') g.say.prosody(rate='50%') return HttpResponse(str(resp), content_type='text/xml') -
Django: How to use handler500 to redirect to a frontend server page and also receive admin error email
My question is very similar to this one, except my problem is that my frontend page is in another server, an Angular application. Basically, what I need is to send a redirect response to my Angular frontend when user faces a 500 error, but also would like to receive admin e-mails with stack traces. This only happens when the response is a 500, not the 302 returned by the handler500 redirection. -
How to access a model's attribute from another model without a Forein Key in Django?
I have two models: class PiggyBank(models.Model): date=models.DateField(default=None) depositor=models.CharField(max_length=100) amount=models.DecimalField(max_digits=10, decimal_places=2, default=0) class Withdrawal(models.Model): date=models.DateField(default=None) particulars=models.CharField(max_length=200) amount=models.DecimalField(max_digits=10, decimal_places=2, default=0) balance=models.DecimalField(max_digits=10, decimal_places=2, default=0) voucher_number=models.IntegerField() I want to access the amount field of PiggyBank from Withdrawal to write a method to calculate balance. But these models are not connected through a Foreing Key. How can I do that? -
How should I be using Access-Control-Allow-Headers?
I'm building an backend in Django that accepts requests from other domains, so I'm using django-cors-headers to handle CORS. I'm hitting a snag with one of the outside domains hitting my backend, though, because their request code a) sets withCredentials and b) has some extra headers in the request. Both of these should be irrelevant to them being able to hit my backend, but I get the expected errors of Access-Control-Allow-Credentials' header in the response is '' which must be 'true' and Request header field [field_name] is not allowed by Access-Control-Allow-Headers in preflight response. Some other stackoverflow posts pointed me to Access-Control-Allow-Credentials = 'true' for the first, and Access-Control-Allow-Headers = '*' for the second, but I couldn't find much on what best practices are. What I'm trying to figure out is Is it safe to set both of these flags? There are other headers included in the request that handle authentication via tokens, so I'm not sure if there's much security risk here Should I instead tell my users that my backend disallows credentials and other headers (because they're not necessary to the code working)? The docs for Access-Control-Allow-Headers specify ‘The value “*” only counts as a special wildcard value … -
Browsing Server-Side SMB Mount with React and Django
I am developing a web application using a React frontend and a Django backend, and have run into the following engineering requirement: Users would like to, through the web app, browse files stored in a computing cluster (accessible via SSH and SMB) at my university. The frontend needs access to the directory system on the cluster in order for users to select files, and the backend needs access in order to read the contents of those files. I have successfully performed an SMB mount on my own machine (which I am running the server on during development), but am wondering how I might approach this integration with the front end. I ask that you bear with me if I am over-complicating or overlooking things; I am quite new to backend development. Thanks in advance. -
Elastic Beanstalk returns 502 Bad Gateway?
I have a web application which runs on AWS ElasticBeanstalk and once i'm access this view, it returns 502 Bad Gateway. def word_processor(request): sentence_freq_rank, kincaid_score, dict_file_path, doc_file_path = freq_rank_score.main() # sentence_freq_rank, kincaid_score, dict_file_path, doc_file_path = ( # 1, 2, 3, 4) return JsonResponse({'sentence_freq_rank': sentence_freq_rank, 'kincaid_score': kincaid_score, 'doc_file_path': doc_file_path, 'dict_file_path': dict_file_path}) And the freq_rank_score.main() def main(): text = "estamos reformando a nossa casa" dict_file = "word_frequency_portuguese_corpus.txt" doc_dir_name = "Inteligibilidade - Corpus - Âncoras - Nível 01 - Leitor iniciante" doc_file_name = "Âncora Alfabetização - 09 Fofão.docx" dict_dir_name = os.path.dirname(__file__) dict_file_path = os.path.join(dict_dir_name, dict_file) doc_file_path = os.path.join(doc_dir_name, doc_file_name) sent_req, flesch_kincaid_score=get_scores_from_doc(doc_file_path, dict_file_path) return sent_req, flesch_kincaid_score,dict_file_path,doc_file_path if __name__ == "__main__": main() this project work fine in local environment but after deploying it to EB it returns BadGateway, I think problem is freq_rank_score.main() but I don't know why ? And EB's log says this, [error] 661#661: *19614 upstream prematurely closed connection while reading response header from upstream, client: [ip], server: , request: "GET /webapp/wordprocess HTTP/1.1", upstream: "http://127.0.0.1:8000/webapp/wordprocess" Any idea what's wrong here ? -
Is there an easy way to only serialize non-empty fields with Django Rest Framework's ModelSerializer?
I am working on a Django project with a number of rather large models (around 80 fields). I am using Django Rest Framework's ModelSerializer to serialize the models, and ViewSets to provide an API for my frontend. That works very well, but I would like to reduce the amount of data that is being transferred by the server. Most of my model fields are optional and many instances only have values for a few of them. In those cases I would like to serialize only those fields that have values (i.e. that are truthy). I imagine I could do that either on the serializer side or on the model side, but I do not quite understand how these two talk to each other, so to speak. My current serializer is very simple: class OutfitSerializer(serializers.ModelSerializer): class Meta: model = Outfit fields = '__all__' The view is equally simple: # Outfit views class OutfitViewSet(viewsets.ViewSet): def list(self, request): queryset = Outfit.objects.all() serializer = OutfitSerializer(queryset, many=True) return Response(serializer.data) I fiddled with sub-classing the serializer and modifying the __init__ function (inspired by this part of the DRF docs): class NonEmptyFieldsModelSerializer(serializers.ModelSerializer): """ ModelSerializer that allows fields to be set at runtime via the optional 'fields' argument … -
Django template loop through API results to display in table
so I have some data being returned via API which I am passing into my template I am having an issue though in displaying the data as currently it is showing each char per row, I am trying to make it so in the table I have the coin name in a row with the value in the next col and so on. Data being returned- {"error":[],"result":{"ZGBP":"30622.0790","DASH":"0.5104491200","ADA":"2473.80445621","ZUSD":"67787.8285","KSM":"24.7142610000","CHZ":"13773.0349000000","XXLM":"6926.27220000","KNC":"0.0000000000","MATIC":"1838.9295772000","ZRX":"0.0000000000","BAL":"0.0000000000","XXDG":"17006.92601155","LINK":"144.2407000000","USDT":"60000.00000000","TRX":"923.80015900","COMP":"0.0000034600","ENJ":"257.6815000000","DOT":"0.0000000000","XLTC":"11.4923900000","SC":"0.0000000200","XZEC":"0.0000073100","SOL":"1133.3543869800","SUSHI":"172.4585500000","XXRP":"0.00000000","XETH":"14.5877343640","AAVE":"83.6218990800","ATOM":"151.26763831","XXBT":"0.0000012880","ALGO":"32063.69514500","OCEAN":"652.6077000000"}} My template- <table class="table table-hover table-bordered"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Amount</th> </tr> </thead> <tbody> {% for v in api_reply %} <tr> <td>{{ v }}</td> </tr> {% endfor %} </tbody> </table> -
Django REST API serializer.is_valid() always returns false
I'm trying to make a POST request from the frontend to the backend through REST API. I'm passing as data a dictionary which contains all the fields of the table from the database Data from frontend looks like this: var state = { event: { name: "test", id_organizer: 1, start_date: "2019-11-11T11:11:11", end_date: "2019-12-11T11:12:11", location: "test", description: "test", id_type: 1, status: "pending", } } and POST request like this: axios .post("http://127.0.0.1:8000/api/addevent", state.event) .then(response =>{ console.log(response.data); }) .catch(err => console.log(err)); Here is the model of the event: class Event(models.Model): name = models.TextField() id_organizer = models.ForeignKey(User, on_delete=CASCADE, db_column='id_organizer') start_date = models.DateTimeField() end_date = models.DateTimeField() location = models.TextField() description = models.TextField() id_type = models.ForeignKey(EventType, on_delete=CASCADE, db_column='id_type') status = models.CharField(max_length = 50) class Meta: db_table="events" Here is the database table Here is the @api_view: @api_view(['POST']) def addevent(request): if request.method == "POST": data = JSONParser().parse(request) serializer = EventSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({'saved':True},status=status.HTTP_201_CREATED) else: return Response({'saved':False}, status=status.HTTP_400_BAD_REQUEST) Here is the serializer: class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = '__all__' The request happens but the function serializer.is_valid() always returns false and the response is always {'saved':False} I already validated the data that it is sent correct and when I printed it, I got the output: … -
Get all sessions from memcached with Django
I'm using memcached to store my session. Is there a way to get all the session from memcached displayed? I'm looking for a way to manage the sessions and delete the sessions manually through some user interface -
Change form styling of django-filters from SelectMultiple to CheckboxInput¶
I feel that the documentation is quite unclear on this. I have the following filter logic on an attribute called categories of model ProductPage (works as intended): class ProductFilter(django_filters.FilterSet): class Meta: model = ProductPage fields = ['categories'] def product_list(request): f = ProductFilter(request.GET, queryset=ProductPage.objects.all()) return render(request, 'product/filter.html', {'filter': f}) Template looks like this: <form method="get"> {{ filter.form }} <div class="fieldWrapper"> {{ filter.form.name.errors }} {{ filter.form.name }} </div> <input type="submit" /> </form> I get the typically Multiple Select form which technically works well: Picture of form However, I would rather have a few checkboxes / radio buttons / something similar. Yet, I have no idea where to get access to the styling or type of widget. -
'widget_tweaks' to style the formset.empty_form
Does anyone know how I can use 'widget_tweaks' to style the formset.empty_form. Check the documentation however when applying it I get this error: the object 'PartForm' does not have attribute 'as_widget' I think i'm not doing well in html. I already used widget_forms on the same page and it looks good; but when implementing it in empty_forms it doesn't work presupuestos-forms.html <div class="form-row" id="empty-row"> {{formset.empty_form|add_class:"form-row" }} </div> -
How to Logout the App when Refresh the page ? In Django
This Is My code of login in Django Application from django.shortcuts import redirect, render from django.contrib.auth import authenticate,logout,login from django.contrib.auth.decorators import login_required from SedHelper.settings import LOGIN_URL from .models import HelperApps # Create your views here. def Login(request): if request.method == 'GET': if request.user.is_authenticated: logout(request) return render(request,'login.html') elif request.method == 'POST': username=request.POST['username'] password=request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect(home) else: error={ 'LoginSts':False, 'MSG':'You are not Logged In' } return render(request,'login.html',context=error) # No backend authenticated the credentials def logout_view(request): print(request.user.is_authenticated) if request.user.is_authenticated: logout(request) return redirect(Login) def home(request): #load all data from db(10) if request.user.is_authenticated: posts=HelperApps.objects.all()[:11] return render(request,'dashboard.html',{'posts':posts}) else:return redirect(Login) I just wanted to Logout when ever someone refresh the Page .In entire Application where ever someone refresh the the page it should logout immidiately.Anyone please. i am also new to stackoverflow Please try to ignore the mistakes. -
TypeError: __init__ missing 1 required positional argument: 'to', I get this error when I make migrations "python3 manage.py makemigrations"
Python 3.8.10, django version 3.2.9. When I am running the following code: "python3 manage.py makemigrations auth_app" ... I get this error: TypeError: init() missing 1 required positional argument: 'to'. I've checked out everything that says the error and still get the same.This is the whole error message. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/allfsr/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/allfsr/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/allfsr/.local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/allfsr/.local/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/allfsr/.local/lib/python3.8/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/allfsr/Documents/C4_WD/BANK/backend_auth/auth_app/models/__init__.py", line 1, in <module> from .account import Account File "/home/allfsr/Documents/C4_WD/BANK/backend_auth/auth_app/models/account.py", line 4, in <module> class Account(models.Model): File "/home/allfsr/Documents/C4_WD/BANK/backend_auth/auth_app/models/account.py", line 6, in Account user = models.ForeignKey(related_name='account', on_delete= models.CASCADE) TypeError: __init__() missing 1 required positional argument: 'to' -
django jQuery date picker wont change date format
I have a django form which as two date fields. I am trying to have a Calendar Pop-up with the default date being sent on click as ("yyyy-mm-dd"). I have tried this several ways, changed the setting in the javascript, changed the django settings file, but no matter what the form says invalid date and the date format that gets sent to the field always is mm/dd/yyyy. Here is an example of the code In the form I have: from django import forms from functools import partial DateInput = partial(forms.DateInput, {'class': 'datepicker'}) class SearchForm(forms.Form): start_date = forms.DateField(widget=DateInput(format = '%Y-%m-%d'), required=False, input_formats=['%Y-%m-%d']) end_date = forms.DateField(widget=DateInput(format = '%Y-%m-%d'), required=False, input_formats=['%Y-%m-%d']) My tempplate has the following: <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script> <script> $(document).ready(function() { $('.datepicker').datepicker() }); </script> <TR> <TD COLSPAN="3" ALIGN="Center"> Start Date:&nbsp;{{ form.start_date }}&nbsp;&nbsp; End Date:&nbsp;{{ form.end_date }} Date Format <B>MUST</B> be YYYY-MM-DD<br> Dates are inclusive.<br> If a date is left blank it is assumed to go until the start or end.</TD> </TR> I have tried putting dateFormat('yyyy-mm-dd') inside the datepicker code , as well as format('yyyy-mm-dd'), format('yy-mm-dd'). None of them changes the way to date is sent to the field, it's always "mm/dd/yyyy'. The form says this is not … -
I need to create an authentication for a distributor using jwt
I need to create an authentication for a distributor using jwt. However I'm only able to create the authentication token for the superuser. Could someone help me create a way to authenticate the distributor? Here are the models: class Distributors(TimeStampedModel): name = models.CharField("Nome completo", max_length=250) cpf = BRCPFField("CPF") email = models.EmailField("Email") password = models.CharField("Senha", max_length=15) def __str__(self): return self.name authentication needs to ask for name and password -
How to get data from amoCRM through API?
I am trying to get data through API from amoCRM system but I am having some problems and I am really tired. The url: https://alamiri.amocrm.ru/api/v4/contacts This API should return contacts of users that contain (first name, email, number, ...). When I copy and paste the above link in the browser, I get the data and everything works fine but when I try to get that data in Python it returns the following: {'detail': 'Invalid user name or password', 'status': 401, 'title': 'Unauthorized', 'type': 'https://httpstatus.es/401' } my code in python (Django framework): import requests import pprint def get_contacts(): url = "https://alamiri.amocrm.com/api/v4/contacts" api_key = "def50200c1f820b24e23a1a776cec978ed0e3eb3c479b83b91bef4158728d" client_uuid = "e1899afa-85a8-45ca-93f9-7f4b26374a5d" client_secret = "jUlw4E6H4jIW39GXXjpLjratAwOEiaqPr3KDBKYwc9ZQLXK2UlhMcsuu" headers = { 'login': login, 'client_uuid': client_uuid, 'client_id': client_uuid, 'client_secret': client_secret, 'grant_type': 'authorization_code', 'Authorization': f'Bearer {api_key}', } response = requests.get(url, headers=headers) pprint.pprint(response.json()) get_contacts() I am reading their documentation (amoCRM) and I tried a lot of things but none worked! 😥 https://www.amocrm.com/developers/content/platform/abilities/ I followed their instructions how to work with their API: https://nova-amocrm.notion.site/894277ffef5940e7a5daadd2abc746c8 But I am stuck and I don't know how to solve this problem! Any help please? If you don't know what is amoCRM, then -
Show ValidationError in the template - Django
I am developing a program that consists of sales. I want that when registering a sale, if there is not enough stock of the requested product, an error will appear indicating that there is no stock. I was able to do it but I get the ValidationError like this: ValidationError at /ventas/create/ ['No hay suficiente stock del producto.'] forms.py: class VentasForm(forms.ModelForm): """Formulario modelo de ventas.""" class Meta: """Meta class.""" model = Venta fields = ('fecha', 'cliente', 'producto', 'cantidad', 'forma_pago') def save(self): """Restar stock.""" data = super().clean() producto = Product.objects.get(id=data['producto'].pk) verificar_stock = producto.cantidad - float(data['cantidad']) if verificar_stock >= 0: producto.cantidad -= float(self.data['cantidad']) else: raise forms.ValidationError('No hay suficiente stock del producto.') producto.save() views.py: class CreateVentasView(CreateView): """Registrar venta.""" template_name = 'ventas/create.html' form_class = VentasForm success_url = reverse_lazy('ventas:list') context_object_name = 'venta' and in the template: {{ form.as_p }} -
Django Crispy Form loop through {% crispy %} object
I'm trying to use crispy form fields within each table's column. I can render it using: {% load crispy_forms_tags %} <tr> <form method="get" class="form-inline justify-content-center"> {% for field in filter.form %} <th>{{ field|as_crispy_field }}</th> {% endfor %} <input class='hidden-submit' type="submit"/> </form> </tr> And it looks like this which is what I want: But the problem is my Layout() which I'm using to add extra parameters such has placeholders etc to the form is not working because I'm using |as_crispy_field tag to render individual fields. Here is my form component: class CustomFiltersForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.form_tag = False self.helper.layout = Layout( ) for field_name, field in self.fields.items(): self.helper.layout.append(Field(field_name, placeholder="Search " + field.label)) Is there a way to loop through {% crispy filter.form %} or an alternative way to populate individual fields using cripsy forms? Something like: {% for field in {% crispy filter.form%} %} ... {% endfor %} -
Condition whether field A or B is required in Django Rest Framework
I have a serializer in which I would like to give the opportunity to send a NEW address with a POST request OR give an ID of an already existing address. One of both is required, but right now it asks for both to be given. Any possibility to achieve that it validates with a condition? class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order #fields = '__all__' exclude = ['in_calculation','canceled',] address = AdressSerializer() addressid = serializers.CharField(source='address') read_only_fields = ['id','user','status','costs',''] -
When are Django Querysets executed in the view?
I read the Querysets Django docs regarding querysets being lazy, but still am a bit confused here. So in my view, I set a queryset to a variable like so players = Players.objects.filter(team=team) Later on, I have a sorting mechanism that I can apply sort = '-player_last_name' if pts > 20: players = players.filter(pts__gte = pts).order_by(sort) else: players = players.filter(pts__lte = pts).order_by(sort) if ast < 5: players = players.filter(asts__lte = ast).order_by(sort) else: players = players.filter(asts__gte = ast).order_by(sort) context = {players: players) return render(request, '2021-2022/allstars.html', context) What I want to know is, when is the players queryset evaluated? is it when each page is rendered, or everytime I assign the queryset to a variable? Because if it's the former, then I can just apply the .order_by(sort) chain and the previous applications are redundant. -
What is the best way to learn Django?
What is the best way to learn Django? -
Saving values to django model through a for loop
I want to use a dictionary to store values in a model through a modelform and a view. Today I solve it like this: form.variable_1 = dictionary['variable_1'] form.variable_2 = dictionary['variable_2'] form.variable_3 = dictionary['variable_3'] form.variable_4 = dictionary['variable_4'] form.variable_5 = dictionary['variable_5'] form.variable_6 = dictionary['variable_6'] The keys in the dictionary are identical to the field names for the values I want to store. I would like to make the function a bit more pythonic - something like this: for field in form: form.field = dictionary['field'] However, I'm not sure how to use the Django ORM to achieve this. The fields I want to iterate are numbered 3-28 in the list of fields, so I guess I would have to slice the fields somehow and create a list based on that?