Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django loop refactor: javascript script to views.py in Highcharts
I have a script running that works, but I want to move it to "views.py". I can't seem to get the data I need because of the loop Currently working script: <script> Highcharts.chart('movements_container', { chart: {type: 'column'}, title: {text: "{{account.name}} Income/Outcome"}, plotOptions: {column: {stacking: 'normal', dataLabels: {enabled: true}}}, tooltip: {pointFormat: "Current balance: {{account.balance}} DKK"}, yAxis: {title: {text: "Movements"}}, xAxis: {title: {text: "Income/Outcome"}, type: "datetime"}, credits: {enabled: false}, series: [ {name: "Balance", data: [{{account.balance|floatformat}}], stack: "balance"}, {% for movement in account.movements %} {name: "{{account.name}}", id: "account", data: [{{movement.amount|floatformat}},], stack: "expenses", tooltip: {pointFormat: "Date: {{movement.timestamp}}</br>Transaction: {{movement.text}} </br> Amount: {{movement.amount}}"}}, {% endfor %} ], }); </script> As you can see, the big block above with "series" is what I want to translate to views.py: 12 def account_details(request, pk): 11 assert not request.user.is_staff, 'Staff user routing customer view.' 10 9 account = get_object_or_404(Account, user=request.user, pk=pk) 8 7 chart = { 6 'chart': {'type': 'column'}, 5 'title': {'text': 'test'}, 4 'yAxis': {'title': {'text': "Movements"}}, 3 'xAxis': {'title': {'text': "Income/Outcome"}}, 2 'series': [ 1 # for movement in account.movements: 49 {'name': account.name, 'data':str(account.movements)} 1 ], 3 } 5 6 context = { 7 'account': account, 8 'chart': json.dumps(chart), 10 } 11 12 return render(request, 'bank/account_details.html', context) … -
Problem with importing new Mongo database into the server
I have a Django-based website on the server. I am not really professional at this btw! So, I started the website on the server showing some data from MongoDB. This time I would like to change the DB to the newer one. This is what I am doing: First I drop the last DB: (On venv): $ mongo <db_name> --eval 'db.aggregation__class.drop' Then I scr (the new db) JSON-exported file into a server directory. Then I call the mongo to activate that new db: $ mongoimport --db <new db name> --collection <new db collection name> --file <server directory> I also checked if the db is activated by this: $ mongo <new db name> --eval And it is working. The problem is when I am calling it in the views.py, it does not show that it is connecting to the new db. Consider the fact that it was working with the last db! views.py # connect to MongoDb Database myclient = MongoClient(port=27017) mydatabase = myclient[db_name] classagg = mydatabase['aggregation__class'] database_text = classagg.find() Any suggestion would be appreciated. Thanks -
Should i go with expressjs and mongoose or django and mongoose as the backend for my website (I'm using React for the frontend)?
I have been looking at tutorials for working in the backend of my website and our team members have also thought about using django since it comes with a lot of features(mainly giving permissions to different users is easy there) whereas i don't really have a clue about how this works using express with mongodb. Since the database used for our project is gonna be non-relational(i.e mongodb), please suggest me if i should go with express or django along with mongodb, any documents references will be much appreciated! -
django form not saving on postgresql but does save to sqlite
I've deployed the project to Heroku. I'm using postgresql for my database. The job is attached to a customer table using acct_no as the foreign key. I'm able to create customers using postgresql but I can't create a job. I'm able to create a job using sqlite but when i attempt to use the postgresql database, the createview does not create a job and redirects me to my homepage. I'm fairly new to django and I've tried looking for similiar questions on here but have not been able to find a solution. models.py class Jobs(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. acct_no = models.ForeignKey(Customers, on_delete=models.CASCADE, default=1000000, db_column='ACCT_NO') # Field name made lowercase. foreman = models.CharField(db_column='FOREMAN', max_length=45, blank=True, null=True) comments = models.CharField(db_column='COMMENTS', max_length=255, blank=True, null=True) # Field name made lowercase. views.py class JobCreateView(CreateView): model = Jobs template_name = 'new_job.html' form_class = JobForm def get_initial(self): initial = super(JobCreateView, self).get_initial() initial['acct_no'] = Customers.objects.get(pk = self.kwargs['pk']) return initial def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) customer = Customers.objects.get(pk = self.kwargs['pk']) context["customer"] = customer return context def get_success_url(self): return reverse_lazy('CustomerView', kwargs = {'pk':self.kwargs['pk']}) forms.py class JobForm(forms.ModelForm): class Meta: model = Jobs fields = ['acct_no', 'job_type', 'estimatedate', 'estimatetime', 'vacant', 'year_built', 'comments'] labels = { … -
Import "django.shortcuts" could not be resolved from source
Hello, I wanted to complete my projects that I did not work for a while due to my illness, but when I opened vs code, I came across such an error. -
Save WAV file in Django backend
I am trying to record a voice message in the frontend and send it to the Django backend to test it against a ML algorithm of voice gender prediction. In the frontend I record the voice and I use AJAX to send the blob to the backend where I try to use wave to save the file as a valid .wav. The problem is that the file that gets saved on the backend is only noise without hearing the voice at all. On the frontend I can listen to the voice recording just fine, sounding exactly as it should. I am wondering how could I save on the backend the blob that I receive as a valid WAV file? Here is the recording and blob sending logic on the frontend: <div> <div id='gUMArea'> <button class="home-btn" id='gUMbtn'>Request Stream</button> </div> <div id='btns'> <button class="home-btn" id='start'>Start</button> <button class="home-btn" id='stop'>Stop</button> </div> <div> <ul class="list-unstyled" id='ul'></ul> </div> <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script> 'use strict' let log = console.log.bind(console), id = val => document.getElementById(val), ul = id('ul'), gUMbtn = id('gUMbtn'), start = id('start'), stop = id('stop'), stream, recorder, counter=1, chunks, media; gUMbtn.onclick = e => { let mv = id('mediaVideo'), mediaOptions = { audio: { tag: … -
Django button click rendered View twice
i am really new with Django and still learning. I will try to explain my problem as well as possible. On a button click in my template i want to work with some values & variables: <form method='get' action=''> <input type="submit" value="{{ answer1 }}" name="btn1" /> <input type="submit" value="{{ answer2 }}" name="btn2" /> <input type="submit" value="{{ answer3 }}" name="btn3" /> <input type="submit" value="{{ answer4 }}" name="btn4" /> </form> my views.py: class MyView(TemplateView): def get(self, request, *args, **kwargs): obj = MyObject() self.create_dict(q_obj) if request.GET.get('btn1'): # some code... return render(request, self.template_name, { ... }) The Problem is now whenever i click the button, the used dictionary variable got replaced with the next one because there is a new rendering. [12/Jan/2022 21:48:46] "GET /quizapp/home/subject/ HTTP/1.1" 200 5267 {'answer': <Answer: 3>, 'correct': False} {'answer': <Answer: 5>, 'correct': False} {'answer': <Answer: 2>, 'correct': True} {'answer': <Answer: 7>, 'correct': False} [12/Jan/2022 21:48:47] "GET /quizapp/home/subject/round/ HTTP/1.1" 200 7864 {'answer': <Answer: 4>, 'correct': True} {'answer': <Answer: 2>, 'correct': False} {'answer': <Answer: 6>, 'correct': False} {'answer': <Answer: 1>, 'correct': False} i want to work with the first set but everything i change relates to the second dictionary. I tried fixing with some redirect commands but nothing works... i am … -
Django unittest run specific test syntax
I want to run one specific unit test from my app bank/tests.py in the pipeline but I keep getting errors, I believe I am missing something on the syntax here This is my test: class SettingsTestCase(TestCase): def test_timezone_default(self): target_timezone = 'Europe/Copenhagen' self.assertEqual(target_timezone, settings.TIME_ZONE) print("Test: Correct timezone") This is how I call the test in the pipeline: ... script: - echo "Unit test...." - python manage.py test bank/tests.py:SettingsTestCase.test_timezone_default ... This is the error message when the pipeline fails: RROR: bank/tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: bank/tests Traceback (most recent call last): File "/usr/local/lib/python3.10/unittest/loader.py", line 154, in loadTestsFromName module = __import__(module_name) ModuleNotFoundError: No module named 'bank/tests' ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1) Cleaning up project directory and file based variables 00:01 ERROR: Job failed: exit code 1 Any suggestions? -
error parsing UTF-8 params in Django app at Heroku
I have a django project running on Heroku dyno. The problem is that when I pass a query params in UTF-8 language (farsi) I got 500 error with this log message. 2022-01-12T22:11:30.432160+00:00 heroku[router]: at=info method=GET path="/api/memes/?search=%D8%AA%D8%B3%D8%AA" host=amindjangofirst.herokuapp.com request_id=dece8cd8-8a8e-489e-801a-6b1cbc3df270 fwd="184.163.35.204" dyno=web.1 connect=0ms service=83ms status=500 bytes=452 protocol=https 2022-01-12T22:11:30.431992+00:00 app[web.1]: 10.1.24.50 - - [12/Jan/2022:22:11:30 +0000] "GET /api/memes/?search=%D8%AA%D8%B3%D8%AA HTTP/1.1" 500 145 "https://amindjangofirst.herokuapp.com/api/memes/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" but if I use english characters in query everything works well also on my local machine it's working with UTF-8 params api is available at: working => https://amindjangofirst.herokuapp.com/api/memes/?search=test not-working => https://amindjangofirst.herokuapp.com/api/memes/?search=تست -
Module wsgi error when deploying Django app on apache
I had developped an application using Django (DRF). And I try to deploy it on a server. After following some tutorials on Internet, I got this error : mod_wsgi (pid=27182): Failed to exec Python script file '/my/django/project/path/myProjectName/wsgi.py'. mod_wsgi (pid=27182): Exception occurred processing WSGI script '/my/django/project/path/myProjectName/wsgi.py'. Traceback (most recent call last): File "/my/django/project/path/myProjectName/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application File "/my/django/project/path/venv/lib/python3.9/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/my/django/project/path/venv/lib/python3.9/site-packages/django/utils/version.py", line 1, in <module> import datetime File "/usr/lib/python3.9/datetime.py", line 12, in <module> import math as _math ModuleNotFoundError: No module named 'math' I had checked on some forums but I didn't find a solution to solve my problem. It seems that the problem comes from wsgi module, which is already installed when I was configure the server using this command: sudo apt install libapache2-mod-wsgi-py3 This is my V-host config: <VirtualHost *:8080> ServerAdmin webmaster@localhost # Available loglevels: trace8, ..., trace1, debug, info, no ErrorLog /my-django/project/path/error.log CustomLog /my-django/project/path/access.log combined ServerName my-domaine.com ServerAlias www.my-domaine.com DocumentRoot /my-django/project/path Alias /static /my-django/project/path/static <Directory /my-django/project/path/static> Require all granted </Directory> Alias /media /my-django/project/path/media <Directory /my-django/project/path/media> Require all granted </Directory> <Directory /my-django/project/path/myProject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /my-django/project/path/myProject/wsgi.py WSGIDaemonProcess django_app python-path=/my-django/project/path python-home=/my-django/project/path/venv WSGIProcessGroup django_app … -
Cannot reverse a Django migration using django-otp
Been trying to write the reverse code for a Django migration. Doing the migration there were no issues, but going backwards seems to be causing an issue. My migration file is below. from django.db import migrations, models def forward_migration(apps, schema_editor): totp = apps.get_model('otp_totp', 'TOTPDevice') # Doing some stuff with the devices def reverse_migration(apps, schema_editor): totp_device = apps.get_model('otp_totp', 'TOTPDevice') # Undoing some stuff with the devices class Migration(migrations.Migration): dependencies = [ ('project', 'MY_LAST_MIGRATION'), ] operations = [ migrations.RunPython(forward_migration, reverse_migration), ] When undo the migration, I get the following error: LookupError: No installed app with label 'otp_totp'. What doesn't make sense to me about this error is that if the app can't be found while undoing the migration, why were there no issues while doing the migration? The main solution to this category of problem according to SO is to check the settings.py and to ensure that the referenced app is there correctly. My INSTALLED_APPS: INSTALLED_APPS = [ ..., 'django_otp', 'django_otp.plugins.otp_totp', ... ] This would appear correct according to the django-top docs. I've also tried quite a few variants on the app_label input to get_model function and had no luck. Thank you all in advance! -
How to mock external API call inside a different request function DRF, python
In ViewSet in my DRF project: Let's say I have a post request in which I firstly get data from external api with requests.get, and then I serialize and return it as should be in post request. I am writing unittest with django unittest and I want to mock external api call. This is my first time with mock and I can't find such a case. To sum up: I have post function which gets data from external api if user hasn't passed something. I want to mock result of requests.get but I don't know how to implement it to test for post function I don't know If It would help you to get code snippets or my story is enough. If so, I can add it just let me know. Thanks to everyone that got through my story! -
Deploy failed Internal Server Error 500 - Heroku
I made a project in Django and I want to deploy in heroku but after performing this action it shows me the following error. The console does not show me errors, I attach test images. THANKS FOR READ. -
How low is the visibility of the model for the user?
How to make sure that only the creator of the model could see it, but other participants could not see it, that is, the person who created the model could only see it from his account, and from another account the person saw only his own I have a models.py model class Product(models.Model): username = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=254) image = models.ImageField(upload_to='media/', blank=True, null=True) company_name = models.CharField(max_length=100) def __str__(self): return self.username views.py class ProductListView(ListView): model = Product queryset = Product.objects.all() template_name = 'products_list.html' class ProductDetailView(DetailView): model = Product class NewProductView(LoginRequiredMixin,CreateView): template_name = 'product_form.html' model = Product form_class = NewProductForm success_url = reverse_lazy('product_list_page') class EditProductView(LoginRequiredMixin ,UpdateView): template_name = 'product_form.html' model = Product form_class = EditProductForm success_url = reverse_lazy('product_list_page') how to make it visible only to the current who created it, so that another user sees only his own model that he created. How do I limit the visibility of a model to its creator only? -
How to update changes in live website made with django?
There is an web application live in a server which is made with django. I need to alter a table of that application. I have the code and database in my local machine for working. I have altered the table and added two more columns in the local machine. Altering table in django gives error and you have to migrate the changes of the model. After that it is working fine in my local machine. But I don't know how to push this minor update to the live application. I have the remote access of the server. Do I just go the live project and edit the model code and save and make migrations using cmd? I am afraid I will do some kind of mistake and the application will be effected as it is live. I am new with server side stuffs. Please help. -
Why do I get an old data set in one case after a GET request, and an up-to-date data set in the other
I make a POST request, enter the data into the table, but after that I do a Get and get the old data in this case def get_queryset(self): transaction.commit() if self.action not in ['retrieve', 'list', 'create', 'selector']: res = self.queryset.filter(is_editable=True) else: res = self.queryset return res Up-to-date data) def get_queryset(self): transaction.commit() if self.action not in ['retrieve', 'list', 'create', 'selector']: res = self.queryset.filter(is_editable=True) else: res = Presence.objects.all() return res -
Django bulk update list of objects
I want to create an API endpoint, where you can PUT list of objects and it will work like this: If the ID is specified, query that object and try to update it (if no ID present, show an error) If no ID is present for an object, create. If any previous objects missing saved to the db missing from this list, delete it from the database. What I have found and did not work that way (most of them don't work at all): https://github.com/miki725/django-rest-framework-bulk https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-update The example on django-rest site seems to do it like that, however it is not working for me. -
Which version of Django and/or Python is affected by IP Spoofing?
REF : https://portswigger.net/daily-swig/ip-spoofing-bug-leaves-django-rest-applications-open-to-ddos-password-cracking-attacks Reported Date: Jan 11 2022 Other than providing captcha, what security measure should be taken? Which version of Django and/or Python is affected by IP Spoofing? -
can't override django Form widget attributes correctly
I want to change the name of the widget but then i have two names inside the input class DocumentForm(forms.ModelForm): def __init__(self, *args, **kwargs): # to delete colon after field's name kwargs.setdefault('label_suffix', '') super(DocumentForm, self).__init__(*args, **kwargs) class Meta: model = Document name = "document" fields = ('id', 'comment', 'private', 'position', 'marked') # fields = '__all__' marked = forms.IntegerField( required=False, widget=forms.NumberInput( attrs={ 'name': "asdasdjasdasjdldsa", 'id': "device_documents___name___marked", 'class': 'check preview_image', 'onchange': 'cbChange(this)', 'mazen': "document_set-__name__-position" }, ) ) but if i print this i have two name name="marked" and name="asdasdjasdasjdldsa" how to delete the first one? print(f["marked"]) <input type="number" name="marked" name="asdasdjasdasjdldsa" id="device_documents___name___marked" class="check preview_image" onchange="cbChange(this)" mazen="document_set-__name__-position"> -
tutorial vs API refrence: What is the diffrence?
In many sites like: https://django-tables2.readthedocs.io we see two sections: 1-tutorial 2-API-reference what is the two section explain? what is the difference of them? If we want to use from library How I can start and implementation it? thank you -
Django Rest Framework - loginview Invalid data. Expected a dictionary, but got AnonymousUser
I am trying to code a login view in django rest framework, but I am getting this error: Invalid data. Expected a dictionary, but got AnonymousUser. This is my loginserializer: class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=254, min_length=4) password = serializers.CharField(max_length=68, min_length=8, write_only=True) username = serializers.CharField(max_length=20, min_length=4, read_only=True) tokens = serializers.CharField(max_length=700, min_length=8, read_only=True) class Meta: model = UserProfile fields = ['email', 'password', 'username', 'tokens'] def validate(self, attrs): email = attrs.get('email', '') password = attrs.get('password', '') user = auth.authenticate(email=email, password=password) if not user: raise AuthenticationFailed('Invalid credentials, please try again later') if not user.has_verified_email: raise AuthenticationFailed('Your email has not been verified, please verify it and then proceed to login later.') if not user.is_active and user.has_verified_email: raise AuthenticationFailed('Your account has been disabled, please try again later') return { 'email': user.email, 'username': user.username, 'tokens': user.tokens, } return super().validate(attrs) This is my loginapiview: class LoginAPIView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request): user = request.user serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) return response.Response(serializer.data, status=status.HTTP_200_OK) And I am also returning jwt tokens for the user model using the following function: def tokens(self): refresh_token = RefreshToken.for_user(self) return { 'refresh': str(refresh_token), 'access': str(refresh_token.access_token), } I crossed check everything, I am actually following a course on youtube,but I don't understand what is wrong and … -
IntegrityError: null value in column "id" violates not-null cons
I'm try run a migrate to DB postgres but I find this issue. This is the model `class Place(models.Model): name = models.CharField('Puntos de Luz', max_length=50) description = models.TextField('Descripción', blank=True) url = models.URLField('Canal interactivo', max_length=250) email = models.EmailField('Email',blank=True) create_at = models.DateTimeField('Fecha de creacion', auto_now_add=True) status = models.BooleanField(default=False) def __str__(self): return "{}, {}".format(self.name, self.url) ` and this is my traceback django.db.utils.IntegrityError: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, place, 0001_initial, 2022-01-12 17:01:25.635775+00). this is file migration class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Place', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, verbose_name='Puntos de Luz')), ('description', models.TextField(blank=True, verbose_name='Descripción')), ('url', models.URLField(max_length=250, verbose_name='Canal interactivo')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='Email')), ('create_at', models.DateTimeField(auto_now_add=True, verbose_name='Fecha de creacion')), ('status', models.BooleanField(default=False)), ], ), ] -
Create and add a User to group in Django for tests purpose
I need to test a simple Django project where users in a certain group have some permissions. Now in tests I know how to create a mock user and I have already tested that users not in the group can't access the data trow API, but now I have to test that users in group can access to data. How I can create and add the mock user the group? Thanks in advance for your help. Below my code: import pytest from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.urls import reverse from mixer.backend.django import mixer from rest_framework.status import HTTP_403_FORBIDDEN, HTTP_200_OK from rest_framework.test import APIClient @pytest.fixture() def superheroes(db): return [ mixer.blend('superhero.SuperHero') ] def get_client(user=None): res = APIClient() if user is not None: res.force_login(user) return res # code to test users without permissions (it works!) def test_anon_user_forbidden(): path = reverse('superheroes-list') client = get_client() response = client.get(path) assert response.status_code == HTTP_403_FORBIDDEN # code to test users with permission (so users that are in the group) def test_avengers_user_ok(superheroes): path = reverse('superheroes-list') user = mixer.blend(get_user_model()) # add the user to specific group, but how? client = get_client(user) response = client.get(path) assert response.status_code == HTTP_200_OK -
How to change field value dynamically depended on dropdown selection in django
I've been searching Google, but couldn't find a simple answer to this problem: I have a django models that stores students information and three other models like this: class Level(models.Model): name = models.CharField(max_length=50) class Pricing(models.Model): level = models.ForeignKey(Level, on_delete=models.PROTECT) price = models.PositiveSmallIntegerField(default=0) class Enrollment(models.Model): student = models.ForeignKey(Student, on_delete=models.PROTECT) level = models.ForeignKey(Level, on_delete=models.CASCADE) date_enrolled = models.DateField() price = models.PositiveSmallIntegerField(default=0) I want the Enrollment.price field to be populated dynamically depending on Enrollment.price field value. In javascript, it amounts to setting an event listener to Enrollement.level, but I can't find the equivalent in django. -
Why images are not submitted when using ajax call in django?
I am using a modelForm to create post objects via ajax. The images field are part of the form but not passed to the fields of the Meta class because that will allow to save the post first and add the images uploaded after that. My issue is if I do use a regular view(without ajax) the request.FILES are being submitted correctly but when I use via ajax those files are not part of the request.files which renders an empty <MultiValueDict: {}> I don't really know why. Here is my code. def post(self, request, *args, **kwargs): form = PostForm(request.POST or None, request.FILES or None) result = {} files = request.FILES print(files) if is_ajax(request=request) and form.is_valid(): print("the request is ajax and the form is valid") title = form.cleaned_data.get("content", "") print("Title ", title) post_instance = form.save(commit=False) post_instance.author = request.user result['success'] = True return JsonResponse(result) $.ajax({ url: $("#CreatePostModal").attr("data-url"), data:$("#CreatePostModal #createPostForm").serialize(), method: "post", dataType: "json", success: (data) => { if (data.success) { setTimeout(() => { $(e.target).next().fadeOut(); ResetForm('createPostForm', 'PreviewImagesContainer') $("#CreatePostModal").modal('hide') $(e.target.nextElementSibling).fadeOut() alertUser("Post", "has been created successfully!")// alerting the user }, 1000) console.log(data.title) } else { $("#createPostForm").replaceWith(data.formErrors); $("#PreviewImagesContainer").html(""); $("#CreatePostModal").find("form").attr("id", "createPostForm"); $(e.target.nextElementSibling).fadeOut() }; $(e.target).prop("disabled", false); }, error: (error) => { console.log(error) } }) }); Here is the …