Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CBV: How come my child method is not overriding my parent method?
I'm pretty new when it comes to python classes / django CBVs. I'm trying to have a method (print_test) from my child class override my parent class, but I can't get it to work. What am I doing wrong? Below is my parent: This is my child: I've tried a bunch of things but can't see to get it to work :/ Appreciate all help! -
Django - Save form fields while paging
This will be a lengthy post, please have patience with me, I just started with Django and try to wrap my head around it. I created a site that will go thru exam questions one at a time, displaying the question and the multiple choice answers like on countless other websites. The challenge I experience is when the user clicks "NEXT" on the pagination buttons, I would like for the selected answer(option) to be saved back to the database. I tried it with AJAX scripts but the view never got executed. Maybe there is a better way to do this or could you please point me into the right direction? I will post all of my code and hope someone can please assist me. Thank you for taking the time to look at this. I start with the models.py: from django.db import models class QuesModel(models.Model): question = models.TextField(null=True) code_snippet = models.TextField(null=True) op1 = models.CharField(max_length=200,null=True) op2 = models.CharField(max_length=200,null=True) op3 = models.CharField(max_length=200,null=True) op4 = models.CharField(max_length=200,null=True) ans = models.CharField(max_length=200,null=True) def __str__(self): return self.question class Answer(models.Model): ans_id = models.AutoField(primary_key=True) question_id = models.ForeignKey(QuesModel, on_delete=models.CASCADE) fname = models.CharField(max_length=50) lname = models.CharField(max_length=50) examdate = models.DateField(auto_now_add =True) answer = models.PositiveSmallIntegerField() def __int__(self): return QuesModel.question[self.question_id] template is home.html: {% … -
Target Specific Members of the User Class
I have a Quote Model where I want to restrict members of the 'rep' dropdown list to a subgroup of Users. How do I restrict the Profile foreign key to only those members with Group 'Account' membership? class CustomerQuote(models.Model): quote_no = models.IntegerField(unique=True, blank=True, null=True, verbose_name="record") date_created = models.DateField(auto_now=False, blank=True, null=True, verbose_name="Date Created") rep = models.ForeignKey(Profile, on_delete=models.DO_NOTHING) ... -
Request Errors with fetch API
I'm trying to send data through a form with just one field to my Django API, then read and use the data received in the API for other things. I don't want to store the data, just use it. This is my react code: const handleSubmit = async (e) => { e.preventDefault(); try{ let res = await fetch(api,{ method: 'POST', headers: {'Content-Type':'application/json'}, body: { url: url, }, }); let resJson = await res.json(); if(res.status === 200){ console.log(resJson) setUrl(""); setMessage("Success"); } else{ setMessage("Error"); } }catch(err){ console.log(err); } }; This is my Django view.py @api_view(['POST']) def eda(request): response = { 'result': 'lalala', 'url':request.POST['body'], 'code': 'success' } return Response(response) I don't understand what's wrong, but I get bad request error or unsupported media type error. -
Using a custom model for Django Admin
I have a custom user model, which an admin model inherits: class User(AbstractBaseUser, PermissionsMixin): ... class Staff(User): is_staff = models.BooleanField( _("staff status"), default=True, help_text=_("Designates whether the user is staff"), ) ... class Admin(Staff): is_admin = models.BooleanField( _("staff status"), default=True, help_text=_("Designates whether the user can log into this admin site."), ) ... As well as a custom backend for authorization class AdminBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(Admin.USERNAME_FIELD) if username is None or password is None: return try: user = Admin._default_manager.get_by_natural_key(username) except Admin.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). Admin().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user ... However, I am unable to log in due to has_permission in admin/sites.py Is there a way to avoid registering a custom site, as that will increase complexity? -
Django : Getting the image URL of elements in a table that has a many-to-one relationship with another table
I have an Event model that is linked to other tables with foreign keys. I want to focus on only the Circuit model: class Event(models.Model): game = models.ForeignKey(Game, verbose_name='Nom du jeu', null=True, on_delete=models.SET_NULL) race_type = models.CharField(verbose_name="Type d'événement", max_length=50, choices=type_course) league = models.ForeignKey(League, verbose_name='Ligue', null=True, on_delete=models.SET_NULL) circuit = models.ForeignKey(Circuit, verbose_name='Circuit', null=True, on_delete=models.SET_NULL) event_date = models.DateTimeField(verbose_name="Date de la course") class Circuit(models.Model): name = models.CharField('Circuit', max_length=120) country = models.CharField('Pays', max_length=120, choices=country_choices) image = models.ImageField(blank=True) I also show here another model that I use in the HTML template : class Game(models.Model): name = models.CharField('Nom du jeu', max_length=100) logo = models.ImageField('Logo', blank=True) And there is the HTML template and the view associated : View : def home(request): games = Game.objects.all() return render(request, 'base_site/home.html', context={'title': 'Accueil', 'games': games}) HTML : {% for game in games %} <h3>{{ game.name }}</h3><br> <div class="row"> {% for event in game.event_set.all %} <div class="col-lg-4 mb-2 mt-2"> <div class="card"> <a href=""><img src="{{ event.image.url }}" class="card-img-top" alt="img-circuit" style="background-color: rgb(255, 255, 255)"></a> <div class="card-body"> <h5 class="card-title"><a href="">{{ event.circuit }}</a></h5> <h6 class="card-title">{{ event.event_date }}</h6> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> </div> <div class="card-footer"> <p>{{ event.ligue }}</p> </div> … -
Changing the CSS on the Django admin page
I am trying to change the admin HTML templates but I don't really now how to find the already created Django templates in the first place. Is there an easy way to find all the templates? Right now I am making new html templates and extending them to Djangos templates. -
Handle divide by zero with aggregated fields in Annotate expression
Currently within the following query, win_rate will always default to 0 unless Lost is 0- in that case, win_rate becomes 100. How do I properly allow division of the aggregated fields while avoiding the division by zero error? top_markets = list(opps .annotate(name=Subquery(Market.objects.filter(id=OuterRef('market'))[:1].values('marketname'))) .order_by('name') .values('name') .annotate(opps=Count('id', filter=Q(datecreated__range=(start_date, end_date))), Won=Count( 'id', filter=Q(winloss='Won') & Q(date_closed__range=(start_date, end_date))), Lost=Count('id', filter=Q(winloss='Lost') & Q( date_closed__range=(start_date, end_date))), Concluded=F('Won') + F('Lost')) ) .annotate( win_rate=Case( When(Won=0, then=0), default=((F('Won')) / \ (F('Won')) + F('Lost'))) * 100 ) -
Django .url not showing image in template
I was getting tired of figuring out how to fix this problem. I checked a lot of different posts and answers but nothing helped me. I have a form where I'm creating new advert. I have file input there for Image. Form is valid and everything works fine, but my problem is that when I want to display my image from Advert model then it's not showing on website.. even the alt text. My template code: {% for advert in adverts %} <img src="{{ advert.get_image }}" alt="test"/> <div class="col-lg-4 col-md-6 col-sm-6"> <div class="mb-4 card"> <div id="second-advert" class="carousel slide"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{{ advert.get_image }}" alt="test"/> </div> </div> My urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('carapp.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My settings.py: STATIC_URL = 'carsearch/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] My models.py: class Advert(models.Model): def get_image(self): if self.featured_image and hasattr(self.featured_image, 'url'): return self.featured_image.url else: return '/path/to/default/image' owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) [...] <-- there's more code featured_image = models.ImageField(null=True, blank=True, default='profiles/user.png', upload_to='adverts/') [...] <-- there's more code def … -
uvicorn, Nginx, and Django Error TypeError: ASGIHandler.__call__() missing 1 required positional argument: 'send'
I am configuring uvicorn, Nginx and Django to run uvicorn and it runs Django, the problem running the uvicorn server gives me the following error: ASGIHandler.call() missing 1 required positional argument: 'send' server { listen 80 default_server; listen [::]:80 default_server; # SSL configuration # # listen 443 ssl default_server; # listen [::]:443 ssl default_server; # # Note: You should disable gzip for SSL traffic. # See: https://bugs.debian.org/773332 # # Read up on ssl_ciphers to ensure a secure configuration. # See: https://bugs.debian.org/765782 # # Self signed certs generated by the ssl-cert package # Don't use them in a production server! # # include snippets/snakeoil.conf; root /var/www/html; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name _; location / { include proxy_params; proxy_pass http://unix:/run/backend.sock; } -
Is there a way to reload a Django template screen using the previous request data to an API call?
I built a simple weather app utilizing the OpenWeatherMap API using Python/Django and Django Templates for the client side. I created a refresh button in the <div class="info-grid"> using an <a href="{{ request.get_full_path }}"> and <img> tag, which is intended to refresh to the most current weather information for the currently queried city, but when I click on it, it refreshes the page and shows the weather info for the default city, which I set it to 'Chicago' in views.py. Is there a way to set the refresh button to show the weather info for the currently queried city and not the default city? views.py : def index(request): configure() if 'city' in request.POST: city = request.POST['city'] else: city = 'Chicago' appid = os.getenv('OPEN_WEATHER_API_KEY') URL = 'https://api.openweathermap.org/data/2.5/weather' PARAMS = {'q': city, 'appid': appid, 'units': 'imperial'} r = requests.get(url=URL, params=PARAMS) if r: print(f"==> SUCCESS!: Here's the weather information for {city}. <==") elif city == '': messages.info( request, f'Please enter a city or country.') print( f'!!==> ERROR: User submitted an empty field. <==!!') return redirect('/') else: messages.info( request, f"'{city}' does not exist! Please check your spelling and try searching for a different city or country.") print( f"!!==> ERROR: User entered '{city}'. This value … -
DRF Grant Type Convert Token
I'm trying to implement an authentication system in my Django backend through the Oauth2 protocol. Also, I'm using the drf_social_oauth2 lib. However, I'm having a hard time understanding how I can reproduce the auth system in Postman. Postman offers some auth flows (Grant Types) which greatly facilitates the authentication process. However I came across an authentication flow I've never heard of ( convert_token ). I wish to use the oauth2 system to authenticate using the Facebook Provider, but its not clear for me the flow to validate this in Postman. this is the snippet of code send to validate the access token in react: import axios from 'axios'; import { useHistory } from 'react-router-dom'; const facebookLogin = (accesstoken) => { console.log(accesstoken); axios .post('http://127.0.0.1:8000/auth/convert-token', { token: accesstoken, backend: 'facebook', grant_type: 'convert_token', client_id: '05GYopkyMDxFakgCSuNtpOLrNcyJwU054wZfYBt1', client_secret: 'U3r3rmtff7t52Xa1chfzGf5vtl06zr4PwGbi8sWBcilTKs0YJEm278JPmXbcgMsyYpxYMQbDKFsyjhrzKwDLW8VMfW0ePZmrRuSmssnFPvqjeodYsNTfObTAzxOxZKuH', }) .then((res) => { localStorage.setItem('access_token', res.data.access_token); localStorage.setItem('refresh_token', res.data.refresh_token); }); }; export default facebookLogin; I am expecting to do the same into Postman -
How to call in the google books API in django?
The books are being displayed but when i click on the link it does not lead to the google books.co.in webpage where the book is stored, it displays that the page is not found. my views.py def books(request): if request.method == "POST": form=DashboardForm(request.POST) text=request.POST['text'] url="https://www.googleapis.com/books/v1/volumes?q="+text r = requests.get(url) answer = r.json() result_list = [] for i in range(10): result_dict = { 'title':answer['items'][i]['volumeInfo']['title'], 'subtitle':answer['items'][i]['volumeInfo'].get('subtitle'), 'description':answer['items'][i]['volumeInfo'].get('description'), 'count':answer['items'][i]['volumeInfo'].get('pageCount'), 'categories':answer['items'][i]['volumeInfo'].get('categories'), 'rating':answer['items'][i]['volumeInfo'].get('pageRating'), 'thumbnail':answer['items'][i]['volumeInfo'].get('imageLinks').get('thumbnail'), 'preview':answer['items'][i]['volumeInfo'].get('previewLinks') } result_list.append(result_dict) context={ 'form' : form, 'results' :result_list } return render(request,'dashboard/books.html',context) else: form=DashboardForm() context={'form' : form} return render(request,'dashboard/books.html',context) my books.html template {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <section class='text-center container'> <h2><b>SEARCH FOR BOOKS </b></h2> <p>Enter the search query to obtain your desired book</p><b></b> <form action="" method="post"> {% csrf_token %} {{form}} <input class="btn btn-danger" type="submit" value="Submit"> </form><br> {% for result in results %} <a href="{{result.preview}}" target="_blank"> <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-3"> <img class="img-fluid" src="{{result.thumbnail}}" alt=""> </div> <div class="col-md-9"> <h3 class="p-0 m-0">{{result.title}}</h3> <b> <u> <h5 class="p-0 m-0">{{result.subtitle}}</h5> </u> </b> {% if result.description %} <h6 class="p-0 m-1">{{result.description}}</h6> {% endif %} <b> {% if result.categories %} <h6 class="ml-0 mt-3">Category: {% for category in result.categories %} {{category}} {% endfor %} </h6> {% endif %} {% if result.count … -
Fitting rows and columns in the same table so they line up nicely
I would like to use two different <thead>'s in the same table but i want them stacked nicely. The way it is now, the first heading has 1 less column then the 2nd one so it looks funky. If there is a way to expand that first heading out so that there isnt a space to the right of it, that would be great. Or maybe you know of a better way of tackling this problem. Here is how the table looks right now. and here is the code that i am using to get this result <div class="hidden" id="part-req-section"> <form method="post" name="partForm" id="partForm"> {% csrf_token %} <div class="row"> <div class="container"> <div class="row"> <div class="container"> <div class="table-responsive"> <h3>Part Request</h3> <table class="table table-bordered table-hover table-responsive"> <thead> <tr> <th scope="col">Part name*</th> <th scope="col">Quantity*</th> <th scope="col">Reason*</th><br> </tr> </thead> <tbody id="part-req-form-list"> {{ part_request_formset.management_form }} {% for some_form in part_request_formset %} <tr id="part-req-form" class=""> <td>{{ some_form.part|as_crispy_field }}</td> <td>{{ some_form.quantity|as_crispy_field }}</td> <td>{{ some_form.reason|as_crispy_field }}</td> <tr> {% endfor %} <thead> <tr> <th scope="col">Aisle*</th> <th scope="col">Column*</th> <th scope="col">Shelf*</th> <th scope="col">Bin*</th> </tr> </thead> <tr> <td>{{ location.aisle|as_crispy_field }}</td> <td>{{ location.column|as_crispy_field }}</td> <td>{{ location.shelf|as_crispy_field }}</td> <td>{{ location.bin|as_crispy_field }}</td> </tr> <tr id="empty-part-req-form" class="hidden"> <td>{{ part_request_formset.empty_form.part|as_crispy_field }}</td> <td>{{ part_request_formset.empty_form.quantity|as_crispy_field }}</td> <td>{{ part_request_formset.empty_form.reason|as_crispy_field }}</td> … -
Nextjs With Django Content Security Policy (CSP)
In a project where Nextjs is used as a frontend and Django is used as a backend api, where should the Content Security Policy (CSP) be set? Ive seen in examples that csp rules can be set in nextjs in the next config file and in django it can be set in the settings.py I am still trying to wrap my head around csp and security related things in general. Not sure if this matters but I am not using the api features in Nextjs, only django as an api. -
Django Channels error when trying to create a web-socket connection ValueError: No route found for path ' '
I am working on a django chat application using django-channels and websockets. I have been following a tutorial whereby the instructor is creating a one to one chat between two users. In his example, the instructor is using the URLRouter but I have used the websocketurlpatterns. the error I am getting states ValueError: No route found for path 'ws/chat/' and the websocket connection is not established. Here is my consumers.py: class ChatConsumer(SyncConsumer): def websocket_connect(self, event): me = self.scope\['user'\] other_username = self.scope\['url_route'\]\['kwargs'\]\['username'\] other_user = User.objects.get(username=other_username) self.thread_obj = Thread.objects.get_or_create_personal_thread(me, other_user) self.room_name = f'presonal_thread\_{self.thread_obj.id}' async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name) self.send({ 'type': 'websocket.accept' }) print(f'\[{self.channel_name}\] - You are connected') def websocket_receive(self, event): print(f'[{self.channel_name}] - Recieved message - {event["text"]}') msg = json.dumps({ 'text': event.get('text'), 'username': self.scope['user'].username }) self.store_message(event.get('text')) async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type': 'websocket.message', 'text': msg } ) def websocket_message(self, event): print(f'[{self.channel_name}] - Message sent - {event["text"]}') self.send({ 'type': 'websocket.send', 'text': event.get('text') }) def websocket_disconnect(self, event): print(f'[{self.channel_name}] - Disonnected') async_to_sync(self.channel_layer.group_discard)(self.room_name, self.channel_name) def store_message(self, text): Message.objects.create( thread = self.thread_obj, sender = self.scope['user'], text = text ) class EchoConsumer(SyncConsumer): def websocket_connect(self, event): self.room_name = 'broadcast' self.send({ 'type': 'websocket.accept' }) async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name) print(f'\[{self.channel_name}\] - You are connected') def websocket_receive(self, event): print(f'[{self.channel_name}] - Recieved message - {event["text"]}') async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type': 'websocket.message', 'text': … -
Django + AJAX comments
I'm trying to implement a comment system without reloading the page, but it doesn't work. Comments are inserted only after the page is reloaded, but AJAX does not work. <!-- COMMENT --> <div class="comment-section"> <form action="{% url 'love:comment_urls' %}" method="POST" class='comment-form'> {% csrf_token %} <input type="hidden" name="post_id" value={{i.pk}}> {{ comment_form }} <button type="submit" name="submit_c_form"> Опубликовать </button> </form> </div> <hr> <div class="comment_set"> {% if i.quotes_comment.all %} {% for com in i.quotes_comment.all %} <b>{{ com.user }}:</b> {{ com.body }} {% endfor %} {% endif %} </div> </div> JS code // COMMENT $(document).ready(function () { $('.comment-form').submit(function () { event.preventDefault(); console.log($(this).serialize()); var url = $(this).attr('action') $.ajax({ type: 'POST', url: url, data: $(this).serialize(), dataType: 'html', success: function (response) { console.log('Заработало') $('.comment-section').html(response['form']); }, error: function (rs, error) { console.log(rs, error) } }) }) }) As I said, comments are inserted only after a reboot, but when I click publish, nothing happens. If you change the dataType to 'json', the parser error pops up. Can you explain what I'm doing wrong? -
How can i display my products in Django template?
html file This is my html file and I want to render out my products in this template. But I do know How can I apply loop? <!-- featured-start --> <section class="featured light-bg pt-50 pb-40"> <div class="container custom-conatiner"> <div class="row"> <div class="col-xl-12"> <div class="section__head d-flex justify-content-between mb-30"> <div class="section__title section__title-2"> <h5 class="st-titile">Top Featured Products</h5> </div> <div class="button-wrap button-wrap-2"> <a href="product.html">See All Product <i class="fal fa-chevron-right"></i></a> </div> </div> </div> </div> <div class="row"> <div class="col-xl-6 col-lg-12"> <div class="single-features-item single-features-item-d b-radius-2 mb-20"> <div class="row g-0 align-items-center"> <div class="col-md-6"> <div class="features-thum"> <div class="features-product-image w-img"> <a href="product-details.html"><img src="assets/img/features-product/fpsm-1.jpg" alt=""></a> </div> <div class="product__offer"> <span class="discount">-15%</span> </div> <div class="product-action product-action-2"> <a href="#" class="icon-box icon-box-1" data-bs-toggle="modal" data-bs-target="#productModalId"> <i class="fal fa-eye"></i> <i class="fal fa-eye"></i> </a> <a href="#" class="icon-box icon-box-1"> <i class="fal fa-heart"></i> <i class="fal fa-heart"></i> </a> <a href="#" class="icon-box icon-box-1"> <i class="fal fa-layer-group"></i> <i class="fal fa-layer-group"></i> </a> </div> </div> </div> <div class="col-md-6"> <div class="product__content product__content-d product__content-d-2"> <h6><a href="product-details.html">Samsang Galaxy A70 128GB Dual-SIM</a></h6> <div class="rating mb-5"> <ul class="rating-d"> <li><a href="#"><i class="fal fa-star"></i></a></li> <li><a href="#"><i class="fal fa-star"></i></a></li> <li><a href="#"><i class="fal fa-star"></i></a></li> <li><a href="#"><i class="fal fa-star"></i></a></li> <li><a href="#"><i class="fal fa-star"></i></a></li> </ul> <span>(01 review)</span> </div> <div class="price d-price mb-10"> <span>$307.00 <del>$110</del></span> </div> <div class="features-des mb-25"> <ul> <li><a href="product-details.html"><i class="fas fa-circle"></i> Bass and Stereo … -
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...