Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS Elastic Beanstalk/Django: How do I get static files to work?
I'm running the newest Django/Python version on Elastic Beanstalk, which I believe runs on Amazon Linux 2023. My Django website is finally deployed (after much blood, sweat and tears). My website correctly displays all HTML/Database info, but it's missing CSS/JS, which are contained within the static files. Some of the elastic beanstalk documentation is a bit deprecated - I tried following this guide: But my configuration contained absolutely no mentions of static files at all. What am I missing, and how can I add them? Thanks. -
How to succesfully make a POST request with JS fetch to a Django REST API
I've been trying unsuccesfully to make a POST request to my API end point, and I always get an error. My setup is a django server with a rest API, and I'm trying to add a reservation to the Booking Model, using fetch. This is the code inside my "onSubmit" js function (when the submit button is clicked): csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value; const formdata = new FormData(form); fetch('/api/booking/', { method: 'POST', headers: { "X-CSRF-Token":csrf, "Content-Type": "application/json" }, credentials: "same-origin", body: formdata }) .then(res => res.json()) .then(data => console.log(data)); models.py class Booking(models.Model): client = models.ForeignKey(User, on_delete=models.CASCADE, null=True) date = models.DateField(null=True) hour = models.SmallIntegerField( null=False, default=12, validators=[ #from 8am to 10pm MaxValueValidator(22), MinValueValidator(8) ], ) class Meta: unique_together = ('date', 'hour') forms.py class BookingForm(ModelForm): class Meta: model = Booking fields = ['date', 'hour', 'client'] views.py (of the api endpoint /api/booking/ class BookingView(generics.ListCreateAPIView): queryset = Booking.objects.all() serializer_class = BookingSerializer So this is the error I get in the Chrome JS console: book:159 POST http://127.0.0.1:8000/api/booking/ 400 (Bad Request) onSubmit @ book:159 book:169 {detail: 'JSON parse error - Expecting value: line 1 column 1 (char 0)'}detail: "JSON parse error - Expecting value: line 1 column 1 (char 0)"[[Prototype]]: Object Any idea what is the problem? -
Unit testing in Python on a function that doesn't have a return value? Is including test-specific code in a function bad practice?
I am writing a mock-up Auction site in Django as part of my self-learning to code. I'm at the point where I'm learning to write tests for my software but I've encountered the problem where a number of my functions used for the web app do not normally return a value. In this one example, I included a boolean parameter for a function that checks whether it is being tested or not. If the parameter is true, it executes a block of code that then does return value that I can then assert with unittest. This is the function: def cleantags(testing=False) -> None: """Executed on listing update, delete, or accept. Purges tags in 'Category' that are no longer used""" unused_tags = Category.objects.filter(Q(listing__isnull=True) | Q(listing__sold=True)) for _tag in unused_tags: _tag.delete() if testing: deleted_tags = [] for _tag in unused_tags: deleted_tags.append(_tag.__str__()) return deleted_tags This is the unittest: def test_tag_deleted(self): """Checking that cleantags() will purge tags in Catergories that don't belong to a listing or to one that has sold.""" # ['Lions','Tigers','Bears','Foo','Bar'] tag_objs = self.generate_tags() self.listing1.tags.add(tag_objs[0]) self.listing1.tags.add(tag_objs[1]) self.listing2.tags.add(tag_objs[2]) self.listing2.sold = True del_tags = listmng.cleantags(True) self.assertQuerySetEqual(del_tags, ['Foo','Bar']) I guess my main question is if this is considered bad coding practice, and if so is … -
Fetch user roles from keycloak using django-allauth
I've managed to get Django to login using Keycloak via openid-connect. I did this with django-allauth. The problem I have now is that I can't figure out how to determine (in Django) which roles a user has (these are defined in Keycloak), in order to give the user appropriate permissions to do things. -
mysqlclient Python Package stop working after Sonoma update
I'm working on a project that uses Django, which connects to a MySQL database, and one of the packages that is used to perform this operation is mysqlclient. But, early this day my laptop was forced to update his OS to Sonoma (I'm working on a Mac), and after that, when I tried to run the project again, it stopped working, and now it throws this error: enter image description here I've tried reinstalling my mysql-client with brew and exporting these variables into my .zshrc file without success. export LDFLAGS="-L/usr/local/opt/mysql-client/lib" export CPPFLAGS="-I/usr/local/opt/mysql-client/include" export PKG_CONFIG_PATH="/usr/local/opt/mysql-client/lib/pkgconfig" Could someone please help me with a solution about this issue? -
Django Orm implementation of connection between unrelated fields by geometry
I am trying to return the closest node locations to a starting node where the 2 database tables have no relation defined between one another. Therefore, I need to find a method to create a full cross join between the tables/subsets of data according to a filter or a facsimile of one. Models: class WaysVerticesPgr(models.Model): objects = CTEManager() id = models.BigAutoField(primary_key=True) cnt = models.IntegerField(blank=True, null=True) chk = models.IntegerField(blank=True, null=True) ein = models.IntegerField(blank=True, null=True) eout = models.IntegerField(blank=True, null=True) the_geom = models.PointField(srid=3857, blank=True, null=True) class Meta: managed = True db_table = 'ways_vertices_pgr' class Pois(models.Model): objects = CTEManager() id = models.BigIntegerField(primary_key=True) name = models.TextField(blank=True, null=True) tags = models.JSONField(blank=True, null=True) geom = models.PointField(srid=3857) class Meta: managed = False db_table = 'pois' Query 1 - q1 - is getting points from the Pois table that fit any criteria, the result I want is the nodes inside the waysverticespgr table of the routing section of the database and return each node reachable in a set time (i.e. within walking distance <= 10 min) with the minimum distance from any of the starting nodes and annotate the resulting nodes with the actual distance. I have working sql for this query but implementing with django orm or django_cte … -
How can I create an "Artist" instance from my Django model when an instance of a User class is created?
I am building a web API in Django and DRF. I have an Artist model that contains different fields and a OneToOnefield to a user which was inherited from an AbstractBaseUser class that contains the following fields: username, email, first_name, last_name, is_artist. I want a situation whereby once a user is created, an instance of the Artist model is also created. Note: I am handling authentication endpoints using Third-Party packages and libraries using Djoser. So I didn't define any views for the user model. How can I achieve what I have described above? Here's my code: The User model: import uuid from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class User(AbstractBaseUser, PermissionsMixin): pkid = models.BigAutoField(primary_key=True, editable=False) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) username = models.CharField(verbose_name=_("Username"), max_length=255, unique=True) first_name = models.CharField(verbose_name=_("First Name"), max_length=50) last_name = models.CharField(verbose_name=_("Last Name"), max_length=50) email = models.EmailField(verbose_name=_("Email Address"), unique=True) is_artist = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", "first_name", "last_name", "is_artist"] objects = CustomUserManager() class Meta: verbose_name = _("User") verbose_name_plural = _("Users") def __str__(self): return self.username @property def get_full_name(self): return f"{self.first_name} {self.last_name}" def get_short_name(self): … -
cannot be loaded because running scripts is disabled on this system. For more information,
When I want to active my env on my vs code it says : "cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:3" So I go to my administrator powershell and use this command : Set-ExecutionPolicy RemoteSigned now I can activate my env on my code and I have a very simple project with one app and this view : from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("<h1>Hello world</h1>") Now when I run the code it shows the default page of Django (The install worked successfully! Congratulations! You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs.) though it has to show the "hello world" message for me. Now I use vs code debugging terminal and I can see the "hello world" message on my "localhost:8000". I uninstall and install virtualenv and I added to my path but nothing changed. I'm facing this error for 1 week please someone help me I'm expecting when I run the server in env vs code it shows me the "hello world" message which is shown on debugging mode … -
Error While installing GDAL in Github Actions while deploying to Azure
My work flow file is on: push: branches: - main workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Set up Python version uses: actions/setup-python@v2 with: python-version: '3.9' - name: Install Django run: | pip install django - uses: conda-incubator/setup-miniconda@v2 with: activate-environment: SERVIR_AppTemplate environment-file: environment.yml auto-activate-base: false - run: | conda info conda list - run: conda install -c anaconda django - run: python -c "import sys; print(sys.path)" - name: Install GDAL run: | sudo apt-get update sudo apt-get install -y libgdal-dev sudo apt-get install -y python3-dev - name: Install GDAL Python Package run: | pip install GDAL - name: Upload artifact for deployment jobs uses: actions/upload-artifact@v2 with: name: python-app path: | . !venv/ deploy: runs-on: ubuntu-latest needs: build environment: name: 'Production' url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v2 with: name: python-app path: . - name: 'Deploy to Azure Web App' uses: azure/webapps-deploy@v2 id: deploy-to-webapp with: app-name: 'EcoDynlab' slot-name: 'Production' publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_ }} I'm getting error while installing gdal Collecting gdal Downloading GDAL-3.7.2.tar.gz (777 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 777.0/777.0 kB 27.6 MB/s eta 0:00:00 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python … -
How to create session based authentication with django_rest_framework?
I have been trying to create a simple login with a react and django. When my user first enters the page there is no csrftoken and sessionid. After filling the credentials and clicking on the Log in button a POST request is sent to /api/login. The request is succesful and the csrftoken and sessionid are stored as cookies and the user is redirected to the main application. In the main application there's a Log out button which sends a POST request to /api/logout which is ought to log out the user and flush the session. However I seem to be unable to access the logout route. The console error from the axios call reads: POST http://localhost:8000/api/user-logout/ 403 (Forbidden) and in the Network tab the response reads: { "detail": "CSRF Failed: Origin checking failed - http://localhost:3000 does not match any trusted origins." } Now I obviously did include the origin http://localhost:3000 to the list CORS_ALLOWED_ORIGINS but nevertheless this error keeps occuring. I want to use the django_rest_framework for the SPA application, but in combination with session based authentication. Basically I was hoping to authenticate each request with the session state when the application is to be used via the browser, but … -
column does not exsist in django app, migrations went bad? or related_names issue
I am not sure why I get this error when I am pretty sure the migrations are all without a hitch. I have a new model: class Proposal(models.Model): objects = models.Manager() program = models.ForeignKey("Program", on_delete=models.CASCADE) institution = models.ForeignKey("mainpage.Institution", on_delete=models.CASCADE) title = models.CharField(max_length=100) #scheduler = models.ForeignKey('accounts.APOUser', on_delete=models.CASCADE) scheduler = models.ForeignKey('accounts.APOUser', related_name='%(app_label)s_%(class)s_scheduler_related', on_delete=models.CASCADE) pi = models.ForeignKey('accounts.APOUser', related_name='%(app_label)s_%(class)s_pi_related', on_delete=models.PROTECT) #observers recahback to proposal observer. untrained_observer_list = models.CharField(max_length=200) #just seperate via commas collaborators = models.CharField(max_length=200) #just seperate via commas contact_information = models.CharField(max_length=200) #might break this out to a complete address? #instrument = models.ForeignKey("Instrument", on_delete=models.PROTECT) instrument = models.ManyToManyField("Instrument") #each program can have many instruments. primary_dis_grating = models.CharField(max_length=20) #is this going to be replaced by FILTER DB? or based on instrument? independent from instrument? secondary_dis_grating = models.CharField(max_length=20, null=True, blank=True) slits = models.CharField(max_length=150) #is this based on instrument? independent of instrument? several options per instrument? filters = models.CharField(max_length=150) #same as above targetofop = models.CharField(max_length =200, null=True, blank=True) #can be blank location = models.CharField(max_length=20) #remote, onsite, work by apo? other? time_request_dark = models.IntegerField(null=True, blank=True) time_request_grey = models.IntegerField(null=True, blank=True) time_request_bright = models.IntegerField(null=True, blank=True) science_justification = models.CharField(max_length=300) pre_emption_protection = models.CharField(max_length=200) publication = models.CharField(max_length=300) approved_on = models.DateField() isApproved = models.BooleanField() reviewed = models.BooleanField() I got the error though when I goto … -
Merge two models with one-to-one relationship into one model serializer (Django)
In Django Rest, I have a model named User which is used as AUTH_USER_MODEL. In order to expand this model and separate authentication-related fields with additional information, I have created another model named Profile. Profile contains unrelated data like age, height, country, zip_code, and so on. These two models have one-to-one relationship. I need a special endpoint which is only accessed by admin and used for creating a user and its profile in one request. For this purpose, I need a flat serailizer like this: { "username": "something", "password": "1234", "email": "user@domain.com", "age": 43, "country": "USA" } I tried creating a class inheriting serailizers.Serializer and create fields manually, but this seems very unengineered. Also imagine what happens if later on I add new fields to these models. Also, I could include ProfileSerializer inside UserSerializer and I would have: { "username": "something", "password": "1234", "email": "user@domain.com", "profile": { "country": "USA", // and rest of fields } } I need a flat serializer combining two (or even more) models that have one-to-one relationship.The serializer must contain all required fields of these two models. What should I do? -
Mobile Browser stripping out 10 digit numbers
I have a Django app that takes user text and relays it to another user. In some cases the text includes 10 digit phone numbers or 10 digit authorizations. On mobile devices our users are reporting that any 10 digit number is being removed from the input field. Base.html <!DOCTYPE HTML> <html lang="en"> <head> {% load static tags bootstrap4 %} <!-- <link rel="icon" type="image/png" sizes="96x96" href="{% static 'invoiceManager/images/favicon-96x96.png'%}"> --> {% appName as name %} <title>{{name}} Job Manager</title> <meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate"> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="format-detection" content="telephone=no" /> <!-- <meta name="description" content="Use this HTML basic website two percentage column layout template where the navigation menu and the extra stuff are at the same width on the left column, the main content is on the right column."> <meta name="generator" content="HAPedit 3.1"> <link rel="canonical" href="https://www.w3docs.com/snippets/html/layout_templates/26.html" /> <meta property="og:type" content="website" /> <meta property="og:title" content="{{name}}" /> <meta property="og:description" content="Generic ERP system" /> <meta property="og:image" content="https://www.w3docs.com/build/images/logo-amp.png" /> <meta property="og:image:type" content="image/jpeg" /> <meta property="og:image:width" content="192" /> <meta property="og:image:height" content="192" /> <meta property="og:image:alt" content="W3dcos" /> --> {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <script … -
Setting initial form field value for superuser in Django
I have form for writing comments and I want "author" field to be "admin" for default if the logged user is superuser. I also want to hide the "author" field form for the superuser. model: class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) author = models.CharField(max_length=20) text = models.TextField() publication_date = models.DateTimeField() def ___str___(self): return self.text form: class CreateComment(forms.ModelForm): class Meta: model = Comment fields = ["author", "text"] def __init__(self, *args, **kwargs): super(CreateComment, self).__init__(*args, **kwargs) ChatGPT suggested me to add this to the form: if kwargs.get("user").is_superuser: self.fields["author"].widget = forms.HiddenInput() self.fields["author"].initial = "admin" but I got this error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/14/ Django Version: 4.1.7 Python Version: 3.9.7 Installed Applications: ['mainapp.apps.MainappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Tomasz\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "C:\Users\Tomasz\anaconda3\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Tomasz\Desktop\myblog\mainapp\views.py", line 41, in article_view form = CreateComment() File "C:\Users\Tomasz\Desktop\myblog\mainapp\forms.py", line 23, in init if kwargs.get("user").is_superuser: Exception Type: AttributeError at /14/ Exception Value: 'NoneType' object has no attribute 'is_superuser' I appreciate any help, thanks. -
Django ModelForm doesnt show up
/*I made a website before and ı exactly copy paste modelform part what was before but ı m getting error on my current website */ /*This is my model, */ from django.db import models class AppModel(models.Model): name = models.CharField(max_length=50,verbose_name='Name') email = models.CharField(max_length=100,verbose_name='E-mail') subject = models.CharField(max_length=50,verbose_name='Subject') message = models.TextField(verbose_name='Message') /This is my form,/ from django import forms from App.models import AppModel class UserForm(forms.ModelForm): class Meta: model = AppModel fields = '__all__' /* This is my view, */ from django.shortcuts import render,redirect from .forms import UserForm def SupportForm(request): form = UserForm(request.POST or None) context = dict( form = form ) if form.is_valid(): newForm = form.save() return redirect('support') return render(request,'support.html',context) /* And This is my html, */ {% extends 'layout.html' %} {% load crispy_forms_tags %} {% block container %} {% load static %} <div class="container" style="height: 100vh; display: flex; justify-content: center; align-items: center;"> <div> <h2>Communicate</h2> <hr> <form method="post" action="{% url 'support' %}"> {% csrf_token %} {{ form|crispy }} <!-- {{ form.as_p }} --> <button type = "submit" value = "Submit" class = "btn btn-warning">Ekle</button> </form> </div> </div> {% endblock %} -
django rest framework simple post method with two related objects
I am trying to create a simple Django Rest Framework application storing a listening history, which consists of a ListeningHistory, a Track and an Artist model. Each ListeningHistory record is related to one track, and each track is related to one or multiple artists. If a track or an artist already exists, it should re-use that record and not try to create a new one. models.py: class Artist(models.Model): name = models.CharField(max_length=255, unique=True) #TODO: should be unique in combination w/ probably some other stuff class Track(models.Model): title = models.CharField(max_length=255, unique=True) #TODO: should be unique in combination w/ artists and album artists = models.ManyToManyField(Artist) album = models.CharField(max_length=255, null=True) class ListeningHistory(models.Model): class Meta: ordering = ['-played_at'] played_at = models.DateTimeField(unique=True) track = models.ForeignKey(Track, on_delete=models.PROTECT) serializers.py: class ArtistSerializer(serializers.ModelSerializer): class Meta: model = Artist fields = '__all__' class TrackSerializer(serializers.ModelSerializer): artists = ArtistSerializer(many=True) class Meta: model = Track fields = '__all__' def create(self, validated_data): artists_data = validated_data.pop('artists') track, created = Track.objects.get_or_create(**validated_data) artists = [Artist.objects.get_or_create(name=artist_data['name'])[0] for artist_data in artists_data] track.artists.set(artists) return track class ListeningHistorySerializer(serializers.ModelSerializer): track = TrackSerializer() class Meta: model = ListeningHistory fields = '__all__' def create(self, validated_data): track_data = validated_data.pop('track') artists_data = track_data.pop('artists') track, created = Track.objects.get_or_create(**track_data) artists = [Artist.objects.get_or_create(name=artist_data['name'])[0] for artist_data in artists_data] track.artists.set(artists) listening_history = … -
Django cannot open downloaded zip file
I want to download a note with all attached files to a zip file in Django by clicking a button. That's the view: def download_note(request, pk): note = get_object_or_404(Note, pk=pk) file_path = f'notes/media/downloaded_notes/note{note.id}.txt' notefiles = NoteFile.objects.filter(note=note) urls = [f.file.url for f in notefiles] if get_language() == 'en': content = f'Title: {note.title}, Author: {note.user}, Date: {note.add_date.strftime("%d-%m-%Y %H:%M:%S")}\n' \ f'Category: {note.category}\n' \ f'Note:\n{note.note_text}' else: content = f'Tytuł: {note.title}, Autor: {note.user}, Data: {note.add_date.strftime("%d-%m-%Y %H:%M:%S")}\n' \ f'Kategoria: {note.category}\n' \ f'Notatka:\n{note.note_text}' with open(file_path, 'w', encoding='utf-8') as f: f.write(content) zip_file_path = f'notes/media/downloaded_notes/note{note.id}.zip' with zipfile.ZipFile(zip_file_path, 'w') as zipf: zipf.write(file_path, os.path.basename(file_path)) media_root = settings.MEDIA_ROOT.replace('\\', '/') print(media_root) for url in urls: print(f'{media_root}{url[6:]}') #file_url = os.path.join(media_root, url[6:]) #zipf.write(file_url, os.path.basename(url[6:])) file_name = os.path.basename(url) zipf.write(f'{media_root}{url[6:]}', file_name) with open(zip_file_path, 'rb') as f: response = FileResponse(f.read(), content_type='application/zip') response['Content-Disposition'] = f'attachment; filename="note{note.id}.zip"' return response When I click download button Chrome hangs for few seconds and then file is downloaded. But zip file in Downloads directory is not working. When I am trying to open it there is a message saying that the file's format is invalid or file is broken. But when I go to django project and to media/downloaded_notes/note70.zip everything works fine. So I think an issue is in this fragment: with open(zip_file_path, 'rb') … -
How can I add or do some multiplcations and let my user change their CharField values in Django Application
I need an Explanation and Advice to make my small project like I would given my users "money, not real money just some numbers" and let them spend on my items and I need a way to know how can I make the money usable on the money they have like addition the money amount and subtraction on the amount of their money, I need an Advice and Explanation please. I've tried to do these things and they are not working, my mind is blowing and I need help -
How to filter an item in one queryset from appearing in another queryset in django
I have a Django view where I am getting the first queryset of 'top_posts' by just fetching all the Posts from database and cutting it in the first four. Within the same view, I want to get "politics_posts" by filtering Posts whose category is "politics". But I want a post appearing in 'top_posts', not to appear in 'politics_posts'. I have tried using exclude but it seems like it`s not working. Below is my view which is currently not working: def homepage(request): top_posts = Post.objects.all()[:4] politics_posts = Post.objects.filter(category='news').exclude(pk__in=top_posts) context={"top_posts":top_posts, "politics_posts":politics_posts} return render(request, 'posts/homepage.html', context) Any help will be highly apprecuiated. Thanks. -
how to do dependent drop down in Django
how to do dependent drop down in Django, showing errors anyone [enter image description here] (https://i.stack.imgur.com/vMzmb.png) how to get output like branches corresponding to states [enter image description here] (https://i.stack.imgur.com/fR5lj.png) is it possible without Django forms, only with views -
How can I store the response from a third party API as instance in a Django model
I am building a web API in DRF. And there's this third party API whose response returns fields like ip_address, latitude, longitude, etc. I have a user model(which is basically inherited from an AbstractBaseUser) that contains fields like email, username, first_name and last_name. Creating an instance of this user model works. But what I want to do is save response from this third party API as an instance of a model called Artist that has a OneToOneField with the user model whenever an instance of this user model is saved. How can I do this? Note: I am letting Djoser, a third party library for handling authentication, take care of the authentication endpoints on my user model. So no views involved in this project so far yet it works. -
grouping is giving wrong data if order_by is added
I have a model Lead. It has column deal_value. I want to get the count of leads for the given buckets for deal_value. Buckets are from 0 to 1000 --> '<=1000' from 10001 to 100000 --> '<=100000' So I annotate the queryset with 'bucket' and group by bucket and perform aggregation on it. below is the code: import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'design_studio_app.settings') django.setup() from dashboard.utils import get_accessible_objects_for_a_user from accounts.models import User from dashboard.qfilters import get_q_created_at from django.db.models import Case, When, CharField, Value from django.db.models import Count user = User.objects.get(pk=1529) # get the queryset queryset = get_accessible_objects_for_a_user( 'Leads', user) # get the leads which are created this month queryset = queryset.filter(get_q_created_at('this_month')) queryset = queryset.order_by('deal_value') measure_group_metric = 'deal_value' min_value = 0 max_value = 100000 queryset = queryset.filter( **{measure_group_metric+"__gte": min_value, measure_group_metric+"__lte": max_value}) case_conditions = [ When(**{measure_group_metric+"__gte": 0, measure_group_metric+"__lte": 1000}, then=Value('<=1000')), When(**{measure_group_metric+"__gte": 10001, measure_group_metric+"__lte": 100000}, then=Value('<=100000')) ] queryset = queryset.annotate( bucket=Case( *case_conditions, default=None, output_field=CharField(), ) ) annotated_data = queryset.values('bucket').annotate(count=Count('id',allow_distinct=True)) print(annotated_data) The annotated_data is <SoftDeleteQuerySet [{'bucket': '<=1000', 'count': 26}, {'bucket': None, 'count': 1}, {'bucket': '<=100000', 'count': 8}, {'bucket': '<=100000', 'count': 1}, {'bucket': '<=100000', 'count': 1}]> So the count is wrong. we can see that bucket bucket': '<=100000' is repeated. However if I remove order_by('deal_value'). … -
Problem in Django Testing with Selenium ( TypeError : expected str, bytes or os.PathLike object, not NoneType )
I am currently running a testing to check whether if there is any problem with client-side rendering in Django. Therefore, I am running a loop to visit every route available in the Django project and record the browser console. The code is as follows : class SeleniumTest2(LiveServerTestCase): def setUp(self) -> None: super(MySeleniumTests, self).setUp() User = get_user_model() self.superuser = User.objects.create_superuser('superuser', 'superuser@example.com', 'password') self.client.login(username='superuser', password='password') models = apps.get_models() factories = generate_dynamic_factories_2(models) for model_name, factory_class in factories.items(): instances = factory_class.create_batch(10) for instance in instances : instance.save() def tearDown(self): self.selenium.quit() super(MySeleniumTests, self).tearDown() if(check_library_selenium()): def test_client_side(self): urls = get_urls() driver = webdriver.Edge() live_server = self.live_server_url for url in urls: driver.get( str(live_server) + url) # Print or use the console output as needed logs = driver.get_log('browser') print(url, logs) driver.quit() else : print(RED+'Client-side checker skipped'+RESET) And the error are as follows : Traceback (most recent call last): File "/Users/zulfathihanafi/.pyenv/versions/3.9.16/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/test/testcases.py", line 1723, in __call__ return super().__call__(environ, start_response) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 124, in __call__ response = self.get_response(request) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/test/testcases.py", line 1706, in get_response return self.serve(request) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/test/testcases.py", line 1718, in serve return serve(request, final_rel_path, document_root=self.get_base_dir()) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/views/static.py", line 34, in serve fullpath = Path(safe_join(document_root, path)) File "/Users/zulfathihanafi/Desktop/Fathi/test-6/reporter/venv/lib/python3.9/site-packages/django/utils/_os.py", line 17, … -
Django Installation on Windows 10
I'm a newbie when it comes to Django framework, just want to ask if what drive is it recommended to install Django, should I follow YT vids that installs on desktop or should I put it in more specific path. Thanks As for now I haven't tried to install it, I'm still gathering opinions from experts to reduce flaws and errors in the future. :) -
django.db.utils.OperationalError: (2002, "Can't connect to server on 'mysql' (115)")
I did find some related questions, but the answers don't work. I think the problem might be the configuration problem. When I run sudo docker-compose up, it create 4 images. But the error occurs like that: rest | Performing system checks... rest | rest | System check identified no issues (0 silenced). rest | Exception in thread django-main-thread: rest | Traceback (most recent call last): rest | File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection rest | self.connect() rest | File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner rest | return func(*args, **kwargs) rest | File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect rest | self.connection = self.get_new_connection(conn_params) rest | File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner rest | return func(*args, **kwargs) rest | File "/usr/local/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 247, in get_new_connection rest | connection = Database.connect(**conn_params) rest | File "/usr/local/lib/python3.10/site-packages/MySQLdb/__init__.py", line 121, in Connect rest | return Connection(*args, **kwargs) rest | File "/usr/local/lib/python3.10/site-packages/MySQLdb/connections.py", line 193, in __init__ rest | super().__init__(*args, **kwargs2) rest | MySQLdb.OperationalError: (2002, "Can't connect to server on 'mysql' (115)") rest | rest | The above exception was the direct cause of the following exception: rest | rest | Traceback (most recent call last): rest | File "/usr/local/lib/python3.10/threading.py", line 1016, in _bootstrap_inner rest | self.run() rest …