Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Fixing UnicodeDecode Error Decoding
I am following a Django CRUD tutorial and am getting this error when I try and load my url. The rest of my views all work except this one, and I've never seen this error before. I googled similar issues and found a few proposed solutions (posted below) but nothing has worked on my end. Any ideas how to fix this? I have already tried adding from __future__ import unicode_literals and def __str__(self): return "(%s)" % self.name into my views.py file with no luck 'utf-8' codec can't decode byte 0xd7 in position 2046: invalid continuation byte html {% extends 'base.html' %} {% load static %} {% block title %}Django Ajax CRUD{% endblock %} {% block content %} <div class="container"> <h1>Django Ajax CRUD</h1> <div class="row"> <div class="col-md-4 "> <h3>ADD USER</h3> <form id="addUser" action=""> <div class="form-group"> <input class="form-control" type="text" name="name" placeholder="Name" required> </div> <div class="form-group"> <input class="form-control" type="text" name="address" placeholder="Address" required> </div> <div class="form-group"> <input class="form-control" type="number" name="age" min="10" max="100" placeholder="Age" required> </div> <button class="btn btn-primary form-control" type="submit">SUBMIT</button> </form> </div> <div class="col-md-8"> <h3>USERS</h3> <table id="userTable" class="table table-striped"> <tr> <th>Name</th> <th>Address</th> <th colspan="3">Age</th> </tr> {% if users %} {% for user in users %} <tr id="user-{{user.id}}"> <td class="userName userData" name="name">{{user.name}}</td> <td class="userAddress userData" … -
Running Django with gunicorn (on a K8s node created from a Docker Image) produces poor performance and CORS errors
I'm Deploying Django via gunicorn onto a K8s node from a Docker Image. For a Dockerfile using CMD python manage.py runserver 0.0.0.0:8000, the front end works fine. For a Dockerfile using CMD gunicorn ..., frontend either loads SUPER-slow or fails: Here's the Dockerfile: FROM python:3.9-buster LABEL maintainer="hq@deepspaceprogram.com" RUN apt-get update && \ apt-get upgrade -y && \ apt-get install -y gcc && \ apt-get install -y git && \ apt-get install -y libcurl4 && \ apt-get install -y libpq-dev && \ apt-get install -y libssl-dev && \ apt-get install -y python3-dev && \ apt-get install -y librtmp-dev && \ apt-get install -y libcurl4-gnutls-dev && \ apt-get install -y libcurl4-openssl-dev && \ apt-get install -y postgresql-9.3 && \ apt-get install -y python-psycopg2 ENV PROJECT_ROOT /app WORKDIR /app # install python packages with poetry COPY pyproject.toml . RUN pip3 install poetry && \ poetry config virtualenvs.create false && \ poetry install --no-dev COPY accounts accounts COPY analytics analytics COPY commerce commerce COPY documents documents COPY leafsheets leafsheets COPY leafsheets_django leafsheets_django COPY marketing marketing COPY static static COPY manage.py . # This should be an empty file if building for staging/production # Else (image for local dev) it should contain the complete .env … -
I want to create a database record with a click of a button, when im clicking a button, nothing happens. Could anyone tell me what am I doing wrong?
I want to create a database record with a click of a button (registered user answers to a question selected from 2 possible answers represented by two buttons), when im clicking a button, nothing happens. Could anyone tell me what am I doing wrong? html page <form action="." method="post"> {% for q in questions_data %} <ul> <li>{{ q.question }}</li> </ul> {% csrf_token %} <button type="submit" name="butt_ans" value="{{ q.answer1.value }}">{{ q.answer1 }}</button> <button type="submit" name="butt_ans" value="{{ q.answer2.value }}">{{ q.answer2 }}</button> {% endfor %} </form> views.py @login_required def select_interests(request): questions_data = InterestQuestion.objects.all() if request.method == 'POST': questionnaire_form = InterestSelectionForm(request.POST) if questionnaire_form.is_valid(): test = questionnaire_form.cleaned_data.get("value") else: questionnaire_form = InterestSelectionForm() return render(request, 'quiz/quiz_form.html', locals()) forms.py class InterestSelectionForm(forms.ModelForm): class Meta: model = UserInterest fields = ('selectedInterest',) models.py class UserInterest(models.Model): q_id = models.ForeignKey(InterestQuestion, on_delete=models.CASCADE) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) selectedInterest = models.CharField(max_length=64) -
tuple indices must be integers or slices, not tuple
I'll try to make a JSON for i in ktg_mhs: chart_ktg ={ 'value' : ktg_mhs[i][1], 'name' : ktg_mhs[i][0] } result.append(chart_ktg) data = json.dumps(chart_ktg) but, I get an error at this 'value' : ktg_mhs[i][1], 'name' : ktg_mhs[i][0] How to solve it and why? -
inputs are not being stored in Mysql database
i am currently having an issue with my program my some of my input are not being saved in the MySQL database - any help will be appreciated this creates a custom user which are the employee, admin and senior employee - this is a different model so another table class CustomUser(AbstractUser): user_type_data=((1,"Admin"),(2,"senioremployee"),(3,"employee")) user_type=models.CharField(default=1,choices=user_type_data,max_length=20) this the model for one of my usertypes class senioremployee(models.Model): id = models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE) Dob = models.DateField() Nationality = models.TextField() Address = models.TextField() Postcode = models.TextField() Telephone = models.TextField() Wage = models.TextField() Passportnumber = models.TextField() passportexpirydate = models.DateField() gender = models.CharField(max_length=255) profile_pic = models.FileField() kinname = models.TextField() kinrelation = models.TextField() kinaddress = models.TextField() kinphonenumber = models.TextField() kinemail = models.TextField() created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects = models.Manager() this function add user's data to the table @receiver(post_save,sender = CustomUser) def create_user_profile(sender,instance,created,**kwargs): if created: if instance.user_type==1: admin.objects.create(admin = instance,Dob="",Nationality="",Address="",Postcode="",Telephone="",Wage="",Passportnumber="",passportexpirydate="",gender="",profile_pic="",kinname="",kinrelation="",kinaddress="",kinphonenumber="",kinemail = "") if instance.user_type==2: senioremployee.objects.create(admin = instance,Dob="",Nationality="",Address="",Postcode="",Telephone="",Wage="",Passportnumber="",passportexpirydate="",gender="",profile_pic="",kinname="",kinrelation="",kinaddress="",kinphonenumber="",kinemail = "") if instance.user_type==3: employee.objects.create(admin = instance,Dob="",Nationality="",Address="",Postcode="",Telephone="",Wage="",Passportnumber="",passportexpirydate="",gender="",profile_pic="",kinname="",kinrelation="",kinaddress="",kinphonenumber="",kinemail = "") this is the function that is meant to save the inputs into the senioremployee's table and email,password , firstname, lastname,username into the custom user's table but currently it only stores email,password , firstname, lastname,username into the custom user's table and just ignores the other user … -
Django jquery ajax comment reply create multiple values
I am in pazzle to create a comment reply activities using django jquery and ajax. It's create multiple values to comment or reply on blog. How can I solve this problems? Thanks in advance. models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField(max_length=1000) reply = models.ForeignKey('Comment', on_delete=models.CASCADE, related_name='replies', null=True, blank=True, default=None) post = models.ForeignKey('Post', related_name='comments', on_delete=models.CASCADE) objects = models.Manager() class Meta: ordering = ['-timestamp'] def __str__(self): return self.user.username comment_section.html {% extends "base.html" %} {% block content %} <div class="container-fluid mt-2"> <div class="form-group row"> <form class="comment-form" method="post" action="."> {% csrf_token %} <div class="form-group"> <textarea name="content" cols="60" rows="2" maxlength="1000" required="" id="id_content"></textarea> </div> <button type="submit" value="submit" class="btn-sm btn-outline-warning" style="color: black;">Comment</button> </form> </div> </div> {% if not post.comments.all %} <small>No comments to display</small> {% endif %} {% for comment in comments %} <blockquote class="blockquote"> <img style="float:left; clear: left;" class="rounded-circle article-img" height="10" width="10" src="#"><a href="#" style="text-decoration: none; color: black;"><h5>{{ comment.user.username|capfirst }}</h5></a> <p style="font-size: 8px;">{{ comment.timestamp }}</p> <p style="font-size: 14px;" class="mb-3">{{ comment.content }}</p> <a type="button" name="button" class="reply-btn ml-4"><i class="fas fa-reply fa-sm"></i></a>&emsp; {% if request.user == comment.user %} <a href="#"><i class="fas fa-trash fa-sm" style="color: brown;"></i></a></td> {% endif %} </blockquote> {{ comment.replies.count }} <div class="replied-comments col-md-5" style="display: none;"> {% for reply in comment.replies.all %} … -
Mock a test with a external api rest in Django Rest Framework
Context I am developing an API Rest with Django Rest Framework, and some of my endpoints consume an external API Rest to create a model instance, the code works but right now I am trying to test my code but I have very struggled with that. I am a little beginner developing tests and maybe the question is very obvious but, I tried so many things, with the below links but I couldn't achieve it. Mocking external API for testing with Python How do I mock a third party library inside a Django Rest Framework endpoint while testing? https://realpython.com/testing-third-party-apis-with-mocks/ Codes This is my view from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.response import Response from app.lnd_client import new_address from app.models import Wallet from api.serializers import WalletSerializer class WalletViewSet(viewsets.ModelViewSet): queryset = Wallet.objects.all() serializer_class = WalletSerializer lookup_field = "address" @action(methods=["post"], detail=False) def new_address(self, request): response = new_address() if "error" in response.keys(): return Response( data={"error": response["error"]}, status=response["status_code"] ) else: return Response(response) def create(self, request, *args, **kwargs): response = self.new_address(self) if response.status_code >= 400: return response serializer = self.get_serializer(data=response.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response( serializer.data, status=status.HTTP_201_CREATED, headers=headers ) This is my client with the call to the external api … -
Is there any way to organize filelds in django models?
I have many tables in my django models, each responsible for a different form in my template. I wrote some code to convert this fields directly into tempalte using python and JavaScript. Next I've been trying to add sections into template, which means that in my template each section has own title and own fields. After a few tries my code looked like an example: #before class forms_n(Models.Model): field1 = models.IntegerField() field2 = models.ForeignKey(ForeignModel, on_delete=models.CASCADE,null=False,blank=False) field3 = models.IntegerField() field4 = models.IntegerField() #after class form_n_cfg: @section_decorator(section=0,title="This is seciton 0") class form_n_0(models.Model): field1 = models.IntegerField() field2 = models.ForeignKey(ForeignModel, on_delete=models.CASCADE,null=False,blank=False) class Meta: abstract = True @section_decorator(section=1,title="This is seciton 1") class form_n_1(models.Model): field3 = models.IntegerField() field4 = models.IntegerField() class Meta: abstract = True class form_n(forms_n_cfg.form_n_0,forms_n_cfg,form_n_1): pass #utils.py def section_decorator(**kwargs): def set_attrs(obj): fields = obj._meta.fields for i in fields: for key,value in kwargs.items(): setattr(getattr(obj,i.name),key,value) return obj return set_attrs Everything worked fine, in time I realized that Foreignkey unlike other fields doesn't have any values from my decorator. I think the problem is because i added attrs to for parent class, not subclass form_n which i use (just why other fields had values from decorator). I noticed that just classes inner form_n_cfg has @section_decorator attributes for … -
Django variable inside static tag?
This is part of index.html: {% for listing in active_listings %} <tr> <td>{{ listing.title }}</td> <td>{{ listing.description }}</td> <td>{{ listing.bid }}$</td> {% if listing.image %} <td>{{ listing.image }}</td> <td><img src="{% static 'auctions/'|add:listing.image %}" alt="photo"></td> {% else %} <td>No photo.</td> {% endif %} </tr> {% endfor %} This is the corresponding views.py: def index(request): return render(request, "auctions/index.html", { "active_listings": Listing.objects.filter(active=True), }) And that is my Listing Model: class Listing(models.Model): CATEGORIES = [ ('BO', 'Books'), ('TO', 'Toys'), ('EL', 'Electronics'), ('FA', 'Fashion'), ('HO', 'Home'), ] title = models.CharField(max_length=64) description = models.TextField(max_length=256) bid = models.PositiveIntegerField() image = models.ImageField(null=True, blank=True) category = models.CharField(max_length=2, choices=CATEGORIES, null=True, blank=True) active = models.BooleanField(default=True) Why can't I add the variable listing.image in the html??? It gives me: "GET /static/ HTTP/1.1" 404 1634 -
Django: models setup for using one database to populate another
I'm rebuilding a personal project in Django, (a family tree), and I'm working on migrating the actual data from the old awkward database to my new model/schema, both Postgres databases. I've defined them in the DATABASES list on settings.py as 'default' and 'source'. I've made my models and I'd like to copy the records from the old database into their corresponding table in the new database, but I'm not quite understanding how to set up the models for it to work, since the Django code uses the models/ORM to access/update/create objects, and I only have models reflecting the new schema, not the old ones. In a coincidental case where I have a table with the exact same schema in the old and new database, I have a management command that can grab the old records from the source using my new ImagePerson model (ported_data = ImagePerson.objects.using('source').all()), since it the expected fields are the same. Then I save objects for them in the 'default': (obj, created_bool) = ImagePerson.objects.using('default').get_or_create(field=fieldvalue, etc), and it works just like I need it to. However when I have a table where the old version is missing fields that my new model/table have, I can't use the model … -
defined class and function not recognized
I defined a board object as follow: class Board(models.Model): #let's do the relational part after I've done the other fields Title = models.CharField(max_length=255) Description = models.TextField(blank=True) #where I got the image https://mixkit.co/blog/trello-backgrounds-awesome-free-illustrations-for- trello-boards/ ImageUrl = models.URLField( default="https://mixkit.imgix.net/art/preview/mixkit-starry-night-sky-over-hills-and-water-85- original-large.png?q=80&auto=format%2Ccompress&h=700&q=80&dpr=1", blank=True, null=False) CreatedAt = models.DateTimeField(default=timezone.now) EndsAt = Board.return_date_time_in_one_year() def __str__(self): return self.title def return_date_time_in_one_year(self): now = timezone.now() return now + timedelta(years=1) When I try to migrate I get the following error, I'm not sure where I went wrong in how I defined the classes, I'm new to both python and django. File "C:\Users\Ameer\Documents\GitHub\Squasha_trello_clone\squasha\board\models.py", line 16, in Board EndsAt = Board.return_date_time_in_one_year() NameError: name 'Board' is not defined -
django view pass json to javascript
I try to pass json to javascript. I want make json like this data: [ { value: 335, name: 'Coding' }, { value: 310, name: 'Database' }, { value: 234, name: 'UIX' }, { value: 135, name: 'Manajemen' },] }] I want make json like this, so I can put to javascript { value: 335, name: 'Coding' }, And this is my code cursor.execute('SELECT u.nama_ktgu, COUNT(m.nim) as jml FROM mahasiswa_mhs_si m, mata_kuliah_kategori_utama u, mata_kuliah_kategori k WHERE k.kode_ktgu_id = u.id AND m.kode_ktg_id = k.id GROUP BY k.id') ktg_mhs = cursor.fetchall() #JSON CHART chart_ktg = {} for i in ktg_mhs: chart_ktg['value'] = ktg_mhs[i][1] chart_ktg['name'] = ktg_mhs[i][0] json = json.dumps(chart_ktg) -
Cannot login my DRF dashboard using simpleJWT, it only works when SessionBased authentication is used (I don't want SessionBased auth)
I have a django project that uses 'rest_framework_simplejwt.authentication.JWTAuthentication' as the default authentication class. To my understanding this is a stateless token that does not use SessionAuthentication. In my DRF home screen (the default dashboard created by drf), I'm trying to log-in, using the top-right button on the screen, however it's not working. Here is the error I get: { "detail": "Authentication credentials were not provided." } After testing, said login button only works when SessionAuthentication is the default class and path('home-auth/', include('rest_framework.urls', namespace='rest_framework')) is placed in my global urls.py. I read about scalability issues when having a Session based auth system, so I would like to refrain from using it. I have created an app, users, that has it's own login URL serializer/view, and uses the JWT authentication method, it works just fine without errors. I thought that method would be the default login verification method that DRF would use but that is not the case due to the error above. I can login just fine when I use my users login url. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'drf_yasg', # Third Party Apps #'admin_honeypot', 'rest_framework', 'django_filters', 'corsheaders', 'rest_framework_simplejwt.token_blacklist', # Apps 'users', ] REST_FRAMEWORK = { … -
Django allow user to edit information
I am trying to allow users to update their profile information but nothing happens upon submit. I thought I had every part covered but clearly missing something. On submit the changes for name do not take effect, it reloads the page and shows the old name. Also, does anyone have any feedback on how to update data based on a select tag? My views.py def Info(request): if request.method == "POST": form = ProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('pages/info.html') else: form = ProfileForm(instance=request.user) args = {'form': form} return render(request, 'pages/info.html', args) My forms.py class ProfileForm(UserChangeForm): class Meta: model = Account fields = ( 'name', 'fruits' ) exclude = ( 'is_active', 'password' ) My template <form method="POST" action=""> {% csrf_token %} <div class="col-md-6"> <label class="labels">name</label> {{ form.name}} </div> <div class="col-md-12"> <label for="cars">fruits</label> <select name="fruits" class="custom-select"> <option value="ap">apple</option> <option value="ba">banana</option> </select> </div> <input type="submit" value="Update"> </form> -
A quick question regarding threading module in Django?
I'm building a scrapper that crawls through URLS and finds emails. I've found out that threading can make this crawling process faster and I'm trying to implement it on Django. But there is a lot of information lacking in regards to this module. One quick question I would like to ask is how would someone know if threading is running correctly on Django. Would this code be enough to run threading? from django.shortcuts import render from django.shortcuts import render from .scrapper import EmailCrawler from django.http import HttpResponse from celery import shared_task from multiprocessing import Process import threading def index(request): return render(request, 'leadfinderapp/scrap.html') t = threading.Thread(target=scrap) t.start() def scrap(request): url = request.GET.get('Email') crawl = EmailCrawler(url) target = crawl.crawl() email_list = crawl.emails # or whatever class-level variable you use return render(request, 'leadfinderapp/results.html', {"email_list": email_list}) Thank you very much any help I would really appreciate it. -
Django templates: if .. in
I have a list of products and want to display them in a template, depending on whether or not the product's dealer is "owned" by the current logged user or not. So here's my view: class ArticleListView(ListView, LoginRequiredMixin): template_name = "accounts/list_article_quentin.html" model = Product def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context["website"] = Website.objects.first() context["product_list"] = context["product_list"].filter(published=True) # Get a list of all dealers associated to the current users. currentUserDealers = self.request.user.dealers.all().values_list('id', flat=True) context["current_user_dealers"] = list(currentUserDealers) return context so currentUserDealers is the list of the dealers associated to the current user (It's a ManyToMany relationship between dealers and users). In my template, I would like to do something like that to decide wether to display the product or not: {% if product.dealer.all.0.pk in current_user_dealer %} (there can be multiple dealers for a product but I'll see that later, hence the all.0) Obviously this doesn't work but you get the idea, I want to see if the current product's dealer ID is in the list of current user's associated dealers, to see if we display it or not. What's the syntax to do it in the template? Or maybe there's a better way to do this directly in the view? -
How to render template tags in the views and send them to Ajax calls
In Django i am using bootstrap4 form from the package django-bootstrap4 it renderst the form using {% bootstrap_form form %} Now i just need only this part using a view like @api_view(['GET']) def rendertemplatetag(request) form = DeviceForm() rendered_template = bootstrap_form(form) <-- something like this where renedered_template can be string # return as json return HttpResponse(rendered_template,status=200,content_type="application/json") I am using DRF for this view this view can be called with ajax and then the returned html can be substituded at its place -
Testing a simple Django view gives 404
I have a simple view that returns <h1>Hello world</h1>. It works when running the server, but in tests, it 404s. I'm using reverse and it returns the right path in the test...so I know the view is registered even in the tests. I've followed Django 3.1's guides and many SO answers already, but can't figure it out. Any help's appreciated! Here's my code: foo/views.py from django.http import HttpResponse def hello(request): text = '<h1>Hello world</h1>' return HttpResponse(text) foo/urls.py from django.conf.urls import url from django.contrib import admin from django.urls import path from .views import hello urlpatterns = [ path('admin/', admin.site.urls), url(r'^hello/', hello, name = 'hello'), # I've also tried: path('hello/', hello, name = 'hello'), ] foo/tests/test_hello.py from django.test import TestCase from django.urls import reverse class SimpleTest(TestCase): def test_hello(self): path = reverse('hello') print(path) response = self.client.get(path) print(response.content) self.assertEqual(response.status_code, 200) Test output $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). /hello/ b'\n<!doctype html>\n<html lang="en">\n<head>\n <title>Not Found</title>\n</hea d>\n<body>\n <h1>Not Found</h1><p>The requested resource was not found on this server.</p>\n</body>\n</html>\n' F ====================================================================== FAIL: test_details (foo.tests.test_hello.SimpleTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/-------/foo-project/foo/tests/test_hello.py", line 12, in test_details self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 1 test in … -
Django unlike button query for blog post
Hi I think i made a minor error but i'm unable to figure. Basically AttributeError: 'QuerySet' object has no attribute 'exist' This line is the problem: if blog_post.likes.filter(id=request.user.id).exist(): Can anyone advise me on how to change it for the query to work properly. thank you! Views.py def detail_blog_view(request, slug): context = {} #need to import a package get_object_or_404. return object or throw 404 blog_post = get_object_or_404(BlogPost, slug=slug) total_likes = blog_post.total_likes() liked = False if blog_post.likes.filter(id=request.user.id).exist(): liked = True context['liked'] = liked context['blog_post'] = blog_post context['total_likes'] = total_likes return render(request, 'HomeFeed/detail_blog.html', context) def LikeView(request, slug): context = {} #set a user variable user = request.user #if user is not authenticated, redirect it to the page call "must authenticate.html" which isnamed as must authenticate if not user.is_authenticated: return redirect('must_authenticate') post = get_object_or_404(BlogPost, slug=slug) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return redirect('HomeFeed:detail', slug=slug) html: <form action="{% url 'HomeFeed:like_post' blog_post.slug %}" method="POST" >{% csrf_token %} {% if liked %} <button type="submit" name="blog_post_slug" value="{{blog_post.slug}}" class='btn btn-danger btn-sm'>Unlike</button> {% else %} <button type="submit" name="blog_post_slug" value="{{blog_post.slug}}" class='btn btn-primary btn-sm'>Like</button> {% endif %} {{ total_likes }} Likes </form> This is the traceback: Internal Server Error: /HomeFeed/helloworld-1/detail/ Traceback (most recent call … -
django 'get_bound_field' error when rendering form with extra field in template
I'm using a modelformset using a modelform in which I created an extra-field. The formset is instanciated with a queryset.. all of this is working fine. My problems start when I want to assign a value to the extra_field in the init method of the form. here is the form : class SpotlerCreateForm(forms.ModelForm): name = ShrunkField( max_length=50, label=_("Name"), widget=forms.TextInput( attrs={ "placeholder": _("Give a name to this video... "), "help": _("name should have than 50 characters"), "class": "border-0 text-truncate pl-0", } ), required=True, ) duration = forms.TimeField( widget=forms.TimeInput( attrs={ "name": _("duration"), "readonly": True, "class": "duration text-center", } ), required=False, ) is_postedited = forms.BooleanField( widget=forms.CheckboxInput(), label=_("postedition"), label_suffix="", required=False, ) url = forms.URLField(widget=forms.HiddenInput()) class Meta: model = Spotler fields = [ "url", "name", "duration", "is_postedited", ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance: self.fields['url'] = self.instance.get_put_url(File.FULL) def clean_name(self): name = self.cleaned_data["name"] name = str_clean(name) if len(name) > 50: name = name[:50] return name I shortened my view in the code below: class AjaxSpotlerCreateView(View): def get(self, request): SpotlerFormSet = modelformset_factory(Spotler, form=SpotlerCreateForm, extra=0) s_formset = SpotlerFormSet( queryset=Spotler.objects.filter(id__in=[s.id for s in self.init_spotlers()]), prefix="spotlers", ) context = {"spotler_formset":spotler_formset} return render(self.request, "spotler/upload/sp2-upload_formset.html", context) and the part of the template using the formset is : <div class="border-top border-bottom … -
How to check if a user is logged in, in django token authentication?
Hi there I am currently starting a new rest api project with django. Normally when I start a new project I do a lot of planning and get a idea of how I want to build my app. For this app I want to use token authentication but can't find enough resources for this topic. Can anyone tell me these two things, how to check if a user is logged in/authenticated and how to check which user is logged in(of course with token authentication in django). Thank you in advance. Extra info(you don't need to read this): The reason I want to use this kind of authentication is because I don't want to use the built in django models for my user model because my User model has to have some specific fields for this web app, obviously I can work my way around this but its not very efficient so I figured I'd use token authentication. -
Django and mongoDb inspectdb command
this is the error I am getting whenever I am trying to inspect db through django in mongoDb: Unable to inspect table 'chats' # The error was: 'NoneType' object is not subscriptable. # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models # Unable to inspect table 'chats' # The error was: 'NoneType' object is not subscriptable -
Add form fields programmatically to Wagtail Form
I have a model which subclasses AbstractEmailForm.. I can create a new instance with: new_page = LanderPage(body='body text here', title='Test sub page', slug='testsub', to_address='j@site.com',from_address='j@site.com', subject='new inquiry') This works, but it produces a form without fields. I am not sure how to create the form fields using this structure, such as the form field for name and email address. Can someone point me in the right direction? For reference, this is the page being created: class LanderPageFormField(AbstractFormField): page = ParentalKey('LanderPage', related_name='form_fields') class LanderPage(AbstractEmailForm): body = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('body', classname="full"), InlinePanel('form_fields', label="Form fields"), FieldPanel('thank_you_text', classname="full"), MultiFieldPanel([ FieldRowPanel([ FieldPanel('from_address', classname="col6"), FieldPanel('to_address', classname="col6"), ]), FieldPanel('subject'), ], "Email"), ] -
How to embed a form multiple times with ListView (and once with DetailView)
I have the following listview and detailview structure. I would like to pass in a form to be shown with each object that is listed in the listview (and also with the one object when there is detailview). How can I get this to show up with each object? class ObjectListView(LoginRequiredMixin, ListView): model = Object ... date = (datetime.now() - timedelta(hours = 7)).date() queryset = Object.objects.filter(date=date) def get(self, request, *args, **kwargs): ... return super().get(request, *args, **kwargs) class ObjectDetailView(LoginRequiredMixin, DetailView): model = Object -
fetching data from backend with certain email address react native
I am having trouble trying to fetch only certain data entries from my backend with a specific email address. My backend stores data from multiple user but lets say I want to fetch only the data from johndoe@gmail.com rather than just fetching all the data. How would I go about putting a condition like that. Below is the code I am using to fetch data from my backend. fetchDataFromApi = () => { const url = "http://localhost:8000/api/list/"; fetch(url).then(res => res.json()) .then(res => { console.log(res) this.setState({myListData: res}) }) .catch(error => { console.log(error) }) }; So from the code, I am basically getting all the data and storing it into the state called myListData but I want to only store data for johndoe@gmail.com. Is there any where I can go about achieving this? Thank you in advance!