Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send message from celery task to django channels and then notify the Ui once it's done
The django application that am working on has a celery task that's getting executed in the background. I need django-channels to let the browser know once the celery task is completed. I read the documentation for channels and got confused with the urlpatterns and routing.py modules. It would be of great help if someone could help me giving a clear picture of modules that I should use in my application. -
Are locked records from Django select_for_update affected by updated values
I know that select_for_update locks the records that are being queried if we have more than one concurrent user. But does it also affect the evaluation of the queried records. For example, if user A and user B Query the table 'Jobs' at the same time based on a single variable 'Available' which is a Boolean. Both users would like to access records of available jobs (where Available = True). User A managed to be queued first and the records he is accessing are now locked for user B. If user A changes all records to False, does user B not get any records? Or does he get the same records as user A but with Availability equal to False? Also, does select_for_update() work with MySQL? Or does it have a different solution for concurrent queries? -
django-filter SQLite3 DateRanges with Startdate and Enddate
At the moment I'm working on a Django webapplication which is supposed to search through a database with historical persons. These persons had offices. Here are the models: class Person(models.Model): Sortiername = models.CharField(max_length=100) Ansichtsname = models.CharField(max_length=200) Erste_Erwaehnung = models.CharField(max_length=100) GND = models.CharField(max_length=100) Wikidata = models.CharField(max_length=100) Bemerkung = models.CharField(max_length=2500) class Amt(models.Model): Person = models.ForeignKey(Person, on_delete=models.CASCADE) AmtDeutsch = models.CharField(max_length=50) AmtLatein = models.CharField(max_length=50) Klerus = models.CharField(max_length=10) Ort = models.ForeignKey(Ort, on_delete=models.CASCADE) AmtStart = models.DateField() AmtEnde = models.DateField() I built this filter using django-filters, which allows me to filter the persons by all the necessary parameters: class PersonFilter(django_filters.FilterSet): Ansichtsname = django_filters.CharFilter(lookup_expr='icontains', label='Name') get_aemter_dt = Amt.objects.all() aemter_dt_lst_1 = [] for amt in get_aemter_dt: if amt.AmtDeutsch != "nicht vorhanden": aemter_dt_lst_1.append((amt.AmtDeutsch, amt.AmtDeutsch)) aemter_dt_lst_2 = sorted(list(set(aemter_dt_lst_1))) aemter_dt_tpl = tuple(aemter_dt_lst_2) amt__AmtDeutsch = django_filters.ChoiceFilter(lookup_expr='icontains', label="Amt (Deutsch)", choices = aemter_dt_tpl) get_aemter_lat = Amt.objects.all() aemter_lat_lst_1 = [] for amt in get_aemter_lat: if amt.AmtLatein != "nicht vorhanden": aemter_lat_lst_1.append((amt.AmtLatein, amt.AmtLatein)) aemter_lat_lst_2 = sorted(list(set(aemter_lat_lst_1))) aemter_lat_tpl = tuple(aemter_lat_lst_2) amt__AmtLatein = django_filters.ChoiceFilter(lookup_expr='icontains', label='Amt (Latein)', choices = aemter_lat_tpl) get_functions_dt = Funktion.objects.all() functions_dt_lst_1 = [] for function in get_functions_dt: if function.Name != "nicht vorhanden": functions_dt_lst_1.append((function.Name, function.Name)) functions_dt_lst_2 = sorted(list(set(functions_dt_lst_1))) function_dt_tpl = tuple(functions_dt_lst_2) funktion__Name = django_filters.ChoiceFilter(lookup_expr='icontains', label='Funktion (Deutsch)', choices = function_dt_tpl ) get_functions_lat = Funktion.objects.all() functions_lat_lst_1 = [] for function in … -
How to overwrite create view for adding a function like activity stream
I have a create view function for creating new products for sale and also a create_action function for activity stream. I know how to integrate this function to a function based view but don't know how can I implement the same to a class view. Here are the codes. class CreateProductView(CreateView, LoginRequiredMixin): model = Product template_name = 'store/product/product_form.html' form_class = CreateProductForm success_message = 'Posted' success_url = reverse_lazy('store:store_home') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) This is the create_action for activity stream: create_action(request.user, 'verb', ??) what should I add to the target? I am not saving any object here. So pretty confused. Thanks in advance! -
How to collect broserInfo using Python
I'm currently working with Python Flask and would like to understand how can I dynamically collect the following: "browserInfo": { "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "acceptHeader": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "colorDepth": 24, "screenHeight": 723, "screenWidth": 1536, "timeZoneOffset": 0, "javaEnabled": true } Would greatly appreciate on how to collect the above data points? Thank you:) -
django.core.exceptions.FieldError: Unknown field(s) (Category) specified for TblDetails?
ok. so when i tried to makemigrate for model class,earlier all fields were not visible inside migration>0001_initials. so i use this solution Django missing fields after initial makemigration i edited my code and added the missing field. it work fine for me and all the fields were created in my postagesql database(including Category field). but now when i tried to create form using model. it is raising error model.py class TblDetails(models.Model): Category = models.CharField(max_length=100), ImgUrl = models.CharField(max_length=255), FileName = models.CharField(max_length=100) forms.py class DetailsForm(forms.ModelForm): class Meta: model = TblDetails fields = ('Category','FileName') page.html {% load crispy_forms_tags %} {% block content %} <div class="col-md-10 offset-md-1 mt-5"> <div class="jumbotron"> <h1 class="display-4">Upload Files</h1> <hr class="my-4"> <form action="" method="post" autocomplete="off"> {%csrf_token%} {{form|crispy}} </form> </div> </div> {% endblock content %} and the error raised in terminal django.core.exceptions.FieldError: Unknown field(s) (Category) specified for TblDetails -
uploading .csv file from local to django Admin
I am stuck trying to work out an issue with my exercise and I don't understand what's wrong, I can't figure it out on my own. I want to create an uploader of .csv file on Django admin. Therefore I've created the following admin.py : import csv from io import TextIOWrapper from django.contrib import admin from django import forms from django.urls import path from django.shortcuts import redirect, render from .models import Alimenti, Genere class CsvImportForm(forms.Form): csv_file = forms.FileField() @admin.register(Alimenti) class AlimentiAdmin(admin.ModelAdmin, CsvImportForm): list_display = ( "alimento", "codice_alimento", "parte_edibile", "energia_kj", "energia_ricalcolata_con_fibra_kj", "energia_ricalcolata_kcal", "energia_ricalcolata_con_fibra_kcal", "proteine_totali_gr", "proteine_animali_gr", "proteine_vegetali_gr", "lipidi_totali_gr", "lipidi_animali_gr", "lipidi_vegetali_gr", "colesterolo_mg", ) change_list_template = "admin/change_list.html" def get_urls(self): urls = super().get_urls() my_urls = [ path('Import CSV/', self.import_csv), ] return my_urls + urls def import_csv(self, request): if request.method == "POST": csv_file = TextIOWrapper(request.FILES["csv_file"].file, encoding='utf-8') reader = csv.reader(csv_file) # create Alimenti object from passed in data for row in reader: Alimenti.objects.get_or_create( alimento=row[0], codice_alimento=row[1], parte_edibile=row[2], energia_kj=row[3].replace(",",'.'), energia_ricalcolata_con_fibra_kj=row[4].replace(",",'.'), energia_ricalcolata_kcal=row[5].replace(",",'.'), energia_ricalcolata_con_fibra_kcal=row[6].replace(",",'.'), proteine_totali_gr=row[7].replace(",",'.'), proteine_animali_gr=row[8].replace(",",'.'), proteine_vegetali_gr=row[9].replace(",",'.'), lipidi_totali_gr=row[10].replace(",",'.'), lipidi_animali_gr=row[11].replace(",",'.'), lipidi_vegetali_gr=row[12].replace(",",'.'), colesterolo_mg=row[13].replace(",",'.'), ) self.message_user(request, "Il file csv è stato importato correttamente") return redirect("admin/change_list") form = CsvImportForm() payload = {"form": form} return render( request, "admin/csv_form.html", payload ) class CsvImportForm(forms.Form): csv_files = forms.FileField() @admin.register(Genere) class GenereAdmin(admin.ModelAdmin, CsvImportForm): list_display = ( "ALIMENTO", "CODICE_MERCEOLOGICO", "GRUPPO_MERCEOLOGICO" ) … -
efficient delete old records migration
I need a migration to delete old records in a database table. What is old? If for the same device/gateway relation another record exists with a newer start date. I managed to do this by: def delete_old_gatewaydevices(apps, scheme_editor): GatewayDevice = apps.get_model("gateways", "GatewayDevice") for gw in GatewayDevice.objects.filter(end_date=None).all(): active_gateway = GatewayDevice.objects.filter( device=gw.device, gateway=gw.gateway, end_date=None ).last() for gatewaydevice in GatewayDevice.objects.filter( device=active_gateway.device, gateway=active_gateway.gateway, end_date=None ): if gatewaydevice.start_date < active_gateway.start_date: GatewayDevice.objects.filter(pk=gatewaydevice.pk).delete() But can this be done in one single (or two) queries? What's the best way to do it? -
django-filter on sub query
there is any way to pass an sub query like as .objects.filter(field=data) instead .objects.all() ? The main purpose is to use django_filter only to one user. views storico_user_filter=Storico_PC.objects.filter(user=user1) f=Storico_User_Filter(request.GET,storico_user_filter) filters class Storico_User_Filter(django_filters.FilterSet) : class Meta : model = Storico_PC fields=['motivo','hostname'] the issue is if i pass Storico_PC.objects.all() , all work well but if i pass Storico_PC objects.filter(user=user1) , in the template i see all the reference for that user but when i use the filters return all search empty . Many thanks, -
What would be the best way to temporarily connect Django with many external databases to get SQL queried data
I'm new to Django and I'm trying to find the best way for temporarily connecting to external databases to write SQL queries. Each database will not be connected all the time and I would Django to handle many external databases to be connected (with credentials) to get query data. -
How do I create a card view in HTML from the form data that I have made in django?
I am creating a Django CRM where I am using the forms to acquire data about any company. What I want to do is when I or anybody has written about the details of any companies and submitted them - they are going to be saved as card views in companies.html. Can anybody help me regarding this? companies.html: {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4 mt-4"> <a href="{% url 'company-create' %}" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-plus fa-sm text-white-50"></i> Create Company</a> </div> <div class="text-center"> <a class="small" href="{% url 'dashboard' %}">Back</a> </div> </div> {% endblock content %} company-create.html: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <!-- Begin Page Content --> <div class="container-fluid"> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4 mt-4"> <h1 class="h3 mb-0 text-gray-800">Company Create</h1> </div> <!-- Main Content Here --> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <div class="row"> <div class="col-lg-3"></div> <div class="col-lg-6"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Create a Company!</h1> </div> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{user_form | crispy}} {{profile_form | crispy}} <button type="submit" class="btn btn-primary btn-block">Update</button> </form> … -
[Django} How to filter through the list/retrieve function on Model ViewSet
Anyone know How can I implement a search filter on list/retrieve function to a viewset? I'm trying to use DRF Searh-filter on ViewSet but it's not working (Doesn't return the object filtered). What I wanna return is something like --> /store/1/locker/1/controller?controller={name_controller} view.py class ControllerViewSet(viewsets.ModelViewSet): serializer_class = ControllerSerializer queryset = Controller.objects.all() filter_backends = [filters.SearchFilter] search_fields = ['controller'] def list(self, request, store_pk=None, locker_pk=None): queryset = Controller.objects.filter(locker__store=store_pk, locker=locker_pk) serializer = ControllerSerializer(queryset, many=True, context={'request': request}) return Response(serializer.data) def retrieve(self, request, pk=None, store_pk=None, locker_pk=None): queryset = Controller.objects.filter(pk=pk, locker=locker_pk, locker__store=store_pk) locker = get_object_or_404(queryset, pk=pk) serializer = ControllerSerializer(locker, context={'request': request}) return Response(serializer.data) -
I want to assign matches to users that I select in django admin
I need to assign reports only to the users that I authorise from Django Admin. They should not be able to see all the reports in the database. Here's my code: Models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Match(models.Model): def __str__(self): return self.name name = models.CharField(max_length = 100) url = models.CharField(max_length = 1000) Views.py: from django.shortcuts import render from .models import Match from django.http import HttpResponse # Create your views here. def index(request): all_matches = Match.objects.all() return render(request, 'landing.html' , {"all_matches" : all_matches}) def upload(request): return render(request, 'upload.html') HTML: {% if user.is_authenticated %} <body> <div class="container-fluid"> <div style="float: right;" class="row"> <div class="col-xl-3 sidenav"> <h1 style="color: #ffffff; text-align: center">All Matches</h1><br> <form class="form-inline"> <input class="form-control mr-sm-2 input-mysize" type="search" placeholder="Search" aria-label="Search"> </form><br> {% for match in all_matches %} <li style="list-style: none ; text-align: center"><a href="{{match.url}}" target="iframe1">{{match.name}}</a></li> <hr class="new1"> {% endfor %} </div> <div class="col-md-9"> <iframe name="iframe1" width="1060" height="730" frameborder="0" allowFullScreen="true"></iframe> </div> </div> </div> </body> {% else %} <meta http-equiv="refresh" content="0; url=/login" /> {% endif %} </html> Please help me in a way I can do this. -
return int(value) ValueError: invalid literal for int() with base 10: '' Django Rest Framework
I used to change my models.py for a lot of times. And this is my models.py right now : from django.db import models import json # Create your models here. class Data(models.Model): node_id = models.ForeignKey("Node", on_delete=models.CASCADE) timestamp = models.DateTimeField() vibration = models.IntegerField() moisture = models.IntegerField() gps_latitude = models.CharField(max_length=250) gps_longitude = models.CharField(max_length=250) gyro_x = models.FloatField() gyro_y = models.FloatField() gyro_z = models.FloatField() accelero_x = models.FloatField() accelero_y = models.FloatField() accelero_z = models.FloatField() displacement = models.IntegerField() class Node(models.Model): node_id = models.IntegerField(primary_key=True) serializers.py : from .models import Data,Node from rest_framework import serializers class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = '__all__' class NodeSerializer(serializers.ModelSerializer): class Meta : model = Node fields = '__all__' class AcceleroXSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ['timestamp', 'accelero_x'] views.py : class DataViewSet(viewsets.ModelViewSet): queryset = Data.objects.all() serializer_class = DataSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['node_id'] class MapView(viewsets.ModelViewSet): queryset = Data.objects.filter(node_id=1).order_by('-id')[:1] serializer_class = DataSerializer class NodeViewSet(viewsets.ModelViewSet): queryset = Node.objects.all() serializer_class = NodeSerializer class AcceleroXViewSet(viewsets.ModelViewSet): queryset = Data.objects.all() serializer_class = AcceleroXSerializer urls.py : router = routers.DefaultRouter() router.register(r'data', DataViewSet, 'data') router.register(r'node', NodeViewSet, 'node') router.register(r'map', MapView, 'map') router.register(r'accelerox', AcceleroXViewSet, 'accelerox') urlpatterns = [ path('admin/', admin.site.urls), path(r'api/', include(router.urls)), path(r'', include('rest_framework.urls', namespace='rest_framework')), path('charts/', Charts.as_view(), name='charts'), path('charts2/', ChartsDua.as_view(), name='charts2'), path('chartnode/', ChartNode.as_view(), name='chartnode'), path('map/', Map.as_view(), name='map'), path('addnode/', views.add_node, … -
psycopg2.errors.SyntaxError: syntax error at or near "ON"
I am trying Django from Django documentation. I created two classes in models.py on my polls app: Publication and Articles, Articles class having publications=models.ManayToMany(Publication) Then in python shell, I imported from polls.models import Publication,Articles and executed: >>> p1=Publication.objects.get(id=1) >>> p2=Publication.objects.get(id=2) >>> p3=Publication.objects.get(id=3) >>> a1=Articles(headlines="When will be the lockdown get finished?") >>> a1.publication.add(p1) and I am getting an error: Traceback (most recent call last): File "C:\Python38\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.SyntaxError: syntax error at or near "ON" LINE 1: ..." ("articles_id", "publication_id") VALUES (2, 1) ON CONFLIC... -
Passing URL parameters into Hidden Form fields in Django
I've been trying to pass a value from a URL parameter into a Hidden form field in Django. I'd like to add this as part of the user profile to keep track of who referred them to the site. So in this case... http://website.abc/register/somestring/ the value 'somestring' would be added to a user profile field in the Profile class. I have the following paths added to my urls.py file where 'appref' is the name I've given to the URL parameter I want to save (this file has many paths, I've just included the register paths in this example) from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from users import views as user_views urlpatterns = [ path('register/', user_views.register, name='register'), path('register/<str:appref>/', user_views.register, name='appref'), ] I've already added a Profile class to models.py (the 2 'list_name' fields are just available to users when editing/updating their profiles and work fine. The 'appref' field is not provided as part of the 'Edit Profile' page for obvious reasons ) from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') image = models.ImageField(default='default.jpg', … -
Making table items clickable in Django
I'm trying to make items in the django_tables2 clickable,Really i succeeded to do that but i need some help to make it in a better way,Here is what i tried to do. first i opened "bootstrap.html" in this location("D:\ProgramData\Anaconda3\envs\djenv\Lib\site-packages\django_tables2\templates\django_tables2\bootstrap.html") in the bottom of this file i put this js code <script> function addRowHandlers() { var table = document.getElementById("tableId"); var rows = table.getElementsByTagName("tr"); for (i = 0; i < rows.length; i++) { var currentRow = table.rows[i]; var createClickHandler = function(row) { return function() { var cell = row.getElementsByTagName("td")[0]; var id = cell.innerHTML; //alert("id:" + id); var lines = '<a href="/laundry/'+id+'/">'+ '<h1>' + id + '</h1>' +'</a>'; document.write(lines); }; }; currentRow.onclick = createClickHandler(currentRow); } } window.onload = addRowHandlers(); </script> This code gave me the "id" in a white page but in the same url("localhost:8000/laundry/7/") and this "id" is clickable but the table rows are clickable without making it as a link.. this is the first shoot and if i clicked on any cell of the row it gives me the same id of the row and this is good for me.... The second way i tried to do is putting HTML Tag (<a href="/laundry/{{ cell }}/"></a>)as follow {% block table.tbody.row %} <tr … -
Why does this recursion error appear in pre-installed code?
So I am fairly new to coding with python and Django, but while working on a website I ran into this problem: "File "/Users/home/first_web/myenv/lib/python3.7/site-packages/django/urls/resolvers.py", line 131, in _check_pattern_startswith_slash if regex_pattern.startswith(('/', '^/', '^/')) and not regex_pattern.endswith('/'): RecursionError: maximum recursion depth exceeded while calling a Python object" I have tried looking at the code to see if I could solve it, but to my untrained eye I don't really notice anything wrong (btw, I didn't write the code referenced in the error). Below you can see all the the referenced file's lines of code, but as mentioned above the error is around line 131. """ This module converts requested URLs to callback view functions. URLResolver is the main class here. Its resolve() method takes a URL (as a string) and returns a ResolverMatch object which provides access to all attributes of the resolved URL match. """ import functools import inspect import re import string from importlib import import_module from urllib.parse import quote from asgiref.local import Local from django.conf import settings from django.core.checks import Error, Warning from django.core.checks.urls import check_resolver from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.utils.datastructures import MultiValueDict from django.utils.functional import cached_property from django.utils.http import RFC3986_SUBDELIMS, escape_leading_slashes from django.utils.regex_helper import normalize from … -
Django ORM; how to average data from one model and put it in another model in a single query
# contains sensor data for each second class Reading(models.Model): sensor = models.ForeignKey(Sensor) created_on = models.DateTimeField() value = models.FloatField() # contains hourly averages of sensor data class ReadingAveraged(models.Model): sensor = models.ForeignKey(Sensor) created_on = models.DateTimeField() value = models.FloatField() How to average data from Reading table into hourly averages for each sensor and insert that into ReadingAveraged table using in one query? Currently I have following query which converts data into hourly average for each sensor. Reading.objects.filter( created_on__range=[start_on, end_on]) ) .annotate( reading_on=Trunc( "created_on", "hour", output_field=DateTimeField(), ) ) .values("sensor", "reading_on") .annotate(Avg("value")) I can iterate over the result for this query and use bulk_create API to create data in ReadingAveraged table however that would be slow since huge chunk of data will have to be transfered between servers. How should I do the above process in 1 query in database only. -
More than one value in url on Django Rest Framework
I'm having this issue with Django Rest Framework and i don't get how to solve it. So, i want to pass more than 1 value through my API URL like this: urls.py url(r'^api/resource/(?P<value1>\w+)/resourcetwo/(?P<value2>[\w-]+)/$', views.example.as_view()), In views.py i have this: def get_object(self, *args, **kwargs): try: value1 = self.kwargs.get('value1') value2 = self.kwargs.get('value2') #... rest of the func. The issue is that i don't even get to my get_object because i have the following error from rest_framework.views: file "../env/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) TypeError: get() got an unexpected keyword argument 'value1' I have tried with the following configuration also: path('api/resource/<int:value1>/resourcetwo/<int:value2>', views.example.as_view()), def get_object(self, value1, value2): try: #... rest of the func. But i have the same error from rest_framework views, so how this should be implemented? Thanks for your help! -
Django | IntegrityError creating a new instance from form
when creating a new model instance with a from i get an integrity error because the id field is null even tho its set to auto generate. It worked before I don't know what changed. Model: class Device(models.Model): uuid = models.IntegerField(primary_key=True) owner = models.ForeignKey(User, null=True, on_delete=models.CASCADE) last_changed = models.DateTimeField(default=django.utils.timezone.now) applications = models.ManyToManyField(IoTApplication, blank=True, related_name='App') def __str__(self): return 'device: ' + str(self.uuid) class IPRule(models.Model): id = models.fields.IntegerField(primary_key=True, auto_created=True) device = models.ForeignKey(Device, on_delete=models.CASCADE, related_name='ip_rule') chain = models.CharField(max_length=6) # INPUT/OUTPUT destination_port = models.IntegerField() packet_type = models.CharField(max_length=10) action = models.CharField(max_length=15) # Drop,.. def __str__(self): return self.chain + ' | ' + str(self.device) class Meta: verbose_name_plural = "IP_Rules" ordering = ("id",) views.py @login_required(login_url='/login/') def new_iptables_config(request): if request.method == "POST": form = ConfigForm(request.POST) if form.is_valid(): config = form.save(commit=False) config.device = Device.objects.get(owner=request.user) # config.save() device = Device.objects.get(owner=request.user) device.last_changed = timezone.now() device.save() return redirect('config:app_view', id="1") else: form = ConfigForm() return render(request, 'new_config_from.html', {'form': form}) Error Exception Type: IntegrityError at /new_iptables_config Exception Value: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, INPUT, 2, tcp, ACCEPT, 12). -
Ajax request not fired in django
i have a problem, i think the ajax doesn't reach the matched view. This is the ajax I'm trying to send $.ajax( { url : 'ajax/create_lobby/', data: { 'creator' : data.message.creator, 'opponent' : data.message.opponent, }, headers:{ "X-CSRFToken": csrftoken }, dataType: 'json', success: function (data){ alert("Sended ajax request"); } } ) where var csrftoken = $("[name=csrfmiddlewaretoken]").val(); The main urls.py contains this: urlpatterns = [ path('chat/', include('chat.urls')), path('admin/', admin.site.urls), #this is what is not working re_path(r'^ajax/create_lobby/$', quizViews.createLobby, name = "create_lobby"), path("lobbies/", include('lobbies.urls')), path("lobby/", include('quiz.urls')), path('', include('accounts.urls')), ] So i took care of matching urls more restrictive first. This is the matched view by the url: @csrf_exempt def createLobby(request): creator = request.GET.get("creator", None) opponent = request.GET.get("opponent", None) print(creator) print(opponent) data = { 'creator' : creator, 'opponent' : opponent } return JsonResponse() The ajax seems to not be fired and i can't see the problem. Can you help me, i'm new to ajax. Thank you! -
How to run ajax only when user is logged in. (Django)
I've multiple items that can be added to the cart by clicking the respective button. Each item is a form having information about itemid and, the 'addtocart' button is the submit button for the form. I'm using ajax to make changes in the DB and then reload the page to reflect them. Html <script type="text/javascript"> $(document).on('submit','.addtocart',function(e){ e.preventDefault(); var a=$(this).find('input[name=itemid]').val(); $.ajax({ type:'POST', url:'addtocart', data:{ itemid:a, 'csrfmiddlewaretoken': $('[name="csrfmiddlewaretoken"]').val() } }); setTimeout(() => { document.location.reload(true);} , 100); }); </script> views.py @login_required(login_url='/userhome') def addtocart(request): if request.method == "GET": return redirect('/') else: product_id = request.POST['itemid'] product_quantity = 1 cart = usercart.objects.all().filter(user_id = request.user.id, product_id = product_id ) try: if cart[0] is not None: cart = usercart.objects.get(user_id = request.user.id, product_id=product_id) cart.product_quantity+=1 cart.save() else: cart = usercart(product_id=product_id, user_id=request.user.id, product_quantity=product_quantity) cart.save() except IndexError: cart = usercart(product_id=product_id, user_id=request.user.id, product_quantity=product_quantity) cart.save() return redirect('checkout') I want to redirect to the login page ('/userhome') if the user is not logged in and addtocart button is clicked. I've tried wrapping my Js inside {% if user.is_authenticated %} <script> ... </script> {% endif %} But due to this, the user cannot see the products before logging in. I want a user to see products without logging but addtocart button should work in both situations, … -
'Question' object has no attribute 'choice_set' django
i tried the django polls app but got this , my models included foreign key but i don't get it where's the problem from django.db import models class Question(models.Model): question = models.CharField(max_length = 200) pub_date = models.DateTimeField('published date') def __str__(self): return self.question class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) vote = models.IntegerField(default=0) def __str__(self): return self.choice_text and here is the view: def vote(request , primary_key): question = get_object_or_404(models.Question, id=primary_key) try: selected_choice = question.choice_set.get(id=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request,'polls/detail.html',{ 'question' : question , 'error_message' : "u didn't select a choice." }) else: selected_choice.vote += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args = (question.id))) urls: urlpatterns = [ re_path(r'^$', views.index , name = 'index'), re_path(r'^(?P<primary_key>[0-9]+)/$',views.detail, name = 'detail'), re_path(r'^(?P<primary_key>[0-9]+)/results/$' , views.results , name = 'results'), re_path(r'^(?P<primary_key>[0-9]+)/vote/$' , views.vote , name = 'vote'), ] -
Why am i getting errors trying to deploy my app to Heroku?
I'm trying to deploy my app using Heroku. I tried via CLI and also graphically in their user portal. I get this problem in the build log: Procfile declares types -> (none) It's not reading my Procfile. Here's some of the latest lines of my error logs: 2020-05-08T04:32:57.546072+00:00 app[api]: Deploy 02e1e06c by user djrgrey@gmail.com 2020-05-08T04:32:57.546072+00:00 app[api]: Release v7 created by user djrgrey@gmail.com 2020-05-08T04:33:05.475821+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=herokudanslist.herokuapp.com request_id=ff88cf27-54c2 -4611-b611-ce36c41b09f6 fwd="118.149.66.76" dyno= connect= service= status=503 bytes= protocol=https 2020-05-08T04:33:06.086210+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=herokudanslist.herokuapp.com request_id=a4 690f93-c8e3-4256-b46b-a8d1e69109c1 fwd="118.149.66.76" dyno= connect= service= status=503 bytes= protocol=https 2020-05-08T04:33:13.000000+00:00 app[api]: Build succeeded 2020-05-08T10:04:32.000000+00:00 app[api]: Build started by user djrgrey@gmail.com 2020-05-08T10:05:04.414084+00:00 app[api]: Release v8 created by user djrgrey@gmail.com 2020-05-08T10:05:04.414084+00:00 app[api]: Deploy 92e0c7b1 by user djrgrey@gmail.com 2020-05-08T10:05:37.245718+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=herokudanslist.herokuapp.com request_id=9cb80bd2-7cb6 -4e20-ad8a-e61aeeab0e02 fwd="118.149.66.76" dyno= connect= service= status=503 bytes= protocol=https 2020-05-08T10:05:39.210072+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=herokudanslist.herokuapp.com request_id=a2 9bf337-c13a-4eb7-83ef-e221bc69b6b7 fwd="118.149.66.76" dyno= connect= service= status=503 bytes= protocol=https 2020-05-08T10:05:40.000000+00:00 app[api]: Build succeeded It's not a text file. Here is my edited directory. Steps I've done to resolve: Refactored the name Ran it locally git push heroku master I've also deleted …