Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using filter__in via Foreignkey relationship returns en empty queryset
I'm trying to use the queryset category_filter as a filter__in // Django doc for another query qs_poller. However, the query returns an empty set. # View def render_random_poller(request): if request.user.is_authenticated: category_filter = Category.objects.filter(usercategoryfilter__user=request.user) # Returns <QuerySet [<Category: Sports>, <Category: Lifestyle>, <Category: Environment>]> qs_poller = Poller.objects.filter(poller_category__category__in=category_filter).order_by('-created_on')[:100] # Returns an empty set, although the database holds 5 entries matching the category_filter # Models class UserCategoryFilter(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.ManyToManyField(Category) class Poller(models.Model): created_by = models.ForeignKey(Account, on_delete=models.SET(get_deleted_user)) poller_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) class Category(models.Model): category = models.CharField(max_length=30) -
i have Erroor "Related Field got invalid lookup: icontains" when i try filter on views.py from models.py
here, on views.py I want to filter 'language' from the models.py but it said there is Errror. " raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: icontains" i dont know why just'language' has problem but not when i try to filter 'genre','title', i dont see the Error on the terminal what can be the solutions? here is the models.py from django.db import models from django.urls import reverse import uuid class Genre(models.Model): name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') def __str__(self): return self.name class Language(models.Model): name = models.CharField(max_length=200, help_text="Enter the book's natural language (e.g. English, French, Japanese etc.)") def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book') isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') genre = models.ManyToManyField(Genre, help_text='Select a genre for this book') language = models.ForeignKey('Language', on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library') book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), … -
I want to create multiple objects with single foreign key relation
I need to add multiple skills for one candidate. As now i am getting the error cannot assign multiple instances to skill models class CandidateSkill(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE,related_name="skills",) skills = models.ForeignKey("jobs.Skill", on_delete=models.CASCADE) ---------- class CandidateSkillSerializer(serializers.ModelSerializer): class Meta: model = CandidateSkill fields = ["id", "candidate", "skills"] -
Adding validator to a model field via __init__ of the class model results in duplication of error messages
I have a model like this: class Permission(models.Model): slug = models.CharField('Метка', unique=True, max_length=255) @staticmethod def slug_field_validator(value): raise ValidationError('Error message') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._meta.get_field('slug').validators.append( self.__class__.slug_field_validator) This results in duplication of error messages in admin interface. What am I doing wrong ? -
How to know blank and non blank fields after a django ajax form submission?
I have a modelform which allows a some non required fields. Where I am stuck is figuring out a way that will allow me to exactly know which field came with data, and which did not so while creating my model instance I won't miss any user data inputted. at beginning I thought of serializing the form by using serializeArray then get the non empty value and add it in the form.serialize() but this prevents the form from being valid. Here is the see question. Is there any way to know this even if it is before processing the ajax or in the django view itself ? Thank you in advance. Code: function CreateIssueAjax(e) { e.preventDefault(); const role = this.getAttribute('role'); const _form = $("#CreateIssueForm"); var formString = _form.serializeArray(); console.log(formString) function sendKwargs(arr) { let kwargs = {} arr.forEach(el => { if (!(el.value === "") | (!(el.name === 'csrfmiddlewaretoken'))) { kwargs[el.name] = el.value } }); return kwargs; } console.log(sendKwargs(formString)); var myData = _form.serialize(); console.log(myData); myData['kwargs'] = JSON.stringify(sendKwargs(formString)); $.ajax({ url: "/create-issue/", type: "post", data: myData, datatype: 'json', success: function (data) { console.log("success"); // add to ui function after success // alert the user(alertify.js) }, }); } def createIssue(request): form = CreateIssueForm(request.POST or None) … -
django.template.exceptions.TemplateDoesNotExist: templates/index.html Error
I am making a Django authentication program but keeps on giving me this error. django.template.exceptions.TemplateDoesNotExist: templates/index.html Error. PLS help me coz I have spent hours trying to solve this problem. Views.py from django.http import HttpResponse def home(request): return render(request, "authentication/index.html") def signin(request): return render(request, "authentication/signin.html") def signout(request): pass Urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('',views.home, name = "home"), path('signin',views.signin, name = "signin"), path('signout',views.signout, name = "signout"), ] Settings """ Django settings for gfg project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '-tqa6(3cnb_f@3u(56)mu9z%d2c548xypd-@%6i&60@)mxbs$k' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'gfg.urls' TEMPLATES = … -
Logging SQL with Django logging configuration. The logger always trying to connect with the public schema
The following is the logging configuration for our Django application logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(asctime)s %(name)-12s %(lineno)d %(module)s %(levelname)-8s %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 15728640, # 100MB 'backupCount': 10, 'formatter': 'verbose', 'filename': 'log_files/acme-slcms.log', 'encoding': 'utf-8', }, 'mail_admins': { 'level': 'CRITICAL', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, }, 'loggers': { 'django': { 'propagate': True, 'level': 'DEBUG', 'handlers': ['file'], }, 'django.db.backends': { 'propagate': False, 'level': 'DEBUG', 'handlers': ['file'], } } }) We have added the django.db.backends logger to print the queries generated by the application. But from the output, it seems the logger is connecting to the public schema 2021-10-06 13:37:39,704 django.db.backends 123 utils DEBUG (0.089) SELECT c.relname, c.relkind FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'v', '') AND n.nspname = 'public' AND pg_catalog.pg_table_is_visible(c.oid); args=None After implementing the log, we are not seeing any queries other than this. The application is actually using another schema for storing and retrieving data and is using django-tenant as part of the homegrown … -
Return JSONResponse before updating database in django, python2
Im having a project running on python2.7. The project is old but still its necessary to update the database when a request is received. But the update process takes time and ends up with a timeout. Is there anyway return JsonResponse/Httpresponse, before updating the database so that timeout doesn't occur. I know its not logical to do so, but its a temporary fix. Also, i cant use async since its python2 -
Django and Django rest framework
I was following a resource https://blog.learncodeonline.in/how-to-integrate-razorpay-payment-gateway-with-django-rest-framework-and-reactjs Instead of using reactjs for the front end. How can i make the frontend using Django templates? Please help. Thank you. -
Showing multi-dimensional data in django
Hej! I have some multidimensional data in my django project, e.g. a status of an institution (containing e.g. a year to differ them). Every institution can have multiple status from different years. Also I have multiple institutions and want a table/list of them. Is there a possibility to show show those multi-dimensional data for each institution? Or maybe the newest? I couldn't find it in the docs. # models.py class StatusOfPlants(models.Model): """status (phases) of plants""" class StatusChoices(models.TextChoices): PLANNING = "planning", _("in foundation") IN_OPERATION = "in_operation", _("in operation") plant = models.ForeignKey( Plant, on_delete=models.PROTECT, related_name="status_of_plant" ) status = models.CharField( max_length=20, choices=StatusChoices.choices ) year_valid_from = models.SmallIntegerField( validators=[validate_year], blank=True, null=True ) year_valid_to = models.SmallIntegerField( validators=[validate_year], blank=True, null=True ) def __str__(self): return f"{self.status}" In the admin area can the multi data be added. I'm just wondering about the presentation in the view when I want more than just a list of the status 'names' in one field. Hope it is clear what I'm talking about and someone has an idea how to solve that! Thanks in advance :) -
How can I change referral of inactive user until I found active referral of current user in django
How can I change referral of inactive user until I found active referral of current user This is my models class ReferralCode(models.Model): user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) user_active = models.BooleanField(default=False) referral = models.ForeignKey( User, related_name='comp_active_user', on_delete=models.SET_NULL, null=True, blank=True) class PointValue(models.Model): user_id = models.ForeignKey( User, related_name='realtime_user', on_delete=models.CASCADE) rt_ppv = models.DecimalField( null=True, max_digits=20, decimal_places=2, default=0.00) this is my views def check_active(request): min_ppv = 20 for user in ReferralCode.objects.all(): try: user_point = PointValue.objects.get( user_id=user ) except: pass if user_point.rt_ppv >= min_ppv: user.user_active = True user.save() else: # getting all users referred by this user users_referred = ReferralCode.objects.filter( referral=user ) # changing referral of all users to parent user of current user for user_referred in users_referred: user_referred.referral = user.referral user_referred.save() user.user_active = False user.save() What I'm trying is I want to check each users in ReferralCode and check it's rt_ppv value from PointValue table if it's greater than min_ppv value than I'm changing it's status to True and if it's not than user status will be False and changing all the users whom he referred to parent of current user (check in the else block) Problem : It's changing referral but the new referral of all users it's rt_ppv it's not greater … -
Can't query Many-to-Many relationship in Django
I do have a Model UserCategoryFilter with a M2M relation to Model Category # View @require_GET def get_category_filter(request): # Get the existing user instance if any filter_instance = UserCategoryFilter.objects.get(user=request.user) # Get the current selections/filters selection = filter_instance.categories_selected print(selection) However, selection always returns None instead of a queryset even though there are three categories selected by the user and stored in the DB. # Models class Category(models.Model): category = models.CharField(max_length=30) category_color = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.category) class UserCategoryFilter(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.ManyToManyField(Category) -
How can I merge two or more queryset objects' field into one?
In my serializer, I have the following query: memberships = Membership.objects.filter( user__id=instance.user.id, project__id__in=instance.organization.projects.values_list('id'), ).order_by('project__name') which gives me: "projects": [ { "project": "3ba96c4c-0b82-4f2a-9e1b-f18a8b63912a", "name": "string 1", "role": 0 }, { "project": "5fab483c-9703-4ed8-a3e7-b1516855fb99", "name": "TestProj", "role": 0 }, { "project": "5fab483c-9703-4ed8-a3e7-b1516855fb99", "name": "TestProj", "role": 1 } ], But I would like the output (for frontend's sake) to be: "projects": [ { "project": "3ba96c4c-0b82-4f2a-9e1b-f18a8b63912a", "name": "string 1", "roles": [0] }, { "project": "5fab483c-9703-4ed8-a3e7-b1516855fb99", "name": "TestProj", "roles": [0, 1] } ], How should I modify my query in order to achieve such result? -
Unable to add data from admin panel to webpage in django
I was trying to add data dynamically from admin to my HTML page in django but when I try to add data in admin panel it is not showing anything in the HTML file. when I do makemigrations i am getting this below You are trying to add a non-nullable field 'link' to researchpaper without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: In admin panel I am getting this error why I am getting this problem please help -
docker python3 deployment fail
I deployed a docker container with this Dockerfile for my Django-rest-application: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ COPY . /app/ RUN /usr/local/bin/python -m pip install --upgrade pip RUN pip install -r requirements.txt However, docker doesn't install python3 on my virtual machine, instead it install python2. Is there a way to make sure the docker install the correct python? Thanks, -
How to change a field in django form after calling is_valid() on the form?
I am changing django model choice field to choice field the form renders fine, but when post data is received and is valid is failed, I change the form field but it renders original field? Is there some over ride? # field_1 is ModelChoiceField by defauly if request.method == 'POST': a_form = My_Form(request.POST, instance=assembly_order) if not a_form.is_valid(): a_form.fields['field_1'] = forms.CharField(max_length=50) return render (request, 'my.html', {'a_form': a_form}) # --------- returns modelchoicefield else: a_form.save() else: a_form = My_Form(instance=None) a_form.fields['field_1'] = forms.CharField(max_length=50) return render (request, 'my.html', {'a_form': a_form}) # renders CharField -
Form content not visible on django homepage?
I was trying my hands on learning django and tried creating a resume builder project where user can get form based template by entering some details on the form, but the form is not visible on the homepage. I'm attaching template code for more refrence. {% extends 'base.html' %} {% block content %} <form method="post" action="post-form"> {% csrf_token %} <p> {{form.as_p}} </p> <input type="submit" value="Save" /> </form> {% endblock %} -
like and unlike django ajax
write an application for like and like using Django and ajax, JQuery function but I noticed that it works fine but the problem is if click like button then I am getting 500 internal errors. Here is POST http://127.0.0.1:8000/like/ 500 (Internal Server Error)## here ajax code when run i get 500 internal error. $('#result').click(function() { var liked = $(".like").val(); var addLike = liked + 1 data = { 'liked': addLike } console.log('data', data) SendAjax(); }); // const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; function SendAjax() { $.ajax({ url: '/like/', method: 'POST', headers: { 'X-CSRFToken': csrftoken }, dataType: "json", data: data, success: function(data) { console.log('success', data.status); if (data.status === 200) { console.log(data.status) // let load_url = 'http://127.0.0.1:8000/' + name; // console.log('load url', load_url); // window.location.replace(load_url); } }, }) }; views.py def like(request) : data= {} name=get_object_or_404(Stylish, id=request.POST.get('id')) context= { 'name': name } print('context', context) print("like") if request.method=='POST' and "GET" : liked=request.POST('liked', None) print('liked', liked) like=likes.objects.create( liked=liked) print('like', like) return render(request, 'index.html', data) <div class="col"> <input type="text" class="form-control text-1 textfont copybutton " data-clipboard-action="copy" data-clipboard-target="#copy_0" for="textfont" style="text-align: center; " value="𝔓𝔯𝔢𝔳𝔦𝔢𝔴 𝔗𝔢𝔵𝔱" id="copy_0" readonly="readonly"> <!-- {% if instance.liked%} --> <span id="count"></span> <input class="like" type="image" src="{% static 'images/like.svg' %}" alt="Like" id="like" title="Like" width="10" height="10" id="heart" value="{{ liked }}"> … -
Django: NoReverseMatch at /patient/1/
I have this urls.py in cabinet app: urlpatterns = [ path('', views.index, name='index'), path('register_patient/', views.registerPatient,name='register_patient'), path('register_booking/', views.registerBooking,name='register_booking'), path('register_visit/<int:id>/', views.registerVisit,name='register_visit'), path('<int:id>/', views.detail_patient), ] before adding the 4th path('register_visit/<int:id>/'), the views.detail_patient was working well but now when I add this 4th path the views.detail_patient didn't work and I get this error: NoReverseMatch at /patient/1/ So my problem is that I can't use '<int:id>' more than one time and in my code I have the index page wich show the list of patients and every patient have a button 'details' who's will take me to the 5th path(('<int:id>/', views.detail_patient)) and in this template I have a button 'Nouvelle Chirurgie' who's gonna take me to the 4th path(('register_visit/<int:id>/', views.registerVisit,name='register_visit')). In index.html this the Details button: <a href="{{field.id}}/" class="btn btn-warning">Details</a> And in detail_patient.html this is the 'Nouvelle Chirurgie' button <a href="{% url 'register_visit' %}{{patients.id}}" class="btn btn-primary">Nouvelle Chirurgie</a> How to fix this error -
i want to edit admin panel ,which open with perticular staff user item list only and not want to compromise with TabularInline in same table
Hi i am trying to create rent and co living hobby project for that i want to use admin panel as staff dashboard where staff can perform CURD operations in this section there is on major condition staff can't edit each other property listing,and i have another table for property images where rent-property which i use in tabular inline .i am sharing screen shot below my admin.py code is given below from django.contrib import admin from .models import RentProperties,RentPropertyImages from django.utils.html import format_html from django.contrib.admin.widgets import AdminFileWidget from django.db import models # Register your models here. class RentPropertyImagesAdmin(AdminFileWidget): """Admin widget for showing clickable thumbnail of Image file fields""" def render(self, name, value, attrs=None, renderer=None): html = super().render(name, value, attrs, renderer) if value and getattr(value, 'url', None): html = format_html('<a href="{0}" target="_blank"><img src="{0}" alt="{1}" width="150" height="150" style="object-fit: contain;"/></a>', value.url, str(value)) + html return html class RentPropertyImagesInline(admin.TabularInline): model=RentPropertyImages formfield_overrides = {models.ImageField: {'widget': RentPropertyImagesAdmin}} fk_name="property_image" class ResntpropertiesAdmin(admin.ModelAdmin): inlines=[ RentPropertyImagesInline ] list_display=('posted_by','property_title','area','city','pincode','is_active') list_filter=('is_active','city','ac','childrens_play_area','club_house','fire_safety','is_flat_pg_flatmate') search_fields=('posted_by__username','city','area','pincode','state','property_code','property_title') exclude=('posted_by',) def save_model(self, request, obj, form, change): if not obj.posted_by: obj.posted_by = request.user obj.save() def has_add_permission(self, request, obj=None): if request.user.is_superuser: return True if obj is not None and obj.posted_by != request.user: return False return True def has_change_permission(self, request, obj=None): if … -
How do i deal with foreign key and multiple errors for Django API framework POST?
I have the following codes: models.py class Device(models.Model): hostname = models.CharField(max_length=50, unique = True) ipaddr = models.GenericIPAddressField(protocol='ipv4', unique=True, verbose_name='mangement IP') ##Use for mgt_id_addr date_added = models.DateTimeField(default=timezone.now) def __str__(self): return self.hostname class DeviceDetail(models.Model): SUBNET_CHOICES = ( ('16','16'), ('17', '17'), ('18','18'), ('19','19'), ('20','20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ) DEV_MODS =( ('Catalyst 9606R', 'Catalyst 9606R'), ('C9300L-48T-4X', 'C9300L-48T-4X') ) mgt_interface = models.CharField(max_length=50) subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.hostname serializers.py from rest_framework import serializers from .models import Device, DeviceDetail class DeviceSerializers(serializers.ModelSerializer): class Meta: model=Device fields = '__all__' class DeviceDetailSerializers(serializers.ModelSerializer): class Meta: model = DeviceDetail fields = ['mgt_interface', 'subnetmask', 'ssh_id', 'ssh_pwd', 'enable_secret', 'dev_mod'] views.py @api_view(['POST']) def create_device(request): device = Device() devicedetail = DeviceDetail() deviceserializer = DeviceSerializers(device, data = request.data) devdserializer = DeviceDetailSerializers(devicedetail, data = request.data) if deviceserializer.is_valid() and devdserializer.is_valid(): deviceserializer.save() devdserializer.save(DD2DKEY=deviceserializer.id) results = { "device":deviceserializer.data, "device_details" : devdserializer.data, } return Response(results, status=status.HTTP_201_CREATED) else: errors = { "device":deviceserializer.errors, "device_details" : devdserializer.errors, } return Response(errors, status=status.HTTP_400_BAD_REQUEST) This statement devdserializer.save(DD2DKEY=deviceserializer.id) is giving me … -
How to get out of nested functions
I'm making chat bot service with Django. And my code invoke function in other function, to get the answer. My code is like this: def chat_view(request): user_input = request.GET.get('user_input') answer = flow(user_input) if len(answer) > 1: # Give the user a choice return HttpResponse(answer) def flow(user_input): data = get_data(user_input) # if len(data) > 1: # data_list = data # return data_list answer = get_answer(data) return answer def get_data(user_input): data = query_db_with_user_input(user_input) if len(data) > 1: # At this point, I want to give the user a choice to choose one data. # But to do that, I can pass it to the user after exiting the flow function. # So, I need to put ``if len(data) >1: something`` in the flow function and chat_view function. data_list = data return data_list return data def get_answer(data): answer = f'Data is {data}' return answer When the data is a certain condition, I want to escape all the nested functions and give a response to the user. However, if I write it as a comment, the code becomes too dirty and difficult to maintain. It doesn't matter if I have to rip and fix the code base. Does this have anything to do with … -
Different django url paths executing same view function
I am new to Django and working on to do app. I have following index.html, views.py and urls.py files in my Django app. Whenever I click on changes status link, still it is executing remove function from views.py. What's going wrong ? index.html <ol> {% for task in tasks%} <li> <div class="row"> <div class="col-4">{{task.id}}{{task.name}}</div> <div class="col-4"> <a href="{% url 'to_do_app:change_status' task.id %}"> {% if task.status %} <i class="fas fa-check-circle"></i> {% else %} <i class="far fa-circle"></i> {% endif %} </a> </div> <div class="col-4"><a href="{% url 'to_do_app:remove' task.id %}"><i class="far fa-2x fa-trash-alt"></i></a></div> </div> </li> {% empty %} <li>No Tasks</li> {% endfor %} Views.py date = datetime.datetime.now() def index(request): tasks = Task.objects.all() return render(request, "to_do_app/index.html", { # pass the list of tasks for this perticular session "tasks": tasks, "date": date }) def add(request): # Server Side Form data validation form = NewTaskForm() if request.method == "POST": # take all the data posted from frontend via post request and store it variable 'form' form = NewTaskForm(request.POST) # check if data is valid or not if form.is_valid(): # clean the data task = form.cleaned_data['name'] # append list Task(name=task, status=True).save() # after New task is added, redirect to index page # reverse() function figures out the … -
I am having trouble on fetching data from graphql using apollo and router. Backend: Django, frontend vue
Please find the browser console error Hi evryone, I managed to go through all steps in realpython tutorial to build a blog using django, vue and graphql. My django and vue applications works fine. However, on step 8 (the last step of the tutorial), trying to fetch the data using graphql api is not working. I configured the right end point for apollo. I built a query for all components as provided in the tutorial. At the end nothing is displayed. It is just same as step 7. Has anyone had an experience with this or have some input on what the best option is? -
Data is not saved while using FIlteredSelectMultiple widget
forms.py class RegistrationCreateForm(forms.Form): player = forms.ModelChoiceField(queryset=Player.objects.all(), widget=FilteredSelectMultiple("Player", is_stacked=False)) def __init__(self, *args, **kwargs): super().__init__() class Meta: model = Registration fields = ['player'] @property def media(self): w1 = FilteredSelectMultiple("", False) form_media = forms.Media(js=['js/jsi18n.js'], css={'all': ['css/filtered.css']}) return (w1.media + form_media ) views.py class RegistrationCreateView(AccessControlMixin, CreateView): model = Registration form_class = RegistrationCreateForm template_name_suffix = '_create' def has_access(self, user): return self.can("create_registration", self.tournament) def get_success_url(self): return "%s" % reverse("tournaments:detail", kwargs={"pk": self.kwargs['pk']}) def dispatch(self, request, *args, **kwargs): """ Overridden so we can make sure the `Tournament` instance exists before going any further. """ self.tournament = get_object_or_404(Tournament, pk=kwargs['pk']) return super(RegistrationCreateView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): self.tournament = get_object_or_404(Tournament, pk=self.kwargs['pk']) context = super(RegistrationCreateView, self).get_context_data(**kwargs) context['tournament'] = self.tournament return context def form_valid(self, form): form.instance.tournament = self.tournament form.instance.created_by = get_request().user player_institution_relation = PlayerInstitution.objects.filter(Q(player= form.instance.player) & Q(institution = self.tournament.owner)) if player_institution_relation.exists(): number_of_objects = player_institution_relation.count() if number_of_objects>1: for player_inst in player_institution_relation[1:]: player_inst.delete() else: PlayerInstitution.objects.create(player=form.instance.player, institution=self.tournament.owner) return super(RegistrationCreateView, self).form_valid(form) def get_form(self, *args, **kwargs): tournament = get_object_or_404(Tournament, pk=self.kwargs['pk']) form = super(RegistrationCreateView, self).get_form(*args, **kwargs) #Remove any player that has already a registration if get_request().user.name_format == 'First name Last name': form.fields['player'].queryset = tournament.available_players.order_by("first_name","last_name") else: form.fields['player'].queryset = tournament.available_players.order_by("last_name","first_name") return form I am using FilteredSelectMultiple widget for a foreign key field. It is rendering the form as i …