Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
wich type of modele in django for this form of values?
I want to create a model in my django app for this value, in this value we have ";" : 0;-0.0110227457430789;-0.0117428254241928; how can corige me please ? value = models.CharField(max_length=1000, blank=True, null=True) -
Django IsAuthenticated views always return 403
I have various views and viewsets, when I add the IsAuthenticated permission class I always get the 403 forbidden error Response { "detail": "You do not have permission to perform this action." } In views @api_view(["GET"]) @permission_classes([IsAuthenticated]) def protected_profile(request): In viewsets permission_classes = [IsAuthenticated] When I remove this class my requests work I've even checked if request.user.is_authenticated it returns true. It was working few hours back, I've reverted to previous git commits and now the problem continues to persist, my JWT is right as well. I'm on Django 3.2.3 and channels 3.0.3 if that helps. Any help would be appreciated. Edit: the same deployment works fine on heroku. So, I've dropped the DB locally restarted everything but its still the same. -
'WSGIRequest' object has no attribute 'is_ajax' in django 4
i had built a website with django 3 and i updated it to django 4 since this update i get this error I need help to solve this problem, thank you 'WSGIRequest' object has no attribute 'is_ajax' this is my views views.py def SingleBlog(request, Slug): post = get_object_or_404(Blog, Slug=Slug, Status="p") comments = BlogComment.objects.filter(Post=post, Reply=None, Status="p") is_liked = False if post.Like.filter(id=request.user.id).exists(): is_liked = True if request.method == 'POST': comment_form = CommentForm(request.POST or None) if comment_form.is_valid: content = request.POST.get('Text') reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = BlogComment.objects.get(id=reply_id) comment = BlogComment.objects.create(Post=post, User=request.user, Text=content, Reply=comment_qs) comment.save() # return HttpResponseRedirect(post.get_absolute_url()) else: comment_form = CommentForm() context = { 'object': post, 'comments': comments, 'is_liked': is_liked, 'comment_form': comment_form, } if request.is_ajax(): html = render_to_string('partial/comments.html', context, request=request) return JsonResponse({'form': html}) return render(request, 'blog-single.html', context) def post_like(request): # post = get_object_or_404(Blog, id=request.POST.get('post_id')) post = get_object_or_404(Blog, id=request.POST.get('id')) is_liked = False if post.Like.filter(id=request.user.id).exists(): post.Like.remove(request.user) is_liked = False else: post.Like.add(request.user) is_liked = True context = { 'object': post, 'is_liked': is_liked, } if request.is_ajax(): html = render_to_string('partial/like_section.html', context, request=request) return JsonResponse({'form': html}) thank you -
how to read with Jquery and element readonly for django
Object1 see the image plx there are some readonly field that i set up on django, but i want to read the values using Jquery but really idk how to do it, i want to do it cuz depending of the value that is set on field "tipo" i want a make some values visibles or not. let tipo_persona_check = function(){ if ($('#id_tipo').val() == 'fisica'){ $('.field-empresa').hide(); $('label[for=id_persona').text('Suscriptor'); }else{ $('label[for=id_persona').text('Apoderado'); $('.field-empresa').show(); } in this case im hidding or showing field empresa depending of the value of id_tipo, but when it is on readonly, this id not exist, there is just a span class called readonly (for all readonly) with the value, but idk how to get from it, i need to know if the value is "fisica" or another from the readonly field tipo, to do things. any ideas? -
Import "knox.models" could not be resolved
im trying to import knox.models in my views.py file but i get error "Import "knox.models" could not be resolved" , i have installed knox and add it to my app settings but still got the same error -
RuntimeError: Model doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am writing an app in Django and I'm trying to do some unit testing but I can't seem to find why the test is failing that is the test page: import re from django.test import TestCase from django.urls import reverse from . import models class BasicTests(TestCase): def test_firstname(self): print('test11') acc = models.Accounts() acc.first_name = 'Moran' self.assertTrue(len(acc.id) <= 9, 'Check name is less than 50 digits long') self.assertFalse(len(acc.id) > 50, 'Check name is less than 50 digits long') the error i get is : RuntimeError: Model class DoggieSitter.accounts.models.Accounts doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS thats my installed app: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts' ] -
Getting has_permission() missing 1 required positional argument: 'view' instead of JSON Response
Getting has_permission() missing 1 required positional argument: 'view' instead of JSON Response from rest_framework import filters from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from apps.fm.models.asset import Asset from apps.fm.serializers import AssetSerializer from django.shortcuts import render, redirect from django.urls import reverse class AssetViewSet(viewsets.ModelViewSet): model = Asset serializer_class = AssetSerializer permission_classes = [IsAuthenticated] filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ['name'] ordering_fields = ['id'] ordering = ['-id'] def get_permissions(self): uagent = ['Chrome','Firefox'] if self.request.user_agent.browser.family in uagent: return [] return [IsAuthenticated] def retrieve(self, request, *args, **kwargs): instance = self.get_object() uagent = ['Chrome','Firefox'] if self.request.user_agent.browser.family in uagent: authentication_classes = [] #disables authentication permission_classes = [] #disables permission return redirect(reverse("feedback")+"?type=Asset&id="+str(instance.id)) serializer = self.get_serializer(instance) return Response(serializer.data) def get_queryset(self): queryset = self.model.objects.all() return queryset -
How to create different database tables for user types in Django?
Here is what I am trying to do. The project has Two Type of users: Spot Owners Spot Rentee Owners can add slot, Rentees can book slot. Here is my code: models.py: class UsersManager(BaseUserManager): def create_user(self, nid, password=None): if not nid: raise ValueError('Users must have an nid address') user = self.model( nid=self.normalize_email(nid), ) user.set_password(password) user.save(using=self._db) return user class Users(AbstractBaseUser): user_type = ( ('R', 'Rentee'), ('S', 'Spot Owner'), ) nid = models.CharField(max_length=30, unique=True, primary_key=True) name = models.CharField(max_length=200) email = models.CharField(max_length=200) password = models.CharField(max_length=128) contact = models.CharField(max_length=15, null=True) last_login = models.DateTimeField(auto_now_add=True, null=True) is_spot_owner = models.CharField(max_length=10, choices=user_type,default='user') USERNAME_FIELD = 'nid' objects = UsersManager() def __str__(self): return self.nid class SpotOwner(Users,models.Model): owner_info = models.CharField(max_length=200) def __str__(self) -> str: return self.nid.nid class Rentee(models.Model): nid = models.ForeignKey(Users, on_delete=models.CASCADE) vehicle_type = models.CharField(max_length=200) rentee_credit = models.IntegerField() def __str__(self): return self.name forms.py: class UserForm(ModelForm): class Meta: model = Users fields = '__all__' class RenteeForm(ModelForm): class Meta: model = Rentee fields = '__all__' views.py: def signup(request): form = UserForm(request.POST) print("Errors",form.errors) if request.method == 'POST': print(request.POST) if form.is_valid(): user = form.save() user.set_password(request.POST.get('password')) user.save() nid = request.POST.get('nid') password = request.POST.get('password') user = authenticate(request, nid=nid, password=password) login(request,user,backend='django.contrib.auth.backends.ModelBackend') messages.success(request, 'User created successfully') return redirect('/') else: print("Form invalid") context = {'form': form} return render(request, 'home/signup.html',context=context) Now, … -
how to use variable in html templates django
I would to use the variable to setup name and age in my html files for app in Django. my code is: myapp\views.py from django.shortcuts import render # Create your views here. def test1(request): myname = 'abc' myage = 30 context = {'name': myname,'myage' : myage} return render(request,'index1.html',context) myapp\urls.py from django.urls import path from . import views urlpatterns = [ path('test1/',views.test1) ] myapp\templates\index1.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>thang1</title> </head> <body> <h1>this is template test1</h1> <p>I'm {{ myage }} years old</p> <p>My name is {{ myname }} </p> </body> </html> with above code, only get myold , it can not take myname. Can someone help assist me on this ? I would like to have both myname and my age in the html view. -
How i can add correctly data to an existing choicefield and save it in database: Django
I want to add some choices to an exiting fieldchoice from the database, I have did that in my views.py: if request.method == 'GET': form = FormOperation(instance=request.user, ) var = Metry.objects.filter(user=request.user).last().profile.name varr = Metry.objects.filter(user=request.user).last().profile.category form.fields['dite'].choices.append((varr, var)) print(form.fields['dite'].choices) models.py: dite = models.CharField(null = True, max_length=60,choices = CHOICES) forms.py: class FormOperation(forms.ModelForm): class Meta: model = Operation exclude = ("user",) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) after "append" the choice , As a test I have did a "print" to see the choice and it's normal i can see it in my terminal, but not in the page browser of my django application indeed ,i can see just the first choices without considering what i have append in my views.py,... Any help will be appreciated. -
importerror: cannot import name 'ungettext' from 'django.utils.translation'
I upgraded to django 4. I have realized that I get this error when Irun python manage.py runserver What did it change to??? importerror: cannot import name 'ungettext' from 'django.utils.translation' -
How to subtract values when product is added to shopcart
I have been successful when subtracting quantity of my product when an order is made. I have also been successful subtracting values for the user when product is added to shopcart. The problem is I cannot subtract the variant of the product. It says "Variants matching query does not exist." Here is my code. models.py class Product(models.Model): VARIANTS = ( ('None', 'None'), ('Size', 'Size'), ('Color', 'Color'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) #many to one relation with Category title = models.CharField(max_length=150) image = models.ImageField(null=False, upload_to='images/') price = models.DecimalField(max_digits=12, decimal_places=2,default=0) amount = models.IntegerField(default=0) variant = models.CharField(max_length=10, choices=VARIANTS, default='None') detail = RichTextUploadingField() slug = models.SlugField(null=False, unique=True) def __str__(self): return self.title class Variants(models.Model): title = models.CharField(max_length=100, blank=True,null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) color = models.ForeignKey(Color, on_delete=models.CASCADE,blank=True,null=True) size = models.ForeignKey(Size, on_delete=models.CASCADE,blank=True,null=True) image_id = models.IntegerField(blank=True,null=True,default=0) quantity = models.IntegerField(default=1) price = models.DecimalField(max_digits=12, decimal_places=2,default=0) def __str__(self): return self.title class ShopCart(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) variant = models.ForeignKey(Variants, on_delete=models.SET_NULL,blank=True, null=True) # relation with variant quantity = models.IntegerField() def __str__(self): return self.product.title views.py def product_detail(request,id,slug): query = request.GET.get('q') current_user = request.user category = Category.objects.all() product = Product.objects.get(pk=id) if product.variant != 'None': variantid = request.POST.get('variantid') # from variant add to cart checkinvariant … -
ISSUES SENDING MAIL FROM DJANGO
I get the following error when trying to send mails to users after a successful registration on my app "raise SMTPConnectError(code, msg) Exception Type: SMTPConnectError at /register/ Exception Value: (421, b'Server busy, too many connections') " Any idea on how to go about this my email settings configuration looks like this EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT= 587 EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD= os.environ.get('EMAIL_PASS') EMAIL_USE_TLS= True -
How to link my HTML form to a view class in Django
post_form.Html This is an Html Page With Form to Update and Create As We Know that Create And Update View Class in Django used the same form <form method="post"> {% csrf_token %} <div class="form-group"> <label for="PostInput">PostTitle</label> <input class="form-control" type="text" name="post" placeholder="Name" value="{{ post.postname }}"> </div> <div class="form-group"> <label for="descrInput">Description</label> <input class="form-control" type="text" id="descrInput" placeholder="Description" value="{{ post.description }}"> </div> <input type="submit" value="Save"> </form> Views.py class CreatePost(CreateView): model = post fields = ['title', 'content'] class UpdatePost(UpdateView): model = post fields = ['title', 'content'] Now, the question is how can i link this form with the above html page which already has form or input fields in the web page itself. I know how to do it using function views but i am not getting any materials, tutorials anything about this. Any Material regarding this will be helpful -
django transition between pages with saving data
Tell me how to implement, I just can’t figure it out, I’m still learning. Page1 opens and is created with forms.ModelForm +Meta. It has several inputs (text, selects, date) and 2 more inputs: input_hidden and input_text with the "select" button, as well as the "submit" button (sending to save to the database). By clicking on the "select" button, Page2 opens (like a reference book) with a table and a selection button, the desired row is selected in the table through the radiobutton and by pressing the selection button return to Page1 with data, so that the id of the selected element is recorded in input_hidden in value, and the text of the element string itself was written to input_text. At the same time, if before pressing the button on Page1 data were entered into some other inputs, then when returning from Page2, they retained their values. I can assume that it is possible to do something with saving data through a session, or some other simpler way to organize such a process. -
save data from a user In the form of a choicefield on database
I get information from the user through the following form. I want it to be the same optionally in the admin panel, that is, if I wanted to edit, I would only edit one of the options. in admin panel I want to be able to select in the admin panel, for example, if you need to change something, I can select its value, such as a form Models.py class Reservation_Date(models.Model): date = models.CharField(max_length=20) reservation_received = models.ForeignKey(Reservation_Item, on_delete=models.CASCADE) class Reservation_Received(models.Model): name = models.CharField(max_length=50) date = models.CharField(max_length=50) time = models.CharField(max_length=50) count = models.CharField(max_length=50) table_number = models.CharField(max_length=50) is_read = models.BooleanField(default=False , verbose_name='Read / Unread') views.py if request.method == "POST" and request.POST.get('name'): reservation = Reservation_Received() reservation.name = request.POST.get('name') reservation.date = request.POST.get('date') reservation.time = request.POST.get('time') reservation.count = request.POST.get('count') reservation.table_number = request.POST.get('table_number') try: reservation.save() return JsonResponse({'msg':'Success'}) except IntegrityError: return JsonResponse({'msg':'Error'}) -
How can I override __str__ in models.py?
Apologies if this is a silly question, I am pretty new to python and django. I am following along with a django tutorial, and we are creating a fake movie site that lists movies by genre, title, etc. I am currently trying to override the __str__ function in the models.py file, so rather than displaying Genre (1), it displays the actual genre (ex. "Action"). Here's how my models.py looks currently: from tkinter import CASCADE from django.db import models from django.utils import timezone # Create your models here. class Genre(models.Model): name = models.CharField(max_length=255) def __str__ (self): return self.name class Movie(models.Model): title = models.CharField(max_length=255) release_year = models.IntegerField() number_in_stock = models.IntegerField() daily_rate = models.FloatField() genre = models.ForeignKey(Genre, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) However, vscode is underlining the def __str__ (self): When I hover over it, it tells me: str does not return str pylint(E0307: invalid -str- returned I tried looking at other solutions, but I could not find one that seemed to match my scenario, so I do apologize if this has been solved elsewhere, and I am too incompetent to understand the problem. Thanks for your patience! -
In django, views here i ran into a problem that my varible called created{"created" is not accessed} so plz see my code and tell me answer
I am just showing my views.py because problem is just here after at third line after order. def cart(request): customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() context = {'items':items} return render(request, 'store/cart.html', context) Here ,i also dont know that why we use a word like created, what is its purpose.Thanks. Blockquote -
Link Customer Django user to group and give them permission
I customized the Django user model, now I can't link my users to Django groups to give them permissions from django.db import models from django.core.validators import RegexValidator from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser, PermissionsMixin) from django.db.models.signals import post_save from django.contrib.auth.models import Group USERNAME_REGEX = '^[a-zA-Z0-9.+-]*$' class UserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) if group is not None: group.user_set.add(user) return user # user.password = password # bad - do not do this def create_superuser(self, username, email, password=None): user = self.create_user(username, email, password=password) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) if group is not None: group.user_set.add(user) return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=300, validators=[ RegexValidator(regex=USERNAME_REGEX, message='Username must be alphanumeric or contain numbers', code='invalid_username')], unique=True) email = models.EmailField(max_length=255, unique=True, verbose_name='email address') is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.username def get_short_name(self): # The user is identified by their email address return self.username def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to … -
DJANGO REST + DJOSER /api/auth/users/activation get invalid user or token wrong error
I should create a auth get method, but /auth/users/activation get error { "uid": [ "Invalid user id or user doesn't exist." ] } This error appeared after errors like "this token not valid for this user". In email userid field is string like "MTE", "Mw"... User activation signal not working Djoser params DJOSER = { "LOGIN_FIELD": "email", "PASSWORD_CHANGED_EMAIL_CONFIRMATION": True, 'PASSWORD_RESET_CONFIRM_URL': 'api/users/users/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'api/users/users/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'api/users/users/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': { "user_create": "restapi.app.serializers.RegistrationSerializer", "user": "restapi.app.serializers.UserSerializer", "current_user": "restapi.app.serializers.UserSerializer" }, 'PERMISSIONS': { 'user_list': ['rest_framework.permissions.AllowAny'], } } restapi/app/serializers.py from rest_framework import serializers from restapi.app.models import * from .docs import * from django.contrib.auth.models import User class PioneerProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PioneerProfile fields = ["elo", "max_elo", "min_elo"] class UserSerializer(serializers.HyperlinkedModelSerializer): description = serializers.CharField(source="profile.description") pioneer = PioneerProfileSerializer() class Meta: model = User fields = ["id", "username", "first_name", "last_name", "description", "email", "date_joined", "pioneer"] class RegistrationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ["email", "username", "first_name", "last_name", "email", "password"] def validate_username(self, value): check_query = Genre.objects.filter(name=value) if self.instance: check_query = check_query.exclude(pk=self.instance.pk) if self.parent is not None and self.parent.instance is not None: genre = getattr(self.parent.instance, self.field_name) check_query = check_query.exclude(pk=genre.pk) if check_query.exists(): raise serializers.ValidationError('A Genre with this name already exists.') return value restapi/app/signal.py from django.dispatch import receiver from djoser.signals import user_activated from .models … -
Django:no module named app_name
I am watching a djano rest framework tutorial, and I am doing the same but ,I don't know why it gives 'No module named 'api' error', I included app in settings, and tried many things on internet so far but it did not work. What is the reason for that error? I have always worked like that with no problem. urls.py from xml.etree.ElementInclude import include from django.contrib import admin from django.urls import path, include from api import views urlpatterns = [ path('admin/', admin.site.urls), path('api/',views.api_home) ] views.py from django.http import JsonResponse from django.shortcuts import render def api_home(request): return JsonResponse({'message':'it is your json response'}); settings.py """ Django settings for cfehome project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/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.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-x9upz#&nqh!m=^rb^ozgrbi=!6*3t$3ucml^0c@s^^fjb=dp-j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', … -
update a field in all records of a table through a single form Django 4
I have the following model 'ARTICULO', which I have created and templates to edit it individually # MODEL class Articulo(models.Model): id = models.AutoField(primary_key=True, verbose_name='codigo') nombre = models.CharField(max_length=100, verbose_name='nombre elemento') cantidad = models.PositiveSmallIntegerField(verbose_name='cantidad total') cantidad_disponible = models.PositiveSmallIntegerField(verbose_name='cantidad disponible', default=5) UNIDAD = 'und' KILO = 'kg' LITRO = 'L' UNIDADES_BASE = [ (UNIDAD, 'unidades'), (KILO, 'Kilogramos'), (LITRO, 'litros'), ] unidades = models.CharField(max_length=3, choices=UNIDADES_BASE, default=UNIDAD, verbose_name='unidad base') area = models.CharField(max_length=100, verbose_name='tipo inventario', default='primaria') persona_asignada = models.CharField(max_length=100, default='almacen', verbose_name='persona asignada') def __str__(self): trama = "articulo: " + self.nombre return trama #form to edit individually class ArticuloEditarForm(forms.ModelForm): class Meta: model = Articulo fields = ['nombre', 'cantidad', 'unidades'] # view for generate form of individual article def editar(request, id): articulo = Articulo.objects.get(id=id) formulario = ArticuloEditarForm(request.POST or None, instance=articulo) if formulario.is_valid() and request.POST: formulario.save() return redirect('inventario_inicio') return render(request, 'inventario/editar.html', {'formulario': formulario}) but additionally I would like to create a page where I can perform an update of all the records of the table as a whole (as in the following image) When clicking on the button, all records with the checkbox activated are updated in the database according to the value indicated in their text box. From what I have investigated so far, I think I understand … -
Using django channels, graphene, DjangoChannelsGraphqlWs, cant get loggedin user info in subscriptions
Im building a simple chat application losely based on kimutaiRop implementation, using Django channels and graphene using DjangoChannelsGraphqlWs, for logging in im using social_django Problem being in all queries and mutations I am getting current logged in users info in the info variable. But in subscription i am unable to get current logged in user info. It is working on site, when logged into django, but on https://studio.apollographql.com/ using authorization token, signed in with google, the subscription function does not have any info on the current logged in user. this is my schema.py file. User = get_user_model() class ChatUserType(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = User fields = ["last_name", "first_name",'username', "email", "id", "isOnline"] interfaces = (relay.Node,) class MessageFilter(FilterSet): class Meta: model = Message fields = ("content", "read", 'timestamp',) order_by = ('timestamp', "id") class MessageType(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = Message fields = '__all__' interfaces = (relay.Node,) class RoomType(DjangoObjectType): id = graphene.ID(source='pk', required=True) unread = graphene.String() class Meta: model = Room fields = '__all__' interfaces = (relay.Node,) class Query(MeQuery, graphene.ObjectType): messages = DjangoFilterConnectionField( MessageType, filterset_class=MessageFilter, id=graphene.ID()) @staticmethod def resolve_messages(cls, info, id, **kwargs): user = info.context.user if user is None or not user.is_authenticated: raise Exception("You need to … -
Django: How to download a file on client after an Ajax request
I have a django app where users can save their contacts. I am not building a flow to allow users to download their contacts locally. To do so, I built a CTA ("download") that if clicked Gets the id of the contact selected Triggers an Ajax request to my views In the view I get the contact id, retrieve the data from my DB and create a VCF card out of it. (A contact card - basically a text file) Now I would like to have such file downloaded on the client's machine but I don't know how to do it. I managed to do it if I redirect to a new url where the view does exactly what my view below does, I want to allow users to download the file without being redirected to a new page. Also, trying to avoid storing the contact ids in the URL. That's why I am trying to use ajax but I think that's creating problems because and Ajax request waits JsonReponse from the view. I tried both a GET or POST but it's not working. This is my view currently: def get(self, request, *args, **kwargs): #Get the ids ids = request.GET.getlist('contact_ids[]') … -
How do I get the name of the container to show instead of the id?
So I am trying to figure out how to display the ForeignKey name in the view I have thought about using map method and get the object from the ID and getting the name from said ID, but that doesn't seem to work. I could be doing it wrong but I am not quite sure. JSON Response [ { "id": 3, "name": "Coke", "description": "Cocaine Drink", "container": 3 }, { "id": 4, "name": "Another One", "description": "Dj Khaled Drink", "container": 3 }, { "id": 5, "name": "Testy", "description": "Westy", "container": 4 } ] View class ListDrinks(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): drinks = Drink.objects.all() serializer = DrinkSerializer(map(DrinksId, drinks), many=True) return Response(serializer.data) def post(self, request, format=None): serializer = DrinkSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Models class Container(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Drink(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=500) container = models.ForeignKey( Container, on_delete=models.CASCADE, null=True) def __str__(self): return self.name