Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to deploy the DB, API, and FRONT containers in the above repository to AWS ECS so that they can be operated
https://github.com/hodanov/react-django-postgres-sample-app I want to deploy the DB, API, and FRONT containers in the above repository to AWS ECS so that they can be operated. Therefore, in order to operate the containers separately, the docker-compose.yaml file was divided into containers. I pushed the container to ECR and operated it with ECS, but it stopped by all means. Where should I review it? -
Django global login required middleware error
I'm using Django to make a website In the website, users can have access to all pages only after they log in the website other than login page. So, I did pip install django-glrm and added 'global_login_required.GlobalLoginRequiredMiddleware' in MIDDLEWARE in settings.py Here is the reference https://django-glrm.readthedocs.io/en/latest/readme.html After installing, I just added @login_not_required to login function and it worked for several days. However, today I ran into an error. Not Found http://127.0.0.1:8000/accounts/login/?next=/ What is the problem? After erasing 'global_login_required.GlobalLoginRequiredMiddleware' in settings.py, it does not show the error but login required does not work of course. Please let me know it you have an idea -
NoReverseMatch at / Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/(?P<product_slug>[^/]+)/$']
I am a student currently learning Django. The following error occurs in the project I'm making. We are implementing a function related to product registration, but we can't do anything because of an error. Actually, I don't know much about slugs or Django. What should I do to solve it? Great developers, please help me. I have attached the files for our project. Help would be appreciated. error content : NoReverseMatch at / Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['(?P[0-9]+)/(?P<product_slug>[^/]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'product_detail' with arguments '(8, '')' not found. 1 pattern(s) tried: ['(?P[0-9]+)/(?P<product_slug>[^/]+)/$'] Exception Location: D:\anaconda3\envs\vnv_zn\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: D:\anaconda3\envs\vnv_zn\python.exe Python Version: 3.7.6 Python Path: ['C:\zeronine_project (1)', 'D:\anaconda3\envs\vnv_zn\python37.zip', 'D:\anaconda3\envs\vnv_zn\DLLs', 'D:\anaconda3\envs\vnv_zn\lib', 'D:\anaconda3\envs\vnv_zn', 'D:\anaconda3\envs\vnv_zn\lib\site-packages'] Server time: Tue, 25 May 2021 12:19:01 +0900 model.py from django.db import models from django.contrib.auth.models import AbstractUser from django.urls import reverse # member class Member(AbstractUser): username = models.CharField(primary_key=True, max_length=20, verbose_name='아이디') name = models.CharField(max_length=20, verbose_name='이름', default='') password = models.CharField(max_length=64, verbose_name='비밀번호') phone = models.CharField(max_length=64, verbose_name='전화번호') def __str__(self): return self.username class Meta: verbose_name = ('Member') verbose_name_plural = ('Members') # category class Category(models.Model): category_code = models.AutoField(primary_key=True) name = models.CharField(max_length=200, … -
Getting attribute error while joining 2 tables
There are 2 tables category, sub_category that i want to join through common column id, category. While doing so I'm getting attribute error. I want category's data first then sub_category's data. Models.py: class Category(models.Model): category = models.CharField(max_length=50) image = models.CharField(max_length=500) store_image = models.CharField(max_length=1000) is_active = models.IntegerField() parent_id = models.IntegerField() class Meta: managed = False db_table = 'category' class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, db_column='category') sub_category = models.CharField(max_length=50) is_active = models.IntegerField() class Meta: managed = False db_table = 'sub_category' Views.py: class CategoryView(generics.GenericAPIView): def post(self, request): queryset = Category.objects.all().exclude(parent_id=0) serializer = CategorySerializer(queryset, many=True) return Response(serializer.data) Serialzer.py: class SubCategorySerializer(serializers.ModelSerializer): class Meta: fields = ["id", "category", "sub_category", "is_active"] model = SubCategory class CategorySerializer(serializers.ModelSerializer): sub_category_data = SubCategorySerializer(read_only=True, source='id') class Meta: fields = ["id", "category", "image", "is_active", "parent_id","sub_category_data"] model = Category Error: AttributeError: Got AttributeError when attempting to get a value for field `category` on serializer `SubCategorySerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'category'. -
how to convert a variable passed into HTML from python into HTML?
I'm learning Django. I have a views.py file that converts markdown into html. Then this is passed as a variable, called body into the following html. When I view the page, rather than converting the variable body into html, it just displays: <h1>CSS</h1> <p>Cats can run fast or slow <a href="/animals/HTML">HTML</a> page.</p> Below is my html file. I'm wondering, in order for the html to be read by the web-browser not as a string but as html, do I do something different then {{body}}? {% extends "mapper/layout.html" %} {% block title %} mapper {% endblock %} {% block body %} <h1>{{ title }}</h1> <div> {{ body }} </div> {% endblock %} -
Django static jpg file gets 404
I have been confused for a while and have no idea what is wrong. What i got error is GET /static/jpgfile/connect.jpg HTTP/1.1" 404 ,connect.jpg can be viewed when open http://127.0.0.1:8000/runoob/ Can anyone help to point out what should be modified .Your help will be gratefully appreciated. Here is my directory: Demo |--Demo | |--__init__.py | |--asgi.py | |--search.py | |--settings.py | |--urls.py | |--wsgi.py |--demoapp |--static | |--jpgfile | | |--connect.jpg |--templates | |--runoob.html relevant code is : in Demon>settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] Demon>search.py: def search_form(request): return render(request,'runoob.html') Demon>urls.py: urlpatterns = [path('runoob/',search.search_form),] templates>runoob.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test</title> {% load static %} </head> <body> <img src="/static/jpgfile/connect.jpg" alt="test"> </body> </html> -
Django how to carry url parameters over into new URL
My site has a list of car manufactures. User clicks on a manufacture it displays the models from that manufacture. What I want is when they click on the model it displays data but I am having issues setting up my url structure. path('browse/', BrowseListView.as_view(), name='blog-browse'), path('browse/models/<int:pk_test>/', views.modelsView, name='db-manufactures'), path('browse/models/<int:pk_test>/<int:new_stuff>', views.modelPosts, name='model-post') #this is the new url When i run this i get the error that modelPosts() got an unexpected keyword argument 'pk_test' i believe i am getting this error because pk_test is not being carried over into the new url How do i go about carrying over the pk_test value into the new url. I have been reading through the docs but im still unsure -
Django Boolean Checkbox Input Field printing value='False'
I have a number of Boolean Field checkbox inputs within a form and I have noticed the following Boolean Fields (avaialble, bfbw, asp and tours) are printing a default value of 'False' whilst the remainder of the Boolean Fields (para_athlete, working_with_children) do not. When the value of False is there I cannot toggle the checkbox between on/off (True/False) Is there something obvious that I am missing as I am struggling to see any difference between the fields? Thanks in advance for any help I can get on this. Below is the code. Model athlete_ref = models.CharField(max_length=10, default=1) athlete_name = models.CharField(max_length=80) email = models.EmailField() phone_number = models.CharField(max_length=120) home = models.CharField(max_length=120) education = models.CharField(max_length=120) sport = models.CharField(max_length=120, choices=sports, default='Shooting') notes = models.TextField() gender = models.CharField(max_length=120, choices=genders, default='Not Specified') para_athlete = models.BooleanField(blank=True) working_with_children = models.BooleanField(blank=True) expiry_date = models.DateField(blank=True, null=True) available = models.BooleanField(blank=True) available_from = models.DateField(blank=True, null=True) bfbw = models.BooleanField(blank=True) latest_bfbw_session = models.DateField(blank=True, null=True) number_bfbw_sessions = models.CharField(blank=True, null=True, max_length=10) asp = models.BooleanField(blank=True) latest_asp_session = models.DateField(blank=True, null=True) number_asp_sessions = models.CharField(blank=True, null=True, max_length=10) tours = models.BooleanField(blank=True) latest_tours_session = models.DateField(blank=True, null=True) number_tours_sessions = models.CharField(blank=True, null=True, max_length=10) Form class EditAthleteForm(forms.ModelForm): class Meta(): model = Athlete fields = ('__all__') widgets = { 'athlete_ref': TextInput(attrs={'id':'athlete_ref', 'name': 'athlete_ref', 'hidden': 'hidden'}), 'athlete_name': … -
is it possible to use regular Django+templates and Django restframework+a javascript framework in the same project?
I'm just wondering since Jquery is used less and less and instead of classic use with Ajax, if it is possible to let for example React or Vue handle all of the functionality where Javascript would be needed with DRF in one hand , and consider all of it as statics. And in the other hand, keep working with Django and regular templates. i'm just asking about the possiblity to do so. -
image path is not identifiable on index.html of django3
i am following a tutorial based on django 2 and currently running version 3 of django, the problem i am facing is the identifying path of the tag on the front end of index.html, i'll post the code bellow , kindly tell me where i went wrong and any other mistakes my settings.py STATIC_URL = '/static/' STATICFILES_DIRS= (os.path.join(BASE_DIR, 'static'),) #static root added (A2) MEDIA_ROOT=os.path.join(BASE_DIR, 'media') MEDIA_URL='/media/' my urls.py of main project from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',include('posts.urls')), path('user/',include('user.urls')), path('admin/', admin.site.urls), ]+ static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT) my models.py of app class Posts(models.Model): #created this model field def min_len(val): #this is the custom validator working if len(val)<=9: raise validators.ValidationError("%(val)s Must be more than 10", params={'val':val}) title=models.CharField(validators=[min_len],max_length=255) #validation list provided content=models.TextField(validators=[min_len]) thumb_nail=models.FileField(upload_to="posts/",null=True) #file field added class Posts_Form(forms.ModelForm): #to build a form using django and not html class Meta: #will get data of the fields=[] only model=Posts fields=['title','content','thumb_nail','user','category'] views.py def index(request): form=Posts_Form() #created form object data=Posts.objects.all() #retrive data from the model to display category=Category.objects.all() #we get all data of category if request.method=='POST': form=Posts_Form(request.POST,request.FILES) #request.FILES for file data if form.is_valid(): # data=Posts( # title=request.POST['title'], # content=request.POST['content'], # ) form.save() return redirect('/') return … -
Django forms : 'NoneType' object has no attribute 'is_valid'
Like a lot of people here, i have to deal with a form problem, but even with other posts I can't see the solution, here are my files : testeuh/models.py : from django.db import models from django.contrib import admin # Create your models here. class diapo(models.Model): title = models.CharField(max_length=30) corpus = models.TextField(max_length=300) image = models.ImageField(upload_to="DossierImages") class diapoAdmin(admin.ModelAdmin): search_fields = ['title'] list_display = ['title'] testeuh/forms.py : from django.forms import ModelForm from .models import diapo def DiapoForm(ModelForm): class Meta: model = diapo fields = [ 'title', 'corpus', 'image', ] testeuh/views.py : from django.shortcuts import render from .forms import DiapoForm from .models import diapo # Create your views here. def diapo_create_view(request): form = DiapoForm(request.POST or None) if form.is_valid(): form.save() context = { 'form': form } return render(request, "diapo/create.html", context) def diapo_detail_view(request): obj = diapo.objects.get(id=1) context = { "object" : obj } return render(request, "diapo/detail.html", context) urls.py : """SiteEcran URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including … -
How to configure fields in Django forms.Form?
I'm learning Django and web dev and having difficulty configuring the fields in Django forms.Form so that they come out correctly. Below is my code: Even if I adjust my attrs rows and cols in forms.Textarea it doesn't make any difference. Also, it doesn't seem to matter what I put in CSS the output is still the same. class NewPageForm(forms.Form): title = forms.CharField(label="Title", max_length=100, widget=forms.TextInput) content = forms.CharField(label="Content", widget=forms.Textarea(attrs{"rows":3,"cols":10})) My html: {% block body %} <div class="form"> <form action="{% url 'create' %}" method="post"> {% csrf_token %} {{ form.as_p }} <input type = submit> </form> </div> {% endblock %} What it looks like: Please advise. -
Error: relation "django_admin_log" does not exist
When I try to log in to admin section I get the error page: http://localhost:8000/admin/ ProgrammingError at /admin/ ERROR: relation "django_admin_log" does not exist Then I noticed that 'django_admin_log' table does not exist. captured from psql I can not remember whether I accidentally removed it or not. In order to recover it I checked "django.contrib.admin" is in INSTALLED_APPS in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'db.apps.DbConfig', 'django.contrib.postgres', 'accounts.apps.AccountsConfig', 'django.contrib.sites', 'allauth', 'allauth.account', ] and execute "python manage.py migrate admin" But still, I can not create django_admin_log table. PostgreSQL version is 12.6 I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
SyntaxError: f-string expression part cannot include a backslash
I have this api call. payload = "{\\"weight\\":{\\"value\\":\\"85.00\\",\\"unit\":\\"kg\\"},\\"height\\":{\\"value\\":\\"170.00\\",\\"unit\\":\\"cm\\"},\\"sex\\":\\"m\\",\\"age\\":\\"24\\",\\"waist\\":\\"34.00\\",\\"hip\\":\\"40.00\\"}" I want to use a f string to change those values but I get a syntax error saying I can't use backslash for f strings. What can I do? -
How to replicate Django auth.admin groups and permissions admin page forms?
Anyone know how I can create a form with the exact M2M form used in the admin page for the auth.user model where it has two multiple select boxes with right and left arrows and a search filter for the left select box? Any help is much appreciated! -
Many-To-Many - Too much data in admin page
My authors can have pseudonyms so I added a Many-To-Many relationship. class Name(models.Model): name = models.CharField(max_length=30, unique=True) ... class Author(models.Model): name = models.ManyToManyField(Name) sex = models.CharField(max_length=6, choices=[('m', 'male'),('f', 'female')]) birthday = models.DateField() birthplace = models.CharField(max_length=30) .... After adding many names it quickly becomes cumbersome to scroll and select through thousands of names when adding new author datasets via the admin page. Is there a better way to design the model, so that I can just add those few pseudonyms without this hassle? -
python: 'bool' object is not callable
C:\Users\Republic Of Computer\Desktop\Cirriculum\CvMaker\home\decorators.py, line 6, in wrapper_func from django.shortcuts import redirect def notLoggedUsers(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated(): … return redirect('candidat') else: return view_func (request, *args, **kwargs) return wrapper_func -
Django: Obtaining a QuerySet from a model of two OneToOne fields
I have the following set of models: from django.db import models from django.db.models import CASCADE class Battle(models.Model): idBat = models.UUIDField(primary_key=True) # other attributes... class Participant(models.Model): idPar = models.UUIDField(primary_key=True) # other attributes... class Event(models.Model): participant1 = models.OneToOneField(Participant, CASCADE, related_name='%(class)s_par1') participant2 = models.OneToOneField(Participant, CASCADE, related_name='%(class)s_par2') battle = models.ForeignKey(Battle, CASCADE, related_name="%(class)s_battle") # other atributes... However from a view I wish to get all Participants from a said Battle I obtained from a form. As such, I know I can obtain all Events from a Battle in this way: battle = form.cleaned_data['selected_battle'] events = battle.event_set participants = # now what?? As seen above I don't know how to correctly obtain said participants from each event of the battle. To be clear I can guarantee there will be repeated participants since an event consists of a fight between participant1/2 where one of them kills the other, and a battle is a succesion of said events until one participant remains victoriuos, thus every survivor of an event will appear again in another event in the battle. I wish to obtain all participants without said repetitions and possibly reorder and slice them using QuerySet.order_by(...)[0:N], hence the mention of QuerySet in the title. -
Django REST permission classes don't work together inside an OR but work as expected independently
I'm having troubles putting two permissions together using an OR operator. The documentation says: Doc Provided they inherit from rest_framework.permissions.BasePermission, permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written: ... permission_classes = [IsAuthenticated|ReadOnly] So I have created the permissions: permissions.py class IsFullUserOrReadOnly(permissions.BasePermission): """ This class defines the permission to only allow the request to certain users with a certain role.""" def has_permission(self, request, view): """ This function overrides the default has_permission method to allow the writing methods only to full users or admin users """ if request.method in permissions.SAFE_METHODS: return True is_full_user = False queryset = User.objects.get(email=request.user) if queryset: user = UserSerializer(queryset) if 'roles' in user.data: for role in user.data['roles']: if role == ADMIN or role == FULL_USER: is_full_user = True print('IsFullUserOrReadOnly') print(is_full_user) print(request.method) print(request.method =='POST') return is_full_user or request.method =='POST' class IsOwnerOrReadOnly(permissions.BasePermission): """ This class defines the permission to only allow the POST and PUT methods to the creator of the item.""" def has_object_permission(self, request, view, obj): """ This function overrides the default has_object_permission method to allow the writing methods to the owner of the object """ if request.method in permissions.SAFE_METHODS: return True # Instance must have an attribute named `created_by`. print('IsOwnerOrReadOnly') print(obj.created_by … -
Django print different user profile page from the current connected profile
I have a problem with my code. I would like to add the possibility to access to another profile page. I think my problem is in my html page. what i'm doing is {% with profile=user.profile %} but what i want is showing the profile page corresponding with the username described in the url. For example, if the url contains "profile/toto.html" it will give me the profile page of toto. With my current code, whatever username i put in the url, it shows my own profile page :( Can anyone help me please ? -
Google calendar in Django
I'm a nobbie in Django (actually i'm a nobbie in code) and i've a question for anyone who can help me. I want to create a event in Html input (type="datetime") and send it to my google calendar. With the quickstart of Google Calendar I made it, but only with Static data, hardcoded in the code. I've already search and found a lot of guides but any of them shows how to send dynamic data from my template to the calendar. from datetime import timedelta import pytz from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials service_account_email = "INSERT_HERE" SCOPES = ["https://www.googleapis.com/auth/calendar"] credentials = ServiceAccountCredentials.from_json_keyfile_name( filename="FILENAME.json", scopes=SCOPES ) def build_service(): service = build("calendar", "v3", credentials=credentials) return service def create_event(): service = build_service() start_datetime = datetime.datetime.now(tz=pytz.utc) event = ( service.events() .insert( calendarId="CALENDARID@group.calendar.google.com", body={ "summary": "Foo", "description": "Bar", "start": {"dateTime": start_datetime.isoformat()}, "end": { "dateTime": (start_datetime + timedelta(minutes=15)).isoformat() }, }, ) .execute() ) print(event) create_event() With this code when i run it in the console the event was created, but now i don't know how render this in the input (datetime, text, etc). Any help will be nice. :) -
Creating form-level error in views.py for formset
I've got the following formset. Within views.py, i'd like to assign an error to one of the forms in the formset. I haven't been able to figure out how to do this EmployeeTeamFormset = modelformset_factory(EmployeeTeamMembership, form=EmployeeTeamForm, extra=0, max_num=10, can_delete=True) formset = EmployeeTeamFormset(request.POST or None, queryset=EmployeeTeamMembership.objects.filter(employee__user=user, team=team), form_kwargs={'user': user, 'team': team}) if request.method == 'POST': if formset.is_valid(): instances = formset.save(commit=False) for instance in instances: #if some condition, assign error to form field -
Wagtail - How to add multiple blogs?
I want to create multiple blogs on same Wagtail Project. Currently I am using https://pypi.org/project/wagtail-blog/ ...and I want the same app in same project for 3-4 times. Like Blog 1 Blog 2 Blog 3 and so on.. How to achieve this ? -
Handle non-submit input types in django
Okay so I have two input tags with types as buttons. <div class="buttons-for-trade-or-sell" style="display: flex; position:relative;left: 33px; top:14px"> <div class="button-to-trade"> <input type="button" class="trade-btn" id="button-to-select-trade" name="trade1" value="Trade"></input> </div> <div class="button-to-sell"> <input type="button" class="sell-btn" id="button-to-select-sell" name= "trade2" value="Sell"></input> </div> My problem is how do I send to the server side code which button is selected. For example, if the trade-btn is selected i want the boolean to be set to true in my view. Then from there I would handle it accordingly. Basically, how do I send which button is selected to the server-side? Thanks. -
How to show in Django queryset dict-key and -values seperately in template?
I have the this output in the browser from HTML template: {'coin__name': 'Bitcoin', 'total': Decimal('1498824')} {'coin__name': 'Ripple', 'total': Decimal('335227')} How can I show in an html template separately the key and the value(without saying Decimal)? Desired outcome: Bitcoin, 1498824 Ripple , 335227 I provide the query and the html template below: views.py: test = filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum('trade_price' ) * Sum('number_of_coins'))).order_by('-total') template.html <table class="table table-striped"> <tr> <th>Current dict pair</th> <th>Just the name of the crypto</th> <th>Just the price of the crypto</th> </tr> {% for item in test %} <tr> <td>{{ item }}</td> <td>{{ }}</td> <td>{{ }}</td> </tr> {% endfor %}