Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Dynamically populate the choices of a CharField with the fields of some other models: Models aren't loaded yet RegistryError
Good day everyone, hope you're doing really well. Straight to the point, let's say we have anpp w models: from django.apps import apps from django.db import models class A(models.Model): # A lot of fields go here class B(models.Model): # A lot of fields go here # And some more models ... class ModelChoices(models.TextChoices): A = 'A' B = 'B' ... class Filterset(models.Model): model = models.CharField(max_length=32, choices=ModelChoices.choices) attribute = models.CharField(max_length=32, choices=auto_generate_attributes().choices) def auto_generate_attributes(): all_attributes = set() for model_name in ModelChoices.values: ModelClass = apps.get_model(model_name) model_fields = ModelClass._meta.get_fields() model_attributes = [(attr.name, attr.name) for attr in model_fields] all_attributes.update(model_attributes), Attributes = models.TextChoices( 'Attributes', list(all_attributes), ) return Attributes Now you're probably wondering what's the point of this table. In short, I'll use it in a M2M relationship with another model so that an User can filter on values of different models at once and return a list of FK objects that all models share (Sounds abstract, but trust me). But the other models are still a work in progress and will edit/create new fields as time goes, that's why I have to generate them dynamically instead of hard-coding them. The issue is trying to get the models classes at initilization time to popuplate the choices of … -
django - how to use current user that loged in model (in the way that he cant choose another user)
i want to make a blog with django that any user can create posts and post owned by just that user .the author of the post most be the current user that loged in and never change. i have a problem to get current user in post model !! how i store current that wrote the post with post model ? from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils import timezone from ckeditor.fields import RichTextField class Post(models.Model): STATUS_CHOICES = { } TECHNOLOGY_CHOICES = { } title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique_for_date='publish') author = models.ForeignKey(User,on_delete=models.CASCADE,) body = RichTextField(config_name='default',blank=True, null=True) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') category = models.CharField(max_length=250,default='other') def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('index') -
copy models instance in django not working well
I want to copy blogpost model, i have consider foreign key relationship but still fail in test of blog_copy and blog_author_copy. Could anyone help me? class Author(models.Model): name = models.CharField(max_length=50) class BlogPost(models.Model): title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='blog_posts') date_created = models.DateTimeField(auto_now_add=True) def copy(self): new = BlogPost.objects.get(pk=self.pk) new.pk = None new.id = None new.date_created = datetime.now() # new.author.blog_posts.add(new) authors = Author.objects.all() for author in authors: if self.author == author: author.blog_posts.add(new) new.save() old = BlogPost.objects.get(pk=self.pk) for comment in old.comments.all(): comment.pk = None comment.blog_post = new comment.save() new.comments.add(comment) new.save() class Comment(models.Model): blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE, related_name='comments') text = models.CharField(max_length=500) -
Django - Can't access variable defined with template tag outside for loop
In a Django template, I have to signal that the if conditional was entered and for this I created a template tag: @register.simple_tag def setvar(val=None): return val And in my template I have: <div> {% for item in items %} {% if <!-- condition --> %} {% setvalor '1' as has_favorites %} {% endif %} {% endfor %} <div>{{ has_favorites }}</div> <!-- testing --> </div> The variable has_favorites is not rendered in the browser. It seems that the variable is only available in the for loop scope. Is there a way to workaround that? -
ValueError while logging out user from the page dynamically created by passing pk
I have a page search.html that has a link associated with a pk that when clicked redirects to page doc.html which outputs the contents related to that pk This doc.html extends a page consult_home.html. This page contains the logout button. In all the other pages that extends this consult_home.html the logout button works perfectly. But in the doc file I get the following error and the logout link does not work: ValueError at /consultancy/doc/logout Field 'id' expected a number but got 'logout'. Below are the codes of the view functions and the url patterns and also the template codes: consult_home.html* <button type="button" class="button log_out" onclick="location.href='logout';">LOGOUT</button> view function for logout def logoutUser(request): logout(request) return redirect('/') search.html <a class="judge-ttle" href="{% url 'doc' searches.pk %}">{{searches.title}} &nbsp <i class="fas fa-external-link-alt"></i></a> views for doc.html class DocDetailView(DetailView): model= Laws template_name = 'doc.html' urls.py urlpatterns=[ path('logout', views.logoutUser, name='logout'), path('doc/<str:pk>', DocDetailView.as_view(), name='doc' ), ] As I described above the user is unable to log out when he is in doc.html. How can I remove this Value Error. -
How to install Django+Postgres on Docker using base image Alpine:3.14
Following are the initial three files that you will need to create in your project folder Dockerfile # syntax=docker/dockerfile:1 FROM alpine:3.14 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN apk update RUN apk add postgresql-dev RUN apk add gcc RUN apk add python3-dev RUN apk add musl-dev RUN apk add py3-pip RUN pip install psycopg2 RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db requirements.txt Django>=3.0,<4.0 psycopg2-binary>=2.8 After creating the above 3 files run the following command: docker-compose run web django-admin startproject example_project . Next you will have to modify the settings for database in the newly created settings.py file in your django project folder. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Run: docker-compose up As the server is running go to the Terminal of your container and do migrations (Docker Desktop > Container/Apps > Expand docker > Docker_web CLI) python3 manage.py migrate -
why my django signals not sending for create user profile objects?
I have three model Subscriber, MyAuthors and MyCustomer. When an object creates any of my three models, I send a signal to my user profile model to create a profile object. Signals sending properly from MyCustomer model but I am not understanding why signals not sending for Subscriber and MyAuthors models. here is my code: class UserManagement(AbstractUser): is_blog_author = models.BooleanField(default=False) is_editor = models.BooleanField(default=False) is_subscriber = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) class MyAuthors(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class Subscriber(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class MyCustomer(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile") ....my others fields #my customer_signals working properly @receiver(post_save, sender=MyCustomer) def user_is_created_or_save(sender,instance,created,**kwargs): user = instance.user password = instance.user.password username= instance.user.username email = instance.email first_name = instance.first_name last_name = instance.last_name user_id = instance.user.id is_customer = instance.user.is_customer um = UserManagement(id=user_id,email=email,username=username,password=password,first_name=first_name,last_name=last_name,is_customer=is_customer) um.save() if created: UserProfile.objects.create(user=user) #subscriber_signals @receiver(post_save, sender=Subscriber) def user_is_created_or_save(sender,instance,created,**kwargs): user = instance.user password = instance.user.password username= instance.user.username first_name = instance.first_name last_name = instance.last_name email = instance.email user_id = instance.user.id is_subscriber = instance.user.is_subscriber um = UserManagement(id=user_id,email=email,username=username,password=password,first_name=first_name,last_name=last_name,is_subscriber=is_subscriber ) um.save() if created: UserProfile.objects.create(user=user) #author_signals … -
Django: How to display success data from requests ajax one by one in table
in my page i send input value to another page by request ajax, that page give me form django generated for instance value like this but not give me the same in this expample 👇 How I can send request ajax and get success data like this for each request -
Missing feedback from Django migrate command
When running python manage.py migrate in a ruge database and the migrate process is taking forever to end, however no feedback is provided on the process. I'm worried that some deadlock or conflict can be happening, and the --verbosity argument can't help enough to discover the real problem. Any ideas? The command output that are during forever: Operations to perform: Apply all migrations: admin, atendimento, auth, authtoken, contenttypes, imoveis, sessions Running pre-migrate handlers for application admin Running pre-migrate handlers for application auth Running pre-migrate handlers for application contenttypes Running pre-migrate handlers for application sessions Running pre-migrate handlers for application imagekit Running pre-migrate handlers for application appone Running pre-migrate handlers for application apptwo Running pre-migrate handlers for application django_crontab Running pre-migrate handlers for application django_user_agents Running pre-migrate handlers for application rest_framework Running pre-migrate handlers for application authtoken Running pre-migrate handlers for application simple_history Running migrations: -
Invalid Syntax: ImportError,e
I am trying to make migrations for my Django project, it was working and building fine before I installed and implemented the Django registration-redux module. These are the errors I currently get and I don't understand why or how to fix it. File "/Users/user/Documents/django-projects/tango_with_django_project/manage.py", line 22, in <module> main() File "/Users/user/Documents/django-projects/tango_with_django_project/manage.py", line 11, in main from django.core.management import execute_from_command_line File "/opt/homebrew/lib/python3.9/site-packages/django/core/management/__init__.py", line 54 except ImportError,e: ^ SyntaxError: invalid syntax -
Getting a error "coInitialize has not been called" while converting a uploaded word file to pdf in django using docx2pdf
I am trying to convert an uploaded Docx file to pdf in Django using the docx2pdf module.But when I pass the file into the convert function I am getting the following error, pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None) My views.py: def post(self, request): files=request.FILES.getlist("files") for f in files: file_type=getFileType(f)[-1] final_pdf=f file_type == ".docx": new_file= File() fs = FileSystemStorage() file_name = fs.save(f.name, f) uploaded_file_url = fs.url(file_name) convert('media/'+f.name) new_file.file.save(f.name.split(".")[0]+".pdf",f,save=False) new_file.save() resp={"message": "Files Uploaded"} return Response(resp, status=status.HTTP_200_OK) Thanks in advance. -
Blocks are not highlighting in django vs code
Is there any extension to do this? It is just not showing any type of highlighting in blocks. This is how it should be This is how they look -
Exception Type: AttributeError / Exception Value: 'function' object has no attribute 'objects'?
No puedo ver datos de la tabla post? models.py class Post(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE, default='1') tiempo =models.DateTimeField(default=timezone.now) servicio=models.CharField(max_length=50, blank=True, null=True, choices=servicio) descripcion=models.TextField() beneficios=models.TextField() img=models.ImageField() class Meta: ordering = ['-tiempo'] def __str__(self) : return f'Post {self.descripcion} ' creo este formulario para el ingreso de datos en forms forms.py class PostForm(forms.ModelForm): class Meta: model=Post fields=['Servicio','descripcion','beneficios','img'] Al querer visualizar los datos ingresados, tengo error en esa linea de codigo views.py def view(request): posts=Post.objects.all() #this error? data={ 'post':posts } return render(request, 'view.html', data) enter image description here -
Django Rest Framework authentication and user session
I'm trying to add authentication to my django-react app. At this point I am able to login/register users and it works fine but I want to get only data which is related with user logged in so posted or updated by them. Now I get all data regardless of user which is authenticated. I assume I have to change it in my views but how to do this? This is one of my classes class ListView(viewsets.ModelViewSet): serializer_class = ListSerializer queryset = List.objects.all() And on frontend side I get data this way: const getList = async () => { try { const response = await axiosInstance.get('/list/') if(response){ setList(response.data) } }catch(error){ throw error; } } -
Django REST Framework Error - TemplateDoesNotExist at /
I just deployed my Django REST Framework API ( with React ) app on Heroku and when I open the app I get this error saying that the "TemplateDoesNotExist at /" here's the log of the error : Environment: Request Method: GET Request URL: https://bionems-dj-react.herokuapp.com/ Django Version: 3.2.7 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'base.apps.BaseConfig'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: /app/frontend/build/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/templates/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/templates/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.9/site-packages/rest_framework/templates/index.html (Source does not exist) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 204, in _get_response response = response.render() File "/app/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/app/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 63, in resolve_template return select_template(template, using=self.using) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/loader.py", line 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) Exception Type: TemplateDoesNotExist at / Exception Value: index.html And here is my settings.py file : import os from pathlib import Path import dj_database_url (I've tried … -
django cannot compute sum on nested SUM
I am running this query where I do price*inventory1 and it works but when I try do do price*(inventory1+inventory2) django throws a error. this works results = ( Card.objects.values("rarity") .annotate(price=Sum(F("price") * F("inventory1"))) .order_by() ) this doesn't :( results = ( Card.objects.values("rarity") .annotate( price=Sum( F("price") * Sum( F("inventory1") + F("inventory2") ) ) ) .order_by() ) I am think I am doing something wrong. so, How can I do this in django ORM. -
Reverse for 'allproduct' not found. 'allproduct' is not a valid view function or pattern name
urls.py from django.urls import path from . import views app_name='shop' urlpatterns = [ path('',views.allproduct,name='allproductcat'), path('<slug:c_slug>/',views.allproduct,name='product_by_catagory') ] views.py from django.shortcuts import render, get_object_or_404 from . models import catagory,product # Create your views here. def allproduct(request,c_slug=None): c_page=None products=None if c_slug!=None: c_page=get_object_or_404(catagory,slug=c_slug) products=product.objects.all().filter(catagory=c_page,available=True) else: products=product.objects.all().filter(available=True) return render(request,'catagory.html',{'catagory':c_page,'products':products}) model.py from django.db import models # Create your models here. from django.urls import reverse class catagory(models.Model): name=models.CharField(max_length=250,unique=True) slug=models.SlugField(max_length=250,unique=True) description=models.TextField(blank=True) image=models.ImageField(upload_to='catagory',blank=True) class Meta: ordering=('name',) verbose_name='catagory' verbose_name_plural='catagories' def __str__(self): return '{}'.format(self.name) def get_url(self): return reverse('shop:product_by_catagory',args=(self.slug,)) class product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='product', blank=True) price=models.DecimalField(max_digits=10,decimal_places=2) stock=models.IntegerField() available=models.BooleanField() created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) catagory=models.ForeignKey(catagory,on_delete=models.CASCADE) class Meta: ordering = ('name',) verbose_name = 'product' verbose_name_plural = 'products' def __str__(self): return '{}'.format(self.name) catagory. html {% extends 'base.html' %} {% load static %} {% block metadiscription %} {% if catagory %} {{catagory.discription}} {% else %} welcome {% endif %} {% endblock %} {% block title %} {% if catagory %} {{catagory.name}}--ABC store {% else %} see our new collection {% endif %} {% endblock %} {% block content %} {% if catagory %} <div> <div> <a href="{% url 'shop:allproduct' %}">OUR PRODUCT COLLECTION</a> </div> </div> {% endif %} <div> {% if catagory %} <img src="{{catagory.img.url}}" alt="{{catagory.name}}"> </div> <br> <div> … -
Experience working with .NET or Django framework
My name is Farhad Dorod. I'm Full stack developer. This is my question. Which framework do you prefer? .NET or Django? And why? I want to publish this poll in my article. Please accompany. -
Django POST form accepted by all except 1 button. Potential bug?
I am completely stumped. I have a working Django view, which displayed 'posts' for each post in a list handed into it. list.html {% for p in posts %} #code to display post in a list> <form action="{% url 'archive_commit' p.oid %}" method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.path }}"> {% if p.is_archived %} <input type="hidden" name="action" value="unarchive"> <button type="submit", name="p_oid", value="{{ p.oid }}", class="btn btn-primary btn-sm">Unarchive</button> {% else %} <input type="hidden" name="action" value="archive"> <button type="submit", name="p_oid", value="{{ p.oid }}", class="btn btn-primary btn-sm">Archive</button> {% endif %} </form> When I click the archive button it calls the following URL pattern and view. urls.py url(r'^archive/(?P<oid>.+)/$', views.archive_view, name='archive_post'), views.py def archive_view(request, oid): post = get_object_or_404(models.Post, oid=request.POST.get('p_oid')) archive_query_param = '' if request.POST.get('action') == 'archive': post.is_archived = True post.save() messages.success(request, ('Post ' + oid + ' has been archived')) else: post.is_archived = False post.save() messages.success(request, ('Post ' + oid + ' has been restored')) archive_query_param = '?archived=True/' next = request.POST.get('next', '/') return HttpResponseRedirect(next + archive_query_param) Here's the issue I'm having. EVERY single post on the page behaves as excepted, going to the view and archiving the post and then returning to next, except for the first post of the list. This post just … -
User cannot logout from the page where in the url pk is passed
I have a page search.html that has a link associated with a pk that when clicked redirects to page doc.html which outputs the contents related to that pk This doc.html extends a page consult_home.html. This page contains the logout button. In all the other pages that extends this consult_home.html the logout button works perfectly. But in the doc file I get the following error and the logout link does not work: ValueError at /consultancy/doc/logout Field 'id' expected a number but got 'logout'. Below are the codes of the view functions and the url patterns and also the template codes: consult_home.html* <button type="button" class="button log_out" onclick="location.href='logout';">LOGOUT</button> view function for logout def logoutUser(request): logout(request) return redirect('/') search.html <a class="judge-ttle" href="{% url 'doc' searches.pk %}">{{searches.title}} &nbsp <i class="fas fa-external-link-alt"></i></a> views for doc.html class DocDetailView(DetailView): model= Laws template_name = 'doc.html' urls.py urlpatterns=[ path('logout', views.logoutUser, name='logout'), path('doc/<str:pk>', DocDetailView.as_view(), name='doc' ), ] Please suggest me what to do. -
why name 'self' is not defined in django even self is included
I'm making web blog app with django and it's work pretty well before I added like functionality.Is that something I miss with view (Do i need to create class based view for this ).I tried it but didn't work either.whenever I rendered a url for post I got this error.Do you have any suggestion.Help in advance post_detail() missing 1 required positional argument: 'self' so here is code views.py def post_detail(request,slug,self): template_name = "post_detail.html" post = get_object_or_404(Post, slug=slug) stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes() liked = False if stuff.likes.filter(slug=self.request.user.id).exists(): liked = True context["total_likes"] = total_likes context["liked"] = liked comments = post.comments.filter(active=True).order_by("-created_on") new_comment = None # Comment posted if request.method == "POST": comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() return render( request, context, template_name, { "post": post, "comments": comments, "new_comment": new_comment, "comment_form": comment_form, }, ) def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) 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 HttpResponseRedirect(reverse('post_detail', args=[str(pk)])) urls.py path('like_post/<int:pk>', LikeView, name="like_post") models.py class Post(models.Model): title … -
How to write a unit test on Django REST API endpoint that has permission_classes = (IsAuthenticated,)
Hello everyone I'm looking to write unit test on my django app, in order to test the different API endpoint but it seems like i can't figure our the problem here is a snap code of what i have done so far : urls.py : path('translate/display/', DisplayTranslation.as_view(), name='display_translation'), it's corresponding DRF view.py : class DisplayTranslation(generics.ListAPIView): queryset = Translation.objects.all() serializer_class = TranslationSerializers permission_classes = (IsAuthenticated,) and here is what I have done so far on my unit test.py : apiclient = APIClient() class TranslationTestCases(APITestCase): def setUp(self): self.role = baker.make(Roles) self.user = baker.make(Users, user_role=self.role) self.token = reverse('token_obtain_pair', kwargs={'email': self.user.email, 'password': self.user.password}) self.translation = baker.make(Translation, _quantity=10) def test_get_all_translations(self): header = {'HTTP_AUTHORIZATION': 'Token {}'.format(self.token)} response = self.client.get(reverse('display_translation'), {}, **header) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 10) This is the error I'm getting when I run the test : in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'token_obtain_pair' with keyword arguments '{'email': 'dZbQNWCjif@example.com', 'password': 'PfQzPqqVVLAdLZtJyVUxVjkGJEgRABYdHxMRhCGZJWxnZxpxEgUkgUKklENrWlBiYOCxhaDtJXdtXCtNdOJYtSWTzIrdvPnrmezXBNjEYYTpyZWjOLMnMIBMAfYnLwcC'}' not found. 1 pattern(s) tried: ['token/$'] Some more info, in the authentication on my Django app, I worked with DRF, rest_auth & SimpleJWT library. What I could do to improve my code? or an alternative solution? I couldn't find a similar problem to mine. -
How to use Django message framework in React component?
I am creating a website in which I want to use React in the frontend and Django for the backend. I want to know how can I use Django's message framework in react's component? {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} -
How to debug dockerized Django-React app?
My Django-React app works fine locally, but after I dockerize it and run both Django and Nginx containers, all API calls (which require token) become Unauthorized. How would I debug the app, while it's running with Docker? -
no such column: AGC.id Django
i've been working with an existing datatable so i create the models using "inspectdb", my class doesn't have a primary key so django adds a automatically primary key named="id" when i makemigrations and migrate. Later, when i define the template,views and urls to see the class table at my website there is an error like this one: no such column: AGC.id I don´t know how to fix it, please help me i'm a noob using django Model: class Agc(models.Model): index = models.BigIntegerField(blank=True, null=True) area = models.TextField(db_column='AREA', blank=True, null=True) # Field name made lowercase. periodo = models.BigIntegerField(db_column='PERIODO', blank=True, null=True) # Field name made lowercase. demanda = models.TextField(db_column='DEMANDA', blank=True, null=True) # Field name made lowercase. This field type is a guess. class Meta: db_table = 'AGC' Template: {% extends "despachowebapp/Base.html" %} {% load static %} {% block content %} <table class="table table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">Index</th> <th scope="col">Area</th> <th scope="col">Periodo</th> <th scope="col">Demanda</th> </tr> </thead> <tbody> {% if AGCs %} {% for AGC in AGCs %} <tr> <th scope='row'>{{ Agc.id }}</th> <td>{{ Agc.index }}</td> <td>{{ Agc.index }}</td> <td>{{ Agc.area }}</td> <td>{{ Agc.periodo }}</td> <td>{{ Agc.demanda }}</td> </tr> {% endfor %} {% else %} <h1>No hay datos </h1> </tbody> </table> {% endblock …