Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM deduplication counter
class Country(models.Model): name = models.CharField(max_length=255) class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Score(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) I need the deduplicated count of city.country in the score model. canada = Country.objects.create(name="Canada") USA = Country.objects.crerate(name="USA") ottawa = City.objects.create(name="Ottawa", country=cannada) washington = City.objects.create(name="Washington", country=usd) new_york = City.objects.create(name="New York", country=usd) Score.objects.create(city=ottawa) Score.objects.create(city=ottawa) Score.objects.create(city=washington) Score.objects.create(city=new_york) I want Canada 1 point US 2 points like this. city = City.objects.annotate(point= ???) city[0].point ==> 1 city[1].point ==> 1 city[2].point ==> 1 -
How to make the links generated on sitemap with https protocol instead of http - Python script (Django framework)
I have a Python script (Django framework) it automatically generates links in sitemap but it only generates HTTP links, I want the links to be HTTPS this is what sitemap.py have from django.contrib.sitemaps import Sitemap from .models import Theme class ThemeSitemap(Sitemap): changefreq = 'weekly' priority = 0.8 def items(self): return Theme.objects.all().order_by('-id') I tried to add protocol = "https" but it did not work How can I fix that? -
reverse list in the python
I'm trying to reverse a integer and using the below code but the resultant list value in None. The code: int_a= [1,2,3,4,5,6] rev_word = int_a.split() rev_number = rev_number.reverse() rev_number= "".join(rev) it return the TypeError. Why? -
Make a Web App, With Django at the backend and using SQLite as DB and React/Angular/Vue on the front end
Assignment: Make a Web App, With Django at the backend and using SQLite as DB and React/Angular/Vue on the front end. Tables:https://easyupload.io/m/21b2yk equities returns For each equity given in the equities.csv file, there is a time series of returns in the daily_returns.csv file. Objective of App: To create a graphical time series representation of returns for any equity in the DB. Build an upload screen, which should be capable of ingesting any new equities/ returns updation for existing equities. Addition of returns to be done by upload of csv file. Screen to view all equities and returns in the DB. Feature to update/delete data should be present. Instructions: You can use any charting library which you are comfortable with. Use of rest- framework is recommended. Please upload all the work into a GitHub public repo and share the link. Please upload a proper readme to the GitHub repo with instructions to run the repo on local. Having multiple commits when creating the project is recommended to show progress of the project. link for csv file: https://easyupload.io/m/21b2yk contact:sohampal36@gmail.com -
How can I add attrs to image in the code given below
widgets = { 'img':forms.ImageInput(attrs={'class':'box'}), 'title':forms.TextInput(attrs={'class':'box'}), 'title':forms.TextInput(attrs={'class':'box'}), 'title':forms.TextInput(attrs={'class':'box'}), } 'img':forms.ImageInput(attrs={'class':'box'}), this line gives me error. -
Wrap DRF serializer constructor
Let's say I have the following Django REST Framework serializer: class MySerializer(serializer.ModelSerializer): items = serializers.SerializerMethodField() users = UserSerializer(many=True) class Meta: model = MyModel fields = ("id", "items", "users") I want to wrap the serializer constructor in queries_disabled from django-zen-queries to ensure all data has been prefetched and there are no N+1 violations. How can I do this? -
How auth variable is verifying the token?
I want to verify the token id my code its working, but why is working? i setup good? i have that doubt because auth variable does not know the credentials to verify the token, the variable who know the credentials is firebase_app, how auth variable is verifying the token? from firebase_admin import auth from django.conf import settings firebase_creds = credentials.Certificate(FIREBASE_CONFIG_credentials) firebase_app = firebase_admin.initialize_app(firebase_creds) def login(request): token = 'eyJhbGciO...' try: decoded_token = auth.verify_id_token(token) -
Django with MySQL: 'Subquery returns more than 1 row'
Using django with a MySQL DB and given these models: ModelB ---FK---> ModelA - c_id ModelC I want to get all the ModelC for each ModelA via an annotation. I tried many options looking at existing solutions but could not make it work. The following code works when there is just one ModelC for each ModelA but as soon as there is more than one, I get the Subquery returns more than 1 row error and I don't know how to get a list of the ModelC models instead. I tried to build a list of JSON objects of the ModelC without success. qs = ModelA.objects.all() c_ids = ( ModelB.objects \ .filter(modela_id=OuterRef(OuterRef('id'))) \ .values('c_id') ) all_c = ( ModelC.objects \ .filter(id__in=Subquery(c_ids)) \ .values('id') ) qs1 = qs.annotate(all_c=Subquery(all_c )) for p in qs1: print(p, p.all_c) -
IIS Django localhost opens list of directories
I am trying to deploy a Django app on IIS. After a few days of FINALLY getting HTTP Platform Handler to work now i face another problem right now when i go to local host i see a list of files in my Django app. how do i make it start the Django app right away. i am using HTTP Platform Handler. <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script" /> </handlers> <httpPlatform startupTimeLimit="10" startupRetryCount="10" stdoutLogEnabled="true" processPath="C:\Python310\python.exe" arguments="manage.py runserver"> <environmentVariables> <environmentVariable name="foo" value="bar"/> </environmentVariables> </httpPlatform> </system.webServer> </configuration> -
Can I use an annotated subquery parameter later on in the same query?
I have a Django queryset that ideally does some annotation and filtering with 3 object classes. I have Conversations, Tickets, and Interactions. My desired output is Conversations that have 1. an OPEN ticket, and 2. exactly ONE interaction, of type mass_text, since the ticket's created_at date. I am trying to annotate the conversation query with ticket_created_at & filter out Nones, then somehow use that ticket_created_at parameter in a subsequent annotation/subquery to get count of interactions since the ticket_created_at date. Is this doable? class Interaction(PolymorphicModel): when = models.DateTimeField() conversation = models.ForeignKey(Conversation) mass_text = models.ForeignKey(MassText) class Ticket(PolymorphicModel): created_at = models.DateTimeField() conversation = models.ForeignKey(Conversation) status = models.CharField() ######################################################## open_ticket_subquery = ( Ticket.objects.filter(conversation=OuterRef("id")) .filter(status=Ticket.Status.OPEN) .order_by("-created_at") ) filtered_conversations = ( self.get_queryset() .select_related("student") .annotate( ticket_created_at=Subquery( open_ticket_subquery.values("created_at")[:1] ) ) .exclude(ticket_created_at=None) .annotate(interactions_since_ticket=Count('interactions', filter=Q(interactions__when__gte=ticket_created_at))) .filter(interactions_since_ticket=1) This isn't working, because I can't figure out how to use ticket_created_at in the subsequent annotation. -
Django UUIDField shows 'badly formed hexadecimal UUID string' error?
I have written a model before and used the UUIDField and everything worked perfectly well, now i tried doing exactly the same thing but i get the error badly formed hexadecimal UUID string, i don't know if i messed something up. I have imported the uuid package and the field goes thus id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False). I have also tried adding ..., default.uuid.uuid4() BUT it does not still work, but might the problem and best fix? class Group(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False) image = models.ImageField(upload_to=user_directory_path, null=True, blank=True) channel_name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) keywords = TaggableManager() joined = models.DateTimeField(auto_now_add=True) status = models.CharField(choices=STATUS, max_length=100, default="active") user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, related_name="channel") members = models.ManyToManyField(User, related_name="user_subs") -
how i create a multi step form using installed bootstrapp5
i'm new in Django programming i want to create a multi step form using bootstrap5 I have installed bootstrap 5 using this command : pip install Django-bootstrap-v5 the problem is when i search how to create a this step form i find many solution that use Js & CSS code imported from static files like this : orm id="regForm" action=""> <h1>Register:</h1> <!-- One "tab" for each step in the form: --> <div class="tab">Name: <p><input placeholder="First name..." oninput="this.className = ''"></p> <p><input placeholder="Last name..." oninput="this.className = ''"></p> </div> <div class="tab">Contact Info: <p><input placeholder="E-mail..." oninput="this.className = ''"></p> <p><input placeholder="Phone..." oninput="this.className = ''"></p> </div> <div class="tab">Birthday: <p><input placeholder="dd" oninput="this.className = ''"></p> <p><input placeholder="mm" oninput="this.className = ''"></p> <p><input placeholder="yyyy" oninput="this.className = ''"></p> </div> <div class="tab">Login Info: <p><input placeholder="Username..." oninput="this.className = ''"></p> <p><input placeholder="Password..." oninput="this.className = ''"></p> </div> <div style="overflow:auto;"> <div style="float:right;"> <button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button> <button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button> </div> </div> <!-- Circles which indicates the steps of the form: --> <div style="text-align:center;margin-top:40px;"> <span class="step"></span> <span class="step"></span> <span class="step"></span> <span class="step"></span> </div> </form> but for my situation there is no file in static directory please can you help me -
How to go about enabling side scrolling in Wagtail admin site
I have been tackling a particular design issue with Wagtail admin. Thus far I have not found a way to enable side scrolling admin listing pages. I want to extend my user model with more data about the users (e.g., occupation, education, address, and so on). While extending Wagtail with some models for a particular project, I noticed Wagtail admin listing pages do not automatically activate sides crolling as Django admin does. I have looked at Wagtail hooks doccumentation but apparently there isn't a straightforward way to do that. I don't think it would be wise to mess with core css. Does anyone have an idea on how to customize css to enable that? See pictures below: This is how Django admin handles it. We can add filters while the table adjusts itself activating side scrolling. Wagtail Bakery demo user model has few fields. So the listing admin page does not need to side scroll. I have not tested adding filters on this page yet, but I am assuming it will work just as it did to my other models. This is how my admin page looks like when using filters. The table does not activate side scrolling and gets … -
Django annotate M2M object with field from through model
Let's say I have the following models: class Color(models.Model): name = models.CharField(max_length=255, unique=True) users = models.ManyToManyField(User, through="UserColor", related_name="colors") class UserColor(models.Model): class Meta: unique_together = (("user", "color"), ("user", "rank")) user = models.ForeignKey(User, on_delete=models.CASCADE) color = models.ForeignKey(Color, on_delete=models.CASCADE) rank = models.PositiveSmallIntegerField() I want to fetch all users from the database with their respective colors and color ranks. I know I can do this by traversing across the through model, which makes a total of 3 DB hits: users = User.objects.prefetch_related( Prefetch( "usercolor_set", queryset=UserColor.objects.order_by("rank").prefetch_related( Prefetch("color", queryset=Color.objects.only("name")) ), ) ) for user in users: for usercolor in user.usercolor_set.all(): print(user, usercolor.color.name, usercolor.rank) I discovered another way to do this by annotating the rank onto the Color objects, which makes sense because we have a unique constraint on user and color. users = User.objects.prefetch_related( Prefetch( "colors", queryset=( Color.objects.annotate(rank=F("usercolor__rank")) .order_by("rank") .distinct() ), ) ) for user in users: for color in user.colors.all(): print(user, color, color.rank) This approach comes with several benefits: Makes only 2 DB hits instead of 3. Don't have to deal with the through object, which I think is more intuitive. However, it only works if I chain distinct() (otherwise I get duplicate objects) and I'm worried this may not be a legit approach (maybe … -
How Do I Add Multiple Objects Inside A Foreign key in Django
So I've been trying to make my django view to create an author model as an instance, and then save multiple objects inside the foreign key. Any Ideas on how to do this? I have tried making a author instance, and then setting the tiktok attribute of the author instance to a new tiktok model instance with the desc, likes, etc. This just updated the previous value, not appending a new tiktok object. Models.py from django.db import models # Create your models here. class TikTok(models.Model): slug = models.SlugField(max_length=300, null=True) desc = models.TextField(max_length=500, blank=True) likes = models.CharField(default=None, blank=True, max_length=100) shares = models.CharField(default=None, blank=True, max_length=100) comments = models.CharField(default=None, blank=True, max_length=100) plays = models.CharField(default=None, blank=True, max_length=100) videoUrl = models.CharField(default=None, blank=True, null=True, max_length=500) videoImg = models.CharField(default=None, blank=True, null=True, max_length=500) music = models.CharField(default=None, blank=True, null=True, max_length=500) def __str__(self): return self.desc class Author(models.Model): userhandle = models.CharField(max_length=100, blank=True) email = models.CharField(max_length=150, null=True, blank=True) verified = models.BooleanField(null=True) followers = models.IntegerField(default=0) tiktoks = models.ForeignKey(TikTok, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.userhandle And then create the instances in my views. In other words, I want one author model, and many tiktoks associated with it. This is what the output should look like: { id: 1, userhandle: 'user' email: 'user@gmail.com' verified: … -
django template tags with async view
As soon as I add async in front of a view, my template which contains {% if request.user.is_authenticated %} causes a SynchronousOnlyOperation, You cannot call this from an async context - use a thread or sync_to_async. The error only occurs when a user is logged in. What am I not getting here? view async def test(request): return render(request, 'test.html') template, test.html {% if request.user.is_authenticated %} <script> const usr = "{{user}}"; </script> {% endif %} -
Django test for 404 erroring because Client expects 200?
I am trying to test my 404 page to ensure certain elements are present on it. My test looks like this: class TestApp404PageIncludesLink(TestCase): def setUp(self): superuser = UserFactory(is_superuser=True, is_staff=True) self.client.force_login(superuser) def test_superuser_can_see_link(self): response = self.client.get("404") self.assertTrue(response.status_code == 404) self.assertContains(response, 'href="/special_link/">Specialty</a>') I am running this test as a logged in user - other tests for other views work fine. I'm trying to check the 404 page. It fails with this: Couldn't retrieve content: Response code was 404 (expected 200) 200 != 404 How do I set up the test so it knows I am trying to get a 404? -
Django sort QuerySets
Hello iam making game administration website with django and i need help with sorting 2 queryes . These are my models.enter image description here and i need to separate from them registered game_names and unregistered game_names enter image description here I was trying to make this in template but it didnt work enter image description here Help Please <3. -
Deploying github repository to Railway showing error 'ModuleNotFoundError''
I'm trying to deploy my django application to Railway using github but receiving this error from the deployment logs 'ModuleNotFoundError: No module named 'commerce.settings'. RAILWAY DEPLOYMENT LOG > File > "/opt/venv/lib/python3.8/site-packages/django/utils/connection.py", > line 50, in configure_settings settings = getattr(django_settings, > self.settings_name) File > "/opt/venv/lib/python3.8/site-packages/django/conf/__init__.py", line > 84, in __getattr__ self._setup(name) File > "/opt/venv/lib/python3.8/site-packages/django/conf/__init__.py", line > 71, in _setup self._wrapped = Settings(settings_module) File > "/opt/venv/lib/python3.8/site-packages/django/conf/__init__.py", line > 179, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) > File > "/nix/store/xq59cyi96kny4v70flfb3ymrzmymk1k1-python3-3.8.13/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 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'commerce.settings' DEPLOYED WEBSITE ERROR Application Error Is your app correctly listening on $PORT? View the deployment below to check for errors -
django-safedelete 1.3.0 - Cannot migrate
I built an internal app that used django-safedelete. I was working fine for months, until i recently upgraded my distro, and tried to add a field to my model. I also upgraded my python modules, everything is up-to-date, and no errors during the upgrade. Now I cannot migrate anymore: if I "makemigrations" I get an error message "django.db.utils.OperationalError: (1054, "Unknown column 'gestion_ltqmappsetting.deleted_by_cascade' in 'field list'")" if I add a boolean "deleted_by_cascade" field in my ltqmappsetting table, then the "makemigration" works, but the "migrate" fails with "MySQLdb.OperationalError: (1060, "Duplicate column name 'deleted_by_cascade'")" I tried removing the field after makemigrations, but the migrate fails with the first error message. I also tried removing the "migration" operations in the 0087...migration.py file, but it does not have any impact. Is there anyway to update the migration file between the makemigrations and the migrate commands ? Thanks a lot for any help on this. jm -
Is this security concept suitable for ehealth records webapp?
I'd like to hear your opinion on my application design regarding data security. Context & Build Steps Personal electronic health records, main purpose of app is storage (read-only). The application will be used by staff. data exchange with third parties. Users will extend to external staff. Mobile App for visualisation of health records. Users will have access to their data (read-only) Stack Backend: python+django (webapplication) DB: postgresql // Divided in two groups personal data (like name, age, adress, ...) and health records (reports, lab values, ...). health records are only files, no database records in that sense (db will have path reference in on column). All of the health records are stored in the aws S3 bucket. Host: heroku + aws S3 bucket for file storage Thoughts & Considerations The app will come with a authentification and authorisation functionality. I consider the health records with higher priority regarding data security than personal data. So what I was thinking is to upgrade my heroku server with heroku shield services which would add security features server-side and make breaches from that side harder. Additionaly I would like to use the encryption service of aws bucket to encrypt all the files in the … -
no module named pars when executing python3 script directly
pars in the django app I have made under INSTALLED_APPS within settings.py When i run this python script directly from bash that includes: from django.db import models from pars.models import tbl1, tbl2, etc technologytitle=soup.find("h1").text try: technology=CMS(nm=technologytitle) technology.save() print("saved techology: {}".format(technologytitle)) except IntegrityError as e: print("Integrity error occurring with saving: {} {}".format(technologytitle, e)) Im getting an error of: ModuleNotFoundError: No module named 'pars' ive done a ton of research, but cant seem to figure out why this is happening. Thanks -
IntegrityError at / null value in column "last_name" violates not-null constraint
I have web app which includes authentication. I have form, but when I enter my credentials and click submit I get an error: IntegrityError at /accounts/professor_register/ null value in column "last_name" violates not-null constraint. view from .forms import ProfessorSignupForm class ProfessorSignup(CreateView): model = User form_class = ProfessorSignUpForm template_name = 'authentication/dubai.html' def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/') form class ProfessorSignUpForm(UserCreationForm): first_name = forms.CharField() last_name = forms.CharField() phone = PhoneNumberField() class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_professor = True user.is_staff = True user.save() professor = Professor.objects.create(user=user) professor.first_name = self.cleaned_data.get('first_name') professor.last_name = self.cleaned_data.get('last_name') professor.username = self.cleaned_data.get('username') professor.email = self.cleaned_data.get('email') professor.password = self.cleaned_data.get('password') professor.save() return user models class User(AbstractUser): is_pupil = models.BooleanField(default=False) is_instructor = models.BooleanField(default=False) class Professor(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) first_name = models.CharField(max_length=20, null=False) last_name = models.CharField(max_length=30, null=True) username = models.CharField(max_length=30, unique=True, null=True) email = models.EmailField(unique=True, null=False) password = models.CharField(max_length=60, null=False) phone_number = PhoneNumberField(null=False, blank=False, unique=True) I am using postgresql as database. I have no idea why this is happening. Every stack answer I tried to replicate gives me another error:( -
How to display data from Rest API in a template
I made an API using Django Rest Framework and I've been able to use it to create come charts using ChartJS. In the same API, after the data used for the charts I have some other data that I want to be displayed simply as a number in the same Django template, but I'm really unsure on how to do that. My API: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { (...CHARTS.JS DATA...) "total_employees": 1, "total_vehicles": 3, } I have already imported the data into the template together with the data I used for the charts. Template: <script> {% block jquery %} var endpoint = '/api/chart/data/' (Chart.JS part) var totalemployees = [] var totalvehicles = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ (Chart.JS data here...) totalemployees = data.totalemployees totalvehicles = data.totalvehicles (ChartJS stuff here...) }, error: function(error_data){ console.log("error") console.log(error_data) } }) (Other ChartJS stuff here...) {% endblock %} </script> I would like to do something like this in the template: <h3 class="text-center m-4">Total number of employees: ("total_employees" value (which in this case is 1)</h3> <h3 class="text-center m-4">Total number of vehicles: ("total_vehicles" value (which in this case is 3)</h3> -
Django Sessions Loose Data with url containing target="_blank"
In my django app, I store the current breadcrumb data (an array) in the session object. When I have a link that includes target="_blank", the session data is lost. I assume this is normal operation, but just want to check that this is true. Any suggestions on where to store the breadcrumb array if I need to retrieve it when I use target="_blank" in my urls as well as whenever a page loads? Keep in mind, the breadcrumb data is on a per user basis. Thanks!