Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to link two model classes in django so that if the input of a user matches a part of the other model class, it retrieves those instances?
I have a project where a user can enter their credentials: user, datasource username, data source, and a new password. When they press submit, it updates the objects that have the same user, datasource username, and data source as what the user submitted and updates those passwords with the new password. These objects are called PcolCredentials objects since they have credentials such as the ones listed above, and these creds have their own model classes. The whole premise of the project works, but the only problem is that it only works with a PcolDataSource. There are two model classes, Pcoldatasource and Datasource, and I am supposed to have a user enter their DataSource in the form, not a Pcoldatasource. In the backend, these objects have PcolDataSources so obviously the form requires a PcolDataSource. I need to use a DataSource instead, and when the user enters a DataSource, it will update all passwords of every object that has that DataSource in a PcolDataSource. For example, a user enters "Dev" as a DataSource and the PcolDataSource of objects that have Dev are Prod, Dev, Test. This will update the password all objects that have Dev in the PcolDataSource Prod, Dev, Test. I … -
How to validate space ( ) in RichTextUploadingField by CKEDITOR in django server side
While using RichTextUploadingField by CKEDITOR in an DJANGO project, when i tried saving space though with python codes i tried to validate (.strip() and .isspace()) it got bypass. when i check the DB the entry in the DB was as follows: <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;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;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</strong></em></u></p> Does any one have any idea for solving this issue of saving empty spaces int he DB. -
Django OAuth Toolkit - Authenticating with Access Token
I am trying to follow the steps from this tutorial: https://django-oauth-toolkit.readthedocs.io/en/1.1.2/tutorial/tutorial_03.html I have a provider that is returning an authorization token to my callback_url. After that I am exchanging it for an access token using a POST request to their server. The response has available the username, access token, expiry date and more information. How can I proceed to authenticate the user with this data? import requests def authdt(request): authentication_code = XYZ123 url = "https://PROVIDER/api/v3/oauth/token" payload = authentication_code headers = { 'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", 'cache-control': "no-cache", } response = requests.request("POST", url, data=payload, headers=headers) render(request, "index.html") The tutorial mentions using the OAuth2 authentication backend. https://github.com/jazzband/django-oauth-toolkit/blob/master/oauth2_provider/backends.py The authorize method takes a request objects as an input. What would be the proper way to authorize the user after that in a way that is persistent across different views? -
Is there a testing tool for end to end testing for django rest framework micro services and react js? If not, any other way of end to end testing? [closed]
I am using Django REST framework in backend and ReactJs in front end. Used DRF apitestcases for testing apis. Is there any E2E (end to end) testing tool for DRF and Reactjs web app? Are there any other ways to test End to End? And also, what is automation testing and end to end testing, does it include backend and frontend testing? -
Django-dynamic-formset: how to implement function to remove data from database?
I use for the first time Django-dynamic-formset. Currently, subform of inlineformset can be deleted i.e. removed from DOM but record is not deleted from database. As mentionned in Github documentation, I understand I should implement a 'removed' function that will be called each time 'Delete' link is click. I should recovered row id... but I don't know how... -
Django render dynamic image in template
In a Django view, I can generate a dynamic image (a graph in PNG format), and it creates a response that is an image of my graph. I can get it to display in the browser, but there is no web page with it - it's just the image. Now I'd like to embed this image in an HTML template and render it. How can I do that? (This is my first Django project.) import matplotlib.pyplot as plt import numpy as np import io # Initialize the matplotlib figure f, ax = plt.subplots(figsize=(6, 15)) width = my_data['bar_length'] data_names = my_data['ObjectNames'] y_pos = np.arange(len(data_names)) norm = plt.Normalize(my_data['bar_length'].min(), my_data['bar_length'].max()) cmap = plt.get_cmap("RdYlGn") # Create horizontal bars plt.barh(y_pos, width, color=cmap(norm(my_data['bar_length'].values))) # Create names on the y-axis plt.yticks(y_pos, data_names) FigureCanvasAgg(f) buf = io.BytesIO() plt.savefig(buf, format='png') plt.close(f) response = HttpResponse(buf.getvalue(), content_type='image/png') # This works, but it generates just an image (no web page) return response # This ends up displaying the bytes of the image as text #return render(request, 'my_app/graph.html', {'graph1': buf.getvalue()}) # This is what is in the graph.html template # <div class="graph1"> # {{graph1 | safe}} # </div> -
how to identify whether the thin client is a new one or spare device
I have a Django web application where I am maintaining the different thin client's settings under a specific MAC address. MQTT protocol is used for the communication purpose.When a new thin client finds the MQTT server in Django framework,a new entry will be created for that device in Django application. I've a requirement when old thin client replaces with new thin client,I do not want to create a new table but update the old table with latest MAC address so that new client will act as old one. is it possible to identify whether it is a spare device or a fresh device ? -
How to to avoid duplicate error messages for the same field in django formset
I am trying to render formset errors , with this code if a field in the formset is empty the error pop up , but the probleme is i want to avoid duplicated errors for the same field ?? template : {% for form in formset %} {% for field in form %} {% if field.errors %} <div class="alert alert-danger"> <strong>{{ field.label }}: {{ field.errors|first }}</strong> </div> {% endif %} {% endfor %} {% endfor %} -
What is the most efficient way to run a custom method on many objects of a model in Django?
Let's say I have the model: class my_model(models.Model): name = models.Charfield(#...) def do_something(self): #... No I have a queryset of objects of this class and I want to run the do_something method on all of them. I do: for obj in my_queryset: obj.do_something() But this is very slow. Any Ideas how I could make it faster? -
Django, Apache2 returns default it works page
I was trying to enable ssl on my Django website with LetsEncrypt certbot, with apache2 web-server. It was working fine with http. Now that i have installed certificates using certbot, the website returns the debian apache it works page. These are the last two lines of my apache error log after systemctl restart [pid 2019:tid 139908538110016] AH00489: Apache/2.4.25 (Debian) OpenSSL/1.0.2u mod_wsgi/4.6.5 Python/3.7 configured -- resuming normal operations [pid 2019:tid 139908538110016] AH00094: Command line: '/usr/sbin/apache2' The following is the configuration i used for VirtualHost 443 ServerName example.com ServerAlias www.example.com ServerAdmin root@example.com SSLEngine On Alias /static /home/debian/static <Directory /home/debian/static> Require all granted </Directory> <Directory /home/debian/quizapp/quizapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess quizapp python-home=/home/debian/quizapp/mqbenv python-path=/home/debian/quizapp WSGIProcessGroup quizapp WSGIScriptAlias / /home/debian/quizapp/quizapp/wsgi.py RewriteEngine on Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/exapmle.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem The same configuration is for http site without SSLEngine on. This configuration was working earlier for http but now it shows "It works" page. Is it because i deleted the site from sites-enabled? Because now it contains both the sites so that should'nt happen. What could be the issue here? Also, my server doesnt respond to https requests. I have ports allowed https 443 in ufw firewall. netstat returns this sudo netstat -tulpn … -
Django + PostgreSQL search speed problems (on Webfaction server)
I've got a model (on Django and PostgreSQL) with lookup tokens having 3 fields: tokens (ArrayField containing a list of CharFields (actually tokens)), movie_type (CharField), movie_id (BigIntegerField). I perform one-word search queries, for instance, 'Titanic' and look for those Lookup instances where tokens contain the word I search for. So, the program searches for 'Titanic' and finds the ArrayField with ['Titanic', 'DiCaprio', 'Winslet'] with movie_type Drama and movie_id 175. Using movie_id and movie_type, it retrieves the required QuerySet from my Movie table. The problem is that the speed of queries is different every time on the Webfaction server where my site live (in contrast to the local server, where everything is super-fast). I have tested the speed of both database queries and the python code I have. It measures at 0.0001 to 0.02 seconds, i.e. is very fast. But in practice the results are processed between some 0.2 s and 27 s. And there is no logic behind these different times. So, the query 'Titanic' can be processed within 0.2 s one time and within 27 seconds another time. The question is: what might be causing such problems? I have tested my code speed all about, and I see no … -
How to test changes in models Querries in Django while testing views
Ok, so here's the issue. I want to write simple unit test that checks if there are 2 or more players ready in the game, and host makes request to start the game boolean status of the game changes to True. Views: @login_required def game_start(request, id): game = Game.objects.get(id=id) w_pokoju = game.players_ready player = Player.objects.get(name=request.user) usr = player.nick if w_pokoju > 1 and game.host == usr: if not game.is_played: game.is_played = True game.save() return redirect('detail', id=game.id) else: return redirect('detail', id=game.id) else: return redirect('detail', id=game.id) Looks simple, and works but I want to access it in unit test. def setUp(self): self.client = Client() self.user = User.objects.create_user(username='testuser', password='12345') self.user2 = User.objects.create_user(username='testuser2', password='12345') usr = self.user self.client.login(username='testuser', password='12345') self.player = Player.objects.create(name=usr, parent = usr.username, nick = 'nie') def test_start_room(self): game = Game.objects.create(name='start',host= self.user,is_played=False,max_players=4,players_ready=2) self.start_room = reverse('game_start', args=[game.id]) response = self.client.get(self.start_room, follow=True) self.status = game.is_played self.assertEquals(self.status,True) And The result: AssertionError: False != True Looks like making get request doesn't change anything in "is_played" status, like clicking manually does. Please help me guys where is the trick? -
How to prevent XSS attack in django
I'm trying to prevent XSS attack in Django, is it ok to use {{ body|escape }} in my HTML file only? How can I do some filtration in the backend? -
Celery task calls endpoint. Is it celery or the django server that does the job?
This is a generic question that I seek answer to because of a celery task I saw in my company's codebase from a previous employee. It's a shared task that calls an endpoint like @shared_task(time_limit=60*60) def celery_task_here(some_args): data = get_data(user, url, server_name) # some other logic to build csv and stuff def get_data(user, url, server_name): client = APIClient() client.force_authenticate(user=user) response = client.get(some_url, format='json', SERVER_NAME=server_name) and all the logic resides in that endpoint. Now what I understand is that this will make the server do all the work and do not utilize celery's advantage, but I do see celery log producing queries when I run this locally. I'd like to know who's actually doing the job in this case, celery or the django server? -
Database error:No exception message supplied?
I am trying to create an article here.I started to get this error that says Database Error:No exception message supplied What can i do to remove this error? views.py class ArticleCreateView(CreateAPIView): serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def create(self, request): serializer_context = { 'request': request } serializer_data = request.data.get('article',{}) serializer = self.serializer_class( data=serializer_data, context=serializer_context, ) serializer.is_valid(raise_exception=True) serializer.save() response = { 'success' : 'True', 'status code' : status.HTTP_200_OK, 'message': 'Article Created Successfully!', } status_code = status.HTTP_200_OK return Response(serializer.data, status=status.HTTP_201_CREATED) serializer.py class ArticleCreateSerializer(serializers.ModelSerializer): caption = serializers.CharField(required=False) details = serializers.CharField(required=False) author = UserSerializer(read_only=True) class Meta: model = Article fields = ('id','author','caption','details') def create(self, validated_data): author=self.context['request'].user.profile article = Article.objects.create(author=author,**validated_data) return article -
Ajax returning HTML seems to be blocked by corporate firewall
I've made a django web app that works very well on every device I own, but my company's computer. I am sure this is because my web content is filtered by my company's rules (the machine connects to the internet via a token+proxy). More precisely, ajax requests to a view returning a HTTPresponse (via render()) are blocked, while those that return json (via JsonResponse()) are not. I got a 403 "MediaTypeNotDetected" error and this cryptic message: "this file has been blocked because it's not supported" (I translated to english). I've tried returning my HTML via JsonResponse (JsonResponse({"html": loader.render_to_string(...)}, ...)) and that worked. But that's not a good solution (it would mean refactoring a huge part of my code and I don't want that). Could anyone tell me what's going on and how I can fix that (I've already asked my company to whitelist my domain but I'm not quite sure that will fix the issue, plus it could take a hell of a long time to be done...). -
Django 3 - Model.save() when providing a default for the primary key
I'm working on upgrading my project from Django 2 to Django 3, I have read their release notes of Django 3 and there is a point that I don't really understand what it will impact to my current project. Here they say: As I understand, if we try to call Model.save(), it would always create a new record instead of updating if the model is an existing record. For example: car = Car.objects.first() car.name = 'Honda' car.save() # does it INSERT or UPDATE? I suspect it is an "INSERT" statement as their explanation. I have had an experimented and it is still the same behaviour as Django 2, not sure what they mean. -
How to use grant_type as client_credentials with django oauth toolkit
Are there any good resources that shows how to use different grant_types using Django oauth toolkit. I am specifically looking for configuration steps for grant_type=client_credentials -
Django - Model logic that spans multiple models. Where to add this? (related foreign keys)
I'm trying to work out how I go about calculating stats for my app based off related foreign keys. And the best way to do so. Where I put the logic etc. It's a bit unclear to me. Basic example: MODELS (Basic sample) class Enquiry(models.Model): name = models.CharField(max_length=250, null=True, blank=True) class Interaction(models.Model): enquiry = models.ForeignKey('Enquiry', on_delete=models.CASCADE, related_name='relatedinteraction') rating = models.IntegerField(null=True, blank=True) interaction = models.CharField(max_length=250, null=True, blank=True) Okay for example lets say I have multiple interactions associated to multiple enquiries. And I have a view that outputs all the enquiries in a summary page. How would I output the following within the summary view for each: The last interaction each enquiry had OR if none yet have this message 'None Yet...' The avg rating of all the interactions for each enquiry Please could someone help me understand how and where this logic should go? I initly thought I should be making model methods on in the Enquiry class calling the Interactions model. But that caused massive amounts of DB queries. So I am trying to understand how this should really be done. -
Django: Saving new object with form and inline formset (transaction managment)
I have a form in which I creates a new "parent" object, exactly one child object of type A and n child objects of type B (n can also be 0). I do this with a form and and two inlineformsets. I have set in settings 'ATOMIC_REQUESTS': True. I'm using a function based view. The code for saving the data is like this: if form.is_valid(): parent = form.save(); formsetA = AFormset(request.POST, instance=parent) formsetB = BFormset(request.POST, instance=parente) if formsetA.is_valid(): # save first form in inline formset (there always only is one) # and then assign meta data a = formset[0].save() if formsetB.is_valid(): for b in formsetB: if b.is_valid(): b.save() Check if parent is valid, save it and set it as instance of the inline formsets. Then check the inline formsets. If a form is not valid I redirect back to the form. No exception. Issue is that if a inlineformset is invalid, it returns to the form but the parent was already saved and transaction is not rolled back. If I roll back the transaction manually just before redirecting back to the form I get an exception: An error occurred in the current transaction. You can't execute queries until the end … -
Data migration to delete datarows isn't working correctly
I have a table in my database "gatewaydevices", where every gateway is connected to a device. Field: start_date, device, gateway, end_date There can be multiple rows for the same gateway/device combination. There should only be one combination with end_date null. That's the active gateway for that device In the current database this is not, so I want to delete all records where the end_date is null and there is another record for those device/gateway with end_date null and a recent start_date. So there is only one record with end_date null per device/gateway combination. This record has the most recent start_date then. I filled my test db with these records: I started with this data migration: from django.db import migrations def delete_old_gatewaydevices(apps, scheme_editor): GatewayDevice = apps.get_model("gateways", "GatewayDevice") for gw in GatewayDevice.objects.filter(end_date=None).all(): active_gateway = ( GatewayDevice.objects.filter( device=gw.device, gateway=gw.gateway, end_date=None ) .order_by("start_date") .first() ) for gatewaydevice in GatewayDevice.objects.filter( device=active_gateway.device, gateway=active_gateway.gateway, end_date=None ): if gatewaydevice.start_date < active_gateway.start_date: GatewayDevice.objects.filter(pk=gatewaydevice.pk).delete() class Migration(migrations.Migration): dependencies = [ ("gateways", "0028_merge_20200410_1529"), ] operations = [migrations.RunPython(delete_old_gatewaydevices)] After I ran the migration, the data-rows are still in my database, is that normal? It's like nothing changed? Is my migration script not correct or am I doing something else wrong? -
Can I use a JS Framework to display small JS tasks in a Django project?
I have an idea to simplify the online experiments from our university. But I'm not so familiar with the newest FE frameworks eg. react, angular, vue. Any answer on this post is appreciated :) The idea is, to put our experiments in two folders, "tasks" and "treatments". A task could be something trivial like put some sliders on the right position or write with a chatbot (this should be coded in js, I guess?) and in treatments could be something like collecting badges or the setting for the chatbot (e.g. human-like/machine-like). My question is: Can I use a JS Framework to load the content from the two directories and show them as options on a main page? After selecting the task and the treatments, it would generate a page with the selected items, e.g. the chatbot with the human-like setting. I Would like to do this with Django (because I already worked with it) so we can create unique links to send them to the probands. Is Django with a JS Framework the right decision? How would you approach the problem? -
Python how to calculate montlhy and yearly amount
I have a question for you. I managed to calculate a monthly amount of my data with the following code: incassi = dict() total_incassi=dict() for year, month, totale in(Ricavi.objects.values_list( 'data_pagamento__year', 'data_pagamento__month'). annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('ricavo')*(1+F('iva'))), output_field=FloatField())).values_list('data_pagamento__year', 'data_pagamento__month', 'totale')): if id not in incassi.keys(): incassi[id]=list(defaults) index=month-1 incassi[id][index]=totale total_ricavi={'Ricavi Lordi': [sum(t) for t in zip(*ricavi.values())],} But in this manner, if I put in my database the following date: 1/01/2020 100€ 1/01/2021 100€ My code carry out the following output: Jan 200€ without considering the year. how can change my code to get it? -
Correct way to serialize form data involving more than one Model
I have three models of Account, Club and AgentPlayer class Account(models.Model): nickname = models.CharField(max_length=64) club_account_id = models.IntegerField() agent_players = models.ManyToManyField( AgentPlayer, related_name="accounts") clubs = models.ManyToManyField( Club, through='AccountClub', related_name='accounts') def __str__(self): return f"{self.nickname} ({self.club_account_id})" class AccountClub(models.Model): account = models.ForeignKey( Account, on_delete=models.CASCADE, related_name='club_deal') club = models.ForeignKey( Club, on_delete=models.CASCADE, related_name='account_deal') rakeback_percentage = models.DecimalField( max_digits=3, decimal_places=3, validators=[MinValueValidator(Decimal('0.01'))]) chip_value = models.DecimalField(max_digits=3, decimal_places=2, validators=[ MinValueValidator(Decimal('0.01'))]) def __str__(self): return f"{self.account.nickname} belongs to {self.club.name} with rakeback of {self.rakeback_percentage} and chip value of {self.chip_value}" class Club(models.Model): PLATFORMS = ( ('UP', 'UP'), ('PB', 'PB'), ('PPP', 'PPP'), ('ANP', 'ANP'), ('PT', 'PT'), ) name = models.CharField(max_length=64) code = models.CharField(max_length=3) club_id = models.IntegerField() chip_value = models.DecimalField(max_digits=3, decimal_places=2, validators=[ MinValueValidator(Decimal('0.01'))]) platform = models.CharField(max_length=3, choices=PLATFORMS, default='PB') agent_players = models.ManyToManyField( AgentPlayer, through='Deal', related_name='clubs') def __str__(self): return f"{self.name} ({self.code}) - {self.club_id}" I am trying to create Account via djangos REST framework. The form data that I get from front end is rendered using an AccountForm class: class AccountForm(ModelForm): rakeback_percentage = forms.DecimalField( min_value=0, decimal_places=3, help_text='Should not be higher than your own') chip_value = forms.DecimalField( min_value=0.1, decimal_places=2) class Meta: model = Account fields = '__all__' def __init__(self, user, *args, **kwargs): super(AccountForm, self).__init__(*args, **kwargs) self.fields['agent_player'].queryset = AgentPlayer.objects.filter( user=user) I could parse the data from the form and create each model … -
Unpickle (dill) fails in Django but works in normal script
I have this weird case that I can deserialize a pickled object in a regular script but it fails inside of a Django app. I have a statistical model pickled were parts of it are using PyTorch. When I write a simple script I can restore the model as expected: from strategy.settings import ML_MODELS_PATH from django.http import HttpRequest from django.shortcuts import render import matplotlib.pyplot as plt from pandas_ml_common import Constant from pandas_ml_utils import FeaturesAndLabels, Model, PytorchModel, MultiModel, AutoEncoderModel from pandas_ml_utils.constants import PREDICTION_COLUMN_NAME from pandas_ml_utils.ml.data.extraction import extract_with_post_processor from pandas_ml_quant import pd, np, PostProcessedFeaturesAndLabels import torch as t import torch.nn as nn from pandas_ml_utils.pytorch import Reshape import os def load_model(): m = Model.load(os.path.join(ML_MODELS_PATH, "T", 'ConvAE.model')) print(m) return m if __name__ == '__main__': load_model() But when I use the same function from a Django view it suddenly fails with the message: NameError: name 'nn' is not defined from django.http import HttpRequest from django.shortcuts import render import foo def render_dashboard(request: HttpRequest, **kwargs): symbol = kwargs["symbol"] foo.load_model() Using Django 2.2. and python 3.7