Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid hook call - React. (Duplicated React version in app) when i try npm-link. Rollup.config
I've been stuck on this for like two days. I am trying to make a React component. But after I built the package with rollup.js, I tried to test it with the npm link, but it didn't work. Yes, I tried to use the npm link in node_modules/react in my lib and it didn't work. Thank for any suggestion. rollup.config.js import babel from 'rollup-plugin-babel'; import resolve from '@rollup/plugin-node-resolve'; import external from 'rollup-plugin-peer-deps-external'; import pkg from './package.json'; import path from 'path'; export default [ { input: 'src/index.js', external: [...Object.keys(pkg.peerDependencies)], output: [ { file: 'dist/index.js', format: 'cjs', }, { file: 'dist/index.es.js', format: 'es', exports: "named", } ], plugins: [ babel({ exclude: "node_modules/**", presets: [['@babel/preset-react', {"runtime": "automatic"}]] }), external(), resolve({ dedupe: [...Object.keys(pkg.peerDependencies)] ,moduleDirectory: path.resolve('./node_modules/react'), extensions: ['.js', '.jsx']}), ] } ] -
Reduce the number of SQL queries in a serializer with SerializerMethodField
I need to optimize a serializer with SerializerMethodField that contains a query. The query is used to retrieve information from another object (Event) which is linked by a primarykey to Sensor object. class SiteSensorSerializer(serializers.ModelSerializer): issue = serializers.SerializerMethodField() class Meta: model = Sensor fields = ('id', 'label', 'view', 'issue',) def get_issue(self, obj): return ( Event.objects.filter(sensor=obj, date_end__isnull=True) .order_by('-date_start') .exists() ) class SiteDeviceSerializer(serializers.ModelSerializer): label = DeviceLabelSerializer() sensors = SiteSensorSerializer(many=True, read_only=True) class Meta: model = Device fields = ('id', 'name', 'label', 'sensors') My issue is for each sensor, the query in get_issue method is executed. How to reduce the number of query ? My viewset: class SiteViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = (permissions.IsAuthenticated,) serializer_class = SiteSerializer filter_backends = [ DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter, ] filter_fields = [ "name", ] search_fields = ["name"] ordering = ["name"] def get_queryset(self): if self.request.user.is_superuser: return ( Site.objects.all() .prefetch_related("devices") .prefetch_related("devices__label") .prefetch_related("devices__sensors") ) else: return ( Site.objects.filter(devices__users=self.request.user) .prefetch_related( Prefetch( "devices", Device.objects.filter(users=self.request.user).select_related( "label" ), ) ) .distinct() .prefetch_related( Prefetch( "devices__sensors", Sensor.objects.filter(device__users=self.request.user), ) ) .distinct() ) -
HTMX form submission produces a duplicate form
{% extends "IntakeApp/base3.html" %} {% load static %} {% load crispy_forms_tags %} {% block heading %} <h2>Allergies for {{request.session.report_claimant}}</h2> {% endblock %} {% block content %} <form hx-post="{% url 'allergy' %}" hx-target="#allergy_target" hx-swap="outerHTML">{% csrf_token %} <div class="form-row"> <div class="form-group col-md-2 mb-0"> {{ form.allergen|as_crispy_field }} </div> </div> <button type="submit" class="btn btn-primary">Add</button> </form> <div class="container-fluid"> <table class="table table-striped table-sm" id="med-table"> <thead> <tr> <th>Allergen</th> </tr> </thead> <tbody id="allergy_target"> {% for allergy in allergy_list %} <tr> <td>{{allergy.allergen}}</td> <td> <form method="POST" action="{% url 'allergy-delete' allergy.id %}">{% csrf_token %} <input class="btn btn-danger btn-sm" type="submit" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} I tried to all the different hx-swap options, but none fix it...It does post correctly and the swap does work, just not sure why I am getting another form in there. Please help -
I installing ssl certificate in my nginx although only acess in my local server
I have a django server hosted with nginx but it does not have the ssl certificate, I did some research and tried to install the certificate on nginx, I was successful but now I can only access my domain directly from the server and before installing the certificate I could access my server by the domain from anywhere. How do I get access to the site normally from anywhere else with ssl installed, i using windows server I want to access my domain from anywhere with the ssl certificate on it -
Showing differente views with django
I'm working woth django for making a web tha shows embedded code with Power BI, and I got my sidebar, and it also shows the reports associated with the user. The problme is, how can I get the report when I click on the Reports title I'm not sure how to link it Here I will post some of my code with de principal views, models, urls and html code I aprreciate your help views.py def insertar(request): usuario = Usuario.objects.get(username=request.session\['username'\]) reportes = Reporte.objects.filter(id_usuario=usuario.id_usuario) return render(request, 'index.html', {'reportes': reportes}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.login, name='login'), path('home', views.insertar, name='index'), ] models.py from django.db import models # Create your models here. class Usuario(models.Model): id_usuario = models.AutoField(primary_key=True) username = models.CharField(max_length=50) password = models.CharField(max_length=50) class Reporte(models.Model): id_reporte = models.AutoField(primary_key=True) id_usuario = models.ForeignKey(Usuario, on_delete=models.CASCADE) titulo = models.CharField(max_length=50) link = models.CharField(max_length=350) base.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> .sidenav { height: 100%; width: 250px; position: fixed; z-index: 1; top: 0; left: 0; background-color: #21623a; overflow-x: hidden; padding-top: 20px; } .sidenav a { padding: 6px 8px 6px 16px; text-decoration: none; font-size: 20px; color: #818181; display: block; } .sidenav a:hover { color: #f1f1f1; … -
Why does Google Cloud Storage works from the cloud?
Saving files from Django to Google Cloud Storage works through my localhost; why does it break from a Google Cloud Run service container? Here are some, what I think might be, relevant facts: 403 error: it looks like something to do with permissions, but this is still in development, and the bucket still has default permissions, shown as 'Public access: Subject to object ACLs', but I haven't applied any ACLs. %2F (v. '/'): the stack trace below shows the storage path my app is passing as url-encoded, but from my localhost the directory and file are created. Here's my model object; the 'database' field includes the file: class Project(BaseModel): def database_path(project, filename): return '{0}/{1}'.format(project.id, filename) id = models.UUIDField( primary_key=True, default=uuid.uuid4) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) database = models.FileField(upload_to=database_path) I also have very plain code for the form: class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('id', 'owner', 'database', ) ... and saving the form: def store_project(request, id): try: project = Project.objects.get(id=id) except Project.DoesNotExist: # new project project = None if request.method == "POST": form = ProjectForm(request.POST, request.FILES, instance=project) if form.is_valid(): form.save() return redirect("index") else: form = ProjectForm(instance=project) return render(request, "forms/project.html", {"form": form}) Here are my Django settings for this bucket: … -
Implement a simple task management system which require APIs to :
Create tasks with fields *Title (title of task), *Description (any notes or details), *Status (1:open/not done, 2: done; default is 1), *Assigned To (user id to which task is assigned). Update status of task (1: not done, 2: completed) List users who completed all tasks Sort users list in the order of task completion Assumptions for create task API: Add some users with name, id, phone number to the database. No need for user insertion via code. You can assign multiple tasks to a user but maximum 3 tasks should be assigned in a day for a user. I didn't get the update status... -
Django app running on AWS elastic beanstalk cannot write to database
I have a Django app running on AWS elastic beanstalk. It was previously connected to a MySQL RDS instance. I have been through several steps to migrate the data from a MySQL instance to a PostgreSQL instance. In brief I connected to the postgres instance and ran python manage.py migrate I then ran python manage.py sqlflush and ran the resulting SQL commands Then I imported a json fixture of content types from the MySQL db. I created the fixture (when connected to the MySQL db) with python manage.py dumpdata contenttypes --indent=4 --natural-foreign > contenttype.json and imported it into the PostgreSQL db with python manage.py loaddata contenttype.json The above preserves PKs and FKs I then used AWS DMS to load the data from the MySQL instance to the PostgreSQL instance. Using the Django app (e.g. through Django admin) all the data can be read from the Postgres instance. However, trying to post data to the database results in a 500 error. Could this be a problem with security settings in AWS? It seems odd that I can read data from the DB but not post to it. I've tried connecting to the DB using pgAdmin 4 with the same connection settings. … -
Django ORM distinct on only a subset of the queryset
Working in Django Rest Framework (DRF), django-filter, and PostgreSQL, and having an issue with one of our endpoints. Assume the following: # models.py class Company(models.Model): name = models.CharField(max_length=50) class Venue(models.Model): company = models.ForeignKey(to="Company", on_delete=models.CASCADE) name = models.CharField(max_length=50) # create some data company1 = Company.objects.create(name="Proper Ltd") company2 = Company.objects.create(name="MyCompany Ltd") Venue.objects.create(name="Venue #1", company=company1) Venue.objects.create(name="Venue #2", company=company1) Venue.objects.create(name="Property #1", company=company2) Venue.objects.create(name="Property #2", company=company2) I now want to allow the user to filter the results by sending a query in the request, e.g. curl -X GET https://example.com/api/company/?text=pr. This is how I use the Django ORM in the viewset: from django.db import Q Venue.objects.filter(Q(name__icontains=value) | Q(company__name__icontains=value)) The serializer result will look something like: [ { "company_id":1, "company_name":"Proper Ltd", "venue_id":1, "venue_name":"Venue #1" }, { // update ORM to exclude this dict "company_id":1, "company_name":"Proper Ltd", "venue_id":2, "venue_name":"Venue #1" }, { "company_id":2, "company_name":"MyCompany Ltd", "venue_id":3, "venue_name":"Property #1" }, { "company_id":2, "company_name":"MyCompany Ltd", "venue_id":4, "venue_name":"Property #1" } ] Expected result: Want to rewrite the ORM query so that if the filter ("pr") matches the venue__name, return all venues. But if the filter matches the company__name, only return it once, thus in the example above the second dict in the list would be excluded/removed. Is this possible? -
Cannot use distinct w/ a different Order by using Django ORM
I have seen a few posts that reference this issue on Stackoverflow, but I cannot figure out how to get the business need solved, if the query changes. I am trying to get the last 10 contacts that have sent a message to the organization messages = (Message.objects.order_by('-created_at').distinct('contact_id')) However, I get this error: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("messages"."contact_id") "messages"."id"... I see that the distinct column must match the order by column, but a distinct created_at, isn't what the business needs to solve the problem. Any suggestions? -
Python Django, prefetch_related select_related for ForeignKey
There are two models: class Batch(models.Model): name = models.CharField(max_length=150) class Stage(models.Model): batch = models.ForeignKey(Batch, on_delete=models.CASCADE, related_name="stages") feild_1 = models.SmallInteterField(default=0) View: class BatchWiew(ListWiew): model = Batch template_name = index.html def get_context_data(self, **kwargs): context = super().get_context_data() context['batches'] = Batch.objects.?????????????????? index.html {% for batch in batches %} {{ batch.stages.last }} {% endfor %} 'last' in the block {{ batch.stages.last }} creates an additional query to the database for everyone 'batch'. How to immediately take the necessary data from the database to context['batches'] = Batch.objects.?????????????????? tried different options with prefetch_related, select_related it doesn't work -
Django – filter all products that have only empty variations
as the title says I'm trying to filter out all Products where all variations have a stock_quantity of 0. The variations are a separate class with a foreignkey to the Product. The related_name is set to 'variations'. Here is my attempt: Product.objects.annotate(variations_count=Count('variations')).filter(variations__stock_quantity=0) However, it seems that filters out all variations where at least one variation has a stock quantity of 0, not all of them. How can I solve this? Thanks! -
Django Templates - Add Selection boxes for Search Results
Not sure how to begin programming a change to my results template/screen... I have a search that users can use, it returns results from two related models with pagination. This works fine. Users wondered if I could add a selection box for each returned entry. If they selected 1 or more entries - then they could then push an export button, and all selected entries would be saved into a file with all fields listed in csv format. The more I think about it I think I would need a completely different results template without pagination, just because I need to pass the query set to something to print this out, but only want the ones that were selected... Anyone done anything like this? Not really sure if any will have an answer but figured I would put it out there. Thanks. -
Periodically and automatically create objects in Django
I am looking for a way to automatically and periodically (once per week) create objects in Django. The model looks like this: class SettingsWeekly(models.Model): year = models.IntegerField() week_number = models.IntegerField() fuel_cost = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) miles_per_galon = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) week_start = models.DateField() week_end = models.DateField() The idea is to have a new object each week with the current year, week number and some fields that will have values added after the object is automatically created. Thanks! I can get the current year and week_number, but how do I go about automatically creating objects once per week? -
Auth0 react native gives invalid tokens
I am developing an application with a React Native application and a Django Rest Framework backend. Now, when users are authenticated in React Native, and I use the getCredentials() function from the useAuth0() hook, I get an accessToken and an idToken. However, both of these tokens are unable to authenticate in the Django REST framework application, returning the following: { "detail": "Invalid token." } I followed this tutorial to integrate Auth0 with django. Maybe this has something to do with the fact that the Django api is registered as an API in Auth0 and that it has an identifier? Because this identifier is nowhere mentioned in the React native client. Any help/insights are appreciated. -
Django Admin Button: How to pass values from many-to-many through a button to a function?
New to programming, Python, and Django. I've written a standalone function that works well enough that generates a schedule for a tennis doubles league using a list of players, the number of courts available, and a duration, which right now I just print out as a CSV and send out to the league. My goal is to create an admin portal that generates the schedule based on league and player information created in an admin portal and ultimately have that schedule stored in a SQL db and ultimately accessed via a public portal. My immediate issue is that I'm unable to figure out how to pass (or print for that matter) the list of players in my league session. Additionally, I'm not sure exactly how to pass the required information from my admin site through the button to my function. Here's a screenshot of my LeagueSession admin page: As you can see, I've created a button and am printing some of the data I need. I can't get the playersinsession to print. Ultimately I need to pass this as a list, I think. So while printing this list would be a great start, I also need help with passing all … -
Implementing an agent in python/django
I would like to implement an agent with django / python which will interact with an external database, this agent will have to collect the data from the external database and will save it on the database of my application. Need help I need information about its implementation please, or a sample code. -
Django url template tag ovrwrite the last letter of the base address
When using the URL template tag I checked the source code of the html page and the url appears missing the last letter of the base address, see an example: ... <li><a href="{% url 'produtct' %}">Produtcts</a></li> ... returns ... <li><a href="/dec/produtct/">Produtcts</a></li> ... but the the base address is my-site.com/deck ... so, why dont returns ... <li><a href="/deck/produtct/">Produtcts</a></li> ... I checked my settings.py and urls.py and didn't see anything wrong, I don't know where else to look -
Atomic block django [closed]
Preciso desenvolver uma rotina no python utilizando django, onde, vou ter um block atomico que nele será efetuado algumas operações no banco e dentre elas, a criação de um registro especifico em uma determinada tabela no banco de dados que, se ocorrer qualquer erro nessa rotina, quero fazer o rollback de tudo menos da criação deste registro em especifico. Exemplo: def function_teste: with transaction.atomic(): obj_a.save() obj_b.save() with transaction.atomi(): obj_c.save() obj_d.save() raise #Neste ponto, ao gerar a exceção quero fazer o rollback apenas dos regisotr a, b, d. O re Obs.: Não consigo incluir um tratamento de excção dentro da function_teste para tratar a exceção e trabalhar com save points ou algo do tipo, pois, esse exmplo está bem simplicado. E na prática o que vai acontecer é que dentro da fuction_teste eu irei chamar diversas rotinas encadeadas que dentro dela vai ter a criação desse registro c e, quando o fluxo retornar para o método externo (function_teste) e ai ocorrer qualquer raise, eu preciso fazer rollback de tudo menos do registro c. O que quero implementar seria a mesma ideia de ter um autonomous transaction do oracle. Onde tenho uma transação e dentro dela cosigo fazer o commit de um … -
Django form widget - Add suffix while keeping the NumberInput
I have a form input on body height. I would like to put 'cm' after the height number (e.g. 183cm instead of just selecting 183) but keep it as a NumberInput. Is it possible to add the suffix in the widget? I have the following form.py: from django import forms from .models import Account class RegistrationForm(forms.ModelForm): body_height = forms.NumberInput(attrs={'min':120,'max':230,'step':1, 'required':False,}) class Meta: model = Account fields = ['body_height','otherfields'] def __init__(self, *args, **kwargs): self.fields['body_height'].widget.attrs['placeholder'] = 'Your height (centimeters)' -
How to assign default value of the model based on the value of ForeignKey
I have the Account model were I store information about preferred units. However I also want to allow user to change the units for particular exercise which by default should be Account.units. Here are my models: class Account(models.Model): """Model to store user's data and preferences.""" UNIT_CHOICES = [ ('metric', 'Metric'), ('imperial', 'Imperial') ] uuid = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=False) units = models.CharField(max_length=255, choices=UNIT_CHOICES, default=UNIT_CHOICES[0], null=False, blank=False) weight_metric = models.FloatField(null=True, blank=True) height_metric = models.FloatField(null=True, blank=True) weight_imperial = models.FloatField(null=True, blank=True) height_imperial = models.FloatField(null=True, blank=True) def __str__(self): return self.owner.email class CustomExercise(models.Model): UNIT_CHOICES = [ ('metric', 'Metric'), ('imperial', 'Imperial') ] uuid = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(Account, on_delete=models.CASCADE, null=False, blank=False) preferred_units = models.CharField(max_length=255, choices=UNIT_CHOICES, default=owner.units, null=False, blank=False) # <- throws an error that "ForeignKey doesn't have units attribute." name = models.CharField(max_length=255, null=False, blank=False) measure_time = models.BooleanField(default=False) measure_distance = models.BooleanField(default=False) measure_weight = models.BooleanField(default=False) measure_reps = models.BooleanField(default=False) def __str__(self): return f'{self.owner}:{self.name}' As posted in code sample I tried to get that default value from ForeignKey, which not unexpectedly did not work out. So my question is: what is the correct solution to implement this kind of feature? -
VsCode not Auto-importing Django depenencies
I'm learning Django and working with VsCode. In PyCharm, the imports are working fine. PyCharm importing However in VsCode: VsCode importing Is VsCode just not capable of this? Or is there something iffy with my configuration? I have the correct Python interpreter configured as well. I have Pylance installed and it suggests imports automatically for some other things, rather unhelpfully usually. e.g., VsCode importing unhelpful I have tried settings some options in settings.json. The python.analysis.extraPaths adding the path to django on the Python installation. I have tried python.analysis.indexing set to true as well. I haven't found any other solutions. -
Django APIView: how to display calculated value
I have to display a calculated value in APIVIEW, but I can't figure out how to set up the view, it's giving me an error. The code, that returns a simple JSON is working fine: def protein_coverage(request, protein_id): try: proteins = Protein.objects.filter(protein=protein_id) domain_length = 0 coverage = domain_length / protein_length except Protein.DoesNotExist: return HttpResponse({'message': 'This Protein does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ProteinCoverageSerializer(coverage) return JsonResponse(serializer.data,safe=False) I tried this for the APIView: class ProteinCoverage(generics.RetrieveAPIView): serializer_class = ProteinCoverageSerializer def get_queryset(self): pk = self.kwargs['protein_id'] proteins = Protein.objects.filter(protein=pk) domain_length = 0 coverage = domain_length / protein_length return coverage But it's giving me an error: Expected view ProteinCoverage to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. I'm not sure, which API is suitable for this situation and how to pass a single variable to it. I also checked the documentation, but it's not clear. How do I convert this JsonResponse to APIView? -
Making Password First name in signup page in Django [closed]
Is there a way to not show password in the signup page and make the password the first name by default in Django and they will be able to login with that default password which is there first name I tried using the AbstractBaseUser But it did not Work -
Create multiple model instances upon creation of another model
What I am trying to achieve is the following: The user searches for a keyword in a form. The search query is saved in a model called TweetSearch. When the search is submitted a function get_tweets() will be run which scrapes tweets with the keyword that the user submitted. These tweets must be saved in a model called TweetInstance. Then some data from TweetInstance is shown in a dashboard. I don't know how to create instances of multiple models in one view, so I added a view in between the searchform and the dashboard that runs the function get_tweets() and adds them to the database. This does not work well and there must be a better way to do this. Can anyone help me? I tried the following: models.py: class TweetSearch(models.Model): from datetime import datetime, timedelta search_term = models.CharField(max_length=200, blank=True) QUERY_CHOICES = ( ('t', 'in tweet'), ('h', 'in hashtag'), ('u', 'username'), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4) query_type = models.CharField(max_length=1, choices=QUERY_CHOICES, blank=True, default='t') start_default = datetime.now() - timedelta(days=30) start_date = models.DateTimeField(default=start_default) end_date = models.DateTimeField(default=datetime.now) language = models.CharField(max_length=200, blank=True, null=True) country = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=200, blank=True, null=True) searcher = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): …