Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Account with this Email already exists. how to fix this?
I tried to create a login form. But when I try to login django gives the error that Account with this Email already exists. i don`t now how to fix this.Help me plz Here is my code, please tell me where I'm going wrong: forms.py class AccountAuthenticationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model= Account fields = ('email', 'password') def clen(self): email = self.cleaned_data['email'] password = self.cleaned_data['password'] if not authenticate(email=email, password=password): raise forms.ValidationError("Invalid login") views.py def login_view(request): context = {} user = request.user if user.is_authenticated: return redirect("home") if request.POST: form = AccountAuthenticationForm(request.POST) if form.is_valid(): email=request.POST['email'] password = request.POST['password'] user =authenticate(email=email, password=password) if user: login(request,user) return redirect("home") else: form = AccountAuthenticationForm() context['login_form'] = form return render(request, 'account/login.html', context) login.html {% extends 'base.html' %} {% block content %} <h2>Login</h2> <form method="post">{% csrf_token %} {% for field in login_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color:grey">{field.help_text}</small> {% endif %} {% for error in field.errors %} <p style="color:red">{{error}}</p> {% endfor %} {% if login_form.non_field_errors %} <div style="color:red";> <p>{{login_form.non_field_errors}}</p> </div> {% endif %} </p> {% endfor %} <button type="submit">Log in</button> </form> {% endblock content %} I'm just getting started with Django. I will be glad if you point out my mistake -
I can't save data of <select> in html
I have django application with form. in model LIVING_COUNTRIES = [ ('AFGANISTAN', 'Afganistan'), ('ALBANIA', 'Albania'), ('ALGERIA', 'Algeria'), ('ANGORRA', 'Andorra')] class Employee(models.Model): country_living = models.CharField(max_length=50, choices=LIVING_COUNTRIES, default=FRESHMAN, blank=True, null=True) in html <select name="country" id="id_category" data="{{ data.country }}"> {% for each in living_countries_list %} <option value="{{ each.0 }}" class="living_countries">{{ each.1 }}</option> {% endfor %} </select> in view context['has_error'] = True if context['has_error']: employees = models.Employee.objects.all() living_countries_list = LIVING_COUNTRIES return render(request, 'authentication/employee_register.html', context) So I have form rendered in get() method of class-based view. When I click submit post method checks for errors. If there are any context['has_error'] is set to true. For simplycity I've written it down anyway. And if it is true we render form again. I want to have previous choice of user still displayed in html. I've done it on other inputs by `data="{{ data.field }}". How would I do that here? -
How do I bring through my data in Django Template view?
I'm trying to display my data from my HealthStats model to my template, however I can only pull through the user field. I've added the other fields to my template, but they're not showing. I would also like to be able to filter the output to only show records of the logged in user. Models.py class HealthStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.IntegerField(default=5) run_time = models.TimeField() class Meta: db_table = 'health_stats' ordering = ['-date'] def __str__(self): return f"{self.user} | {self.date}" Views.py: class HealthHistory(generic.TemplateView): model = HealthStats template_name = 'health_hub_history.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stats'] = HealthStats.objects.all() return context health_hub_history.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 text-center"> <h1>My Health History</h1> </div> </div> </div> <div class="container-fluid"> <div class="row justify-content-center"> <div class="col-auto text-center p-3"> <table class="table table-striped table-hover table-bordered"> <tr> <td>User:</td> <td>Weight (lbs):</td> <td>Date:</td> <td>Run Distance (km):</td> <td>Run Time (HH:MM:SS):</td> </tr> {% for stat in stats %} <tr> <td>{{ user }}</td> <td>{{ weight }} </td> <td>{{ date }}</td> <td>{{ run_distance }}</td> <td>{{ run_time }}</td> </tr> {% endfor %} </table> </div> </div> </div> {% endblock content %} Any help would be appreciated! -
How to serialize a foreign key relationship as key value pair django rest framework
I'm trying to serialize an relationship in DRF whereas I attempt to get the following output: "statistics":[ "Attacks":{ "id":971, "home_value":3, "away_value":2, "value":5 }, "Corners":{ "id":972, "home_value":0, "away_value":0, "value":0 } ] I wrote the following code for my serializer of this model: class StatisticSerializer(serializers.ModelSerializer): class Meta: model = Statistic fields = ['id', 'home_value', 'away_value', 'name', 'value'] def to_representation(self, instance: Statistic): representation = {instance.name: { "id": instance.id, "home_value": instance.home_value, "away_value": instance.away_value, "value": instance.value }} return representation Which gets me the following output: "statistics":[ { "Attacks":{ "id":971, "home_value":3, "away_value":2, "value":5 } }, { "Corners":{ "id":972, "home_value":0, "away_value":0, "value":0 } } ] Is there any way to get it as demonstrated in the first example using django rest framework? -
how to call a function when app start in django?
i want to call the daily_data_log_checker function in that MainConfig class so that it can run when the app start class MainConfig(AppConfig): default_auto_field = 'django.db.models.AutoField' name = 'main' def daily_data_log_checker(): import datetime from datetime import datetime from datetime import date from main.models.status import DailyMachinePerformance from main.management.commands.jobscheduler import log_daily_data now_time = datetime.datetime.now() today = date.today() if(now_time.hour>= 11): daily_machine_performance = DailyMachinePerformance.objects.filter(date = today) if(len(daily_machine_performance) == 0): log_daily_data() -
Simple quest in view and settings
Well, I working on this problem about 2 weeks. Searching in google a lot, experimenting with options. But that is just not working -_-. I can't even pinpoint what the problem is, probably in views or settings with join. Just look. I had a lot of errors, at this moment I see: No module named 'path', , line 1004, in _find_and_load_unlocked I know this problem is simple, but I tired to struggle :D Settings from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'path.to.inject_form', ], }, }, ] urls urlpatterns = [ path('form/', views.SignUpp, name="SignUpp"), path("",views.head.as_view(), name="mainpage"), path("stocks/", views.stockpage.as_view(), name="stockpage"), path("search/", SearchResultStocks.as_view(), name="search-Stocks"), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Views def SignUpp(request): if request.method == 'POST': form = UserSign(request.POST) if form.is_valid(): body = { 'Name': form.cleaned_data['Name'], 'email': form.cleaned_data['email'], 'Number': form.cleaned_data['Number'], } info_user = "\n".join(body.values()) send_mail( 'Sign', info_user, 'eric1122221@mail.ru', ['eric1122221@mail.ru'], fail_silently=False) form.save() return redirect("dental/mainpage.html") else: form= UserSign() context = { 'form': form } return render(request, 'base.html', context) class head(ListView): template_name = "dental/mainpage.html" model = signup class stockpage(ListView): template_name = "dental/stocks.html" model = stock context_object_name = "stocks" class SearchResultStocks(ListView): model = stock template_name … -
Migrating the database from legacy flask app to django
Hello i have an existing app made in Flask, it consist of simple database but it doesn't have migrations (flask-migrate) ever since and the data grows more. If i enable the migrations on django, could it screw the datas? and in case if i disable the migrations, can django writes up like the old existing ones? Here's my old db model (FLASK) from database.db import db class users(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(255), unique=True) project = db.Column(db.String(255)) reason = db.Column(db.String(255)) timestamp = db.Column(db.DateTime, default=now) And this is my new one (DJANGO) from django.db import models as db class users(db.Model): class Meta: managed = False id = db.AutoField(primary_key=True) name = db.CharField(max_length=255, unique=True) project = db.CharField(max_length=255) reason = db.CharField(max_length=255) timestamp = db.DateTimeField(auto_now_add=True) -
sorting in django admin list by a custom field alphabetically
I have a simple store / product relationship and I want to sort the products depending on the store name alphabetically. models: class Store(models.Model): name = models.CharField("name", max_length = 128) class Product(models.Model): number = models.PositiveIntegerField() name = models.CharField("name", max_length = 128) store = models.ForeignKey(Store, on_delete = models.CASCADE) and in the admin: class ProductAdmin(admin.ModelAdmin): list_display = ["number", "name", "get_store_name",] def get_store_name(self, obj): return f"""{obj.store.name}""" I know I cannot use order_by on custom fields. So I thought I need to override the get_queryset method probably? I found multiple examples to annotate by counted or calculated numbers, but never for strings. -
Optional URL for taggit Django
I'am using django-taggit in my project, to put tags on items. So i watched this tutorial to use the tags in class based views. I want to show all tags on top, and on click on the tags I want to show all items with the tag, and i've been using parameters in the url, to search for the items. But i want this parameter to be optional, so the user doesn't need to give a tag in the url. Is this possible? This is my URL so far: path('items/', views.ItemsView.as_view(), name='items'), -
Convert raw sql to django query
How can I convert this raw sql to django query?? knowledges.raw( ''' SELECT KnowledgeManagement_tblknowledge.KnowledgeCode,KnowledgeManagement_tblknowledge.KnowledgeTitle,KnowledgeManagement_tblknowledge.CreateDate,KnowledgeManagement_tblknowledge.CreatorUserID_id FROM KnowledgeManagement_tblknowledge LEFT JOIN KnowledgeManagement_tblusedknowledge ON KnowledgeManagement_tblknowledge.KnowledgeCode = KnowledgeManagement_tblusedknowledge.knowledge_id where register_status = 7 or register_status = 9 and Status = 1 Group by KnowledgeManagement_tblknowledge.KnowledgeCode order by count( KnowledgeManagement_tblusedknowledge.id) desc; ''' ) -
How to regroup entries in Django by model field (More complex query)?
First i'm not an exeperienced developer in Django, i use Django 4.0.6 on windows 10 and python 3.8.9 in a virtual environment. I need help with my query in Django: first here's my model: from django.db import models class MyWords(models.Model): WordText=models.CharField(max_length=1000, unique=True) WordStatus=models.IntegerField() WordType=models.CharField(max_length=30) and i have this sqllite database table with the following entries as example: db.sqlite3 MyWords Table: WordText WordStatus WordType Dog 0 Animal Cat 1 Animal Car 4 Object Lion 1 Animal Computer 4 Inanimate Object Stone 5 Inanimate Object Child 4 Human What i want to do is to get this info back this way: data == [ {'WordType':'Object', 'WordStatus':4,'WordText':'Car'}, {'WordType':'Animal', 'WordStatus':[0,1,1], 'WordText':'Dog','Cat','Lion'}, {'WordType':'Inanimate Object', 'WordStatus':[4,5], 'WordText':'Computer','Stone'}, {'WordType':'Human', 'WordStatus':4, 'WordText':'Human'} ] Essentially i want to regroup/categorize the entries by WordType so i can access them more easily. Is this possible in Django ORM? If yes, how? I first thought using something like a values_list with WordType as argument followed by a distinct and annotate, but i'm stucked. Something like this: data =MyWords.objects.all().values_list('WordType').distinct().annotate(WordStatus=?).annotate(WordText=?) I don't know if it's correct because i don't know what to replace the question marks with. I don't know if i'm on the correct path. So can anyone guide me please? N.B: I … -
Django Kubernetes Ingress CSRF Cookie not sent
Asking this question here because It's been a couple of days and I can't find anything useful. Problem: I have an app deployed to a Kubernetes cluster running on AWS EKS with a custom docker image on AWS ECR. The app works fine with GET requests but not with POST ones. The error given is Errore 403 forbidden CSRF Token not sent. Django version is 2.2.24 on DRF 3.11.2. I already added CSRF_TRUSTED_ORIGINS in settings.py, nothing changed. The ingress I'm using is AWS's Application Load Balancer set like this: apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: django labels: name: django annotations: alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/target-type: ip alb.ingress.kubernetes.io/backend-protocol: HTTP alb.ingress.kubernetes.io/listen-ports: '[{"HTTP":80}]' alb.ingress.kubernetes.io/group.name: "alta" alb.ingress.kubernetes.io/group.order: "2" alb.ingress.kubernetes.io/healthcheck-protocol: HTTP alb.ingress.kubernetes.io/healthcheck-port: traffic-port alb.ingress.kubernetes.io/healthcheck-path: /v1/app alb.ingress.kubernetes.io/healthcheck-interval-seconds: "15" alb.ingress.kubernetes.io/healthcheck-timeout-seconds: "5" alb.ingress.kubernetes.io/success-codes: "200" alb.ingress.kubernetes.io/healthy-threshold-count: "2" alb.ingress.kubernetes.io/unhealthy-threshold-count: "2" spec: ingressClassName: alb rules: - http: paths: - pathType: Prefix path: / backend: service: name: djangoapp-cluster-ip port: number: 80 Any help is much appreciated. -
Django - remove/hide labels for checkboxes
I would have thought this would be pretty simple but I have plugged away at this for some time and I can't figure it out. I have a multiple choice checkbox in a model form which is in a formset. All I want to do is remove the labels from the checkboxes. I can easily remove the label from the field but I can't figure out how to remove the labels from the checkboxes. I am trying to convert the display of the form to a grid. From this: To this: Here's my form code: class ResourceEditAddForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.portfolio = kwargs.pop('portfolio') super(ResourceEditAddForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.fields["portfolio"].initial = self.portfolio self.fields["portfolio"].required = False self.fields["skills"].queryset = self.portfolio.getSkills() class Meta: model = Resource fields = ['portfolio', 'name', 'skills', 'pct_availability', 'cost_per_day', 'email', 'timezone', 'update_request_time', 'calendar', 'start_date', 'end_date'] widgets = { 'portfolio': forms.HiddenInput(), 'start_date': DateInput(), 'end_date': DateInput(), 'update_request_time': TimeInput(), 'skills': forms.CheckboxSelectMultiple(), } ResourceEditAddFormSet = modelformset_factory( Resource, form=ResourceEditAddForm, extra=0 ) I could build a manual form to achieve this but I want to keep using model forms as there's a few fields other than skills which are managed fine by the form. If anyone can tell me how to … -
Serialize nested JSON to Django models
how can I create a nested structure from a nested JSON? I want my Hobby to have a ForeignKey to the Profile. It cant be that hard, but I really dont understand the error. It even creates the objects and saves them in my database but still says it does not find the field. I Get the following error with my code: AttributeError: Got AttributeError when attempting to get a value for field `description` on serializer `HobbySerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance. Original exception text was: 'RelatedManager' object has no attribute 'description'. serializers.py: class HobbySerializer(serializers.ModelSerializer): class Meta: model = Hobby fields = ["name", "description"] class ProfileSerializer(serializers.ModelSerializer): user_hobby23 = HobbySerializer(many=False) class Meta: model = Profile fields = ["testfield1", "display_name", "mobile", "address", "email", "dob", "user_hobby23"] def create(self, validated_data): user_hobby_data = validated_data.pop('user_hobby23') profile_instance = Profile.objects.create(**validated_data) Hobby.objects.create(user=profile_instance, **user_hobby_data) return profile_instance models.py: class Profile(models.Model): display_name = models.CharField(max_length=30) mobile = models.IntegerField() address = models.TextField() email = models.EmailField() dob = models.DateField() photo=models.FileField(upload_to='profile/',null=True,blank=True) status = models.IntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) testfield1 = models.TextField(null=True) class Hobby(models.Model): user=models.ForeignKey(Profile,on_delete=models.CASCADE,related_name='user_hobby23',null=True) name = models.CharField(max_length=30) description = models.TextField() status = models.IntegerField(default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py: class … -
How to call model method in ajax through views_api and assign the value to table data in DRF?
I am trying to understand the Django Rest Framework. As a beginner here, what I am trying is to call a method from a Model and update the value in the template. I am trying it from views_api.py with an ajax call. I was able to get other values, but I couldn't get three values. Here is what I have so far. reviews/models.py class Review(TimeStampedModel): project = models.ForeignKey('projects.Project', on_delete=models.CASCADE, related_name='reviews') fiscal_year = models.PositiveIntegerField(null=True, blank=True, db_index=True) fiscal_month = models.PositiveIntegerField(null=True, blank=True, db_index=True) has_validation = models.BooleanField('Has PFK', default=False) review_date = models.DateField(help_text='Date of the PFK', db_index=True) wp_validation_deadline = models.DateTimeField(blank=True, null=True, help_text='Deadline to validate WP') cutoff_date = models.DateTimeField(db_index=True, help_text='Up to when actuals are considered (date after accruals were entered)') fct_n_amount = models.DecimalField('FCT n amount', decimal_places=2, max_digits=12, null=True, blank=True) actuals_amount = models.DecimalField('Actual revenue traded', decimal_places=2, max_digits=12, null=True, blank=True, help_text='Cost to date (from monthly projectsales.xlsx)') events_amount = models.DecimalField('Total Events', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In project currency (will be displayed in Thousands)') risks_real_amount = models.DecimalField('Total Risks - Most Likely', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In project currency (will be displayed in Thousands)') risks_max_amount = models.DecimalField('Total Risks - Maximum', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In project currency (will be displayed in Thousands)') opportunities_amount = models.DecimalField('Total Opportunities', decimal_places=2, max_digits=12, null=True, blank=True, help_text='In … -
Signature drawing for the form
For my application with Django, I want to make a signature drawing field after entering the necessary information in the form field. When I want to save and edit this form later, the signature drawn in that signature drawing place needs to be displayed again. I'm new to this and I have no idea how to do it, can you help with this? -
How to generate auto generate unique serial number by date and also It will be generate serial vise after delete in django
I have to generate serial number like TES-0922-1,TES-0922-2 and so on.... here TES is (company_lable) 0922 is (month and year) 1,2 is (serial number) I wish to generate unique number by date . If today is month 9 and year 22 and I am generating new data of this month then my serial number will be TES-0922-01. Also If I have serial numbers TES-0922-01,TES-0922-02,TES-0922-03 and If I am deleting TES-0922-01 from them. afterwards when I creating new data my serial number will be TES-0922-04 Also If I have serial numbers TES-0922-01,TES-0922-02,TES-0922-03,TES-0922-04 and If I am deleting TES-0922-01, TES-0922-04 from them. afterwards when I creating new data my serial number will be TES-0922-04 Note : I am saving that data in the database and handling them by django queryset. What I did is mentioned below but Its not working properly. Because I am counting my data by django queryset. views.py def sales_invoice(request): current_time = datetime.datetime.now() latest_year = current_time.year year=str(latest_year)[-2:] latest_month = current_time.month month="%02d" % (latest_month) company_label= Company_Setup.objects.get(id=request.session['company_id']) existing_label=Sales_Invoice.objects.filter(company=company_label).all() if not existing_label: gen_invoice_number=f"{company_label}-{month}{year}-1" else: total_sales = Sales_Invoice.objects.filter(company=company_label).all().count() + 1 gen_invoice_number=f"{company_label}-{month}{year}-{total_sales}" -
Difference between request.user vs. get_user(request) in Django?
I noticed there are two ways to get a user object from request (assuming user is already logged in and the session is valid): user = request.user user = get_user(request) where get_user() is imported from django.contrib.auth. What's the difference? get_user() seems to do a lot of validation for request session. Which is better? -
Several properties with the same type Django
I have two models class Manager(models.Model): name = models.CharField(max_length=250) def __str__(self): return self.name class Project(models.Model): title = models.CharField(max_length=250, null=True, blank=True) work_statement = models.TextField(null=True, blank=True) contract_id = models.CharField(max_length=250, null=True, blank=True) note = models.TextField(null=True, blank=True) customer = models.CharField(max_length=250, null=True, blank=True) #executer = models.ManyToManyField(Manager) deadline = models.DateTimeField(null=True, blank=True) So there is logic I want Model Project to has several managers as executers but not all of them how can i do it? so for example: Project "N" can include two managers for execution i know that this way is not correct class Project(models.Model): title = models.CharField(max_length=250, null=True, blank=True) work_statement = models.TextField(null=True, blank=True) contract_id = models.CharField(max_length=250, null=True, blank=True) note = models.TextField(null=True, blank=True) customer = models.CharField(max_length=250, null=True, blank=True) executer1 = models.ForeignKey(Manager) executer2 = models.ForeignKey(Manager) deadline = models.DateTimeField(null=True, blank=True) -
Is celery-beats can only trigger a celery task or normal task (Django)?
I am workign on a django project with celery and celery-beats. My main use case is use celery-beats to set up a periodical task as a background task, instead of using a front-end request to trigger. I would save the results and put it inside model, then pull the model to front-end view as a view to user. My current problem is, not matter how I change the way I am calling my task, it always throwing the task is not registered in the task list inside celery. I am trying to trigger a non-celery task(inside, it will call a celery taskthe , using celery beats module, Below is the pesudo-code. tasks.py: @app.shared_task def longrunningtask(): res = APIcall.delay() return res caller.py: from .task import foo def dosomething(input_list): for ele in input_list: res.append(longrunningtask()) return res Periodical Task : schedule, created = CrontabSchedule.objects.get_or_create(hour = 1, minute = 34) task = PeriodicTask.objects.create(crontab=schedule, name="XXX_task_", task='app.caller.dosomething')) return HttpResponse("Done") Nothing special about the periodical task, but This never works for me. It errored that not detected tasks or not registered tasks if I do not make the dosomething() as celery task. Problem is I do not want to make the caller function a celery task, the … -
In Django how to add login required for entire app?
Suppose I have 3 apps in my Django website app_1, app_2, app_3. app_1 and app_2 can access any user, but for app_3 I want the user should log in. Using login_required I can achieve this. But I have more than 30 views and urls. I don't want to write login_required decorator on every view function. Is there any other shortcut? -
How can I "copy" some dependencies to my project
I'm following a great course (Django/react ecommerce on udemy), however the bootstrap version that they're using is really old and a lot of stuff doesn't work on newer versions, I saw they dependencies on Github but all are conflicting when I'm trying to install by npm, I can try and force some but it'll probably make things worse. There's a way I "copy/paste" their package.json and run npm install or something to get the same dependencies on my project? I can refactor everything to newer versions of course but that'll take triple the time to finish the course. -
Django "ProgrammingError at /create-post" usnig heroku postgres as database host
I am trying to create a blog website in django using postgres with heroku in the cloud. When trying to submit the post using forms from django I get this error "ProgrammingError at /create-post column "title" of relation "main_post" does not exist LINE 1: INSERT INTO "main_post" ("author_id", "title", "description"... " This is my view for creating posts from django.shortcuts import render, redirect from .forms import RegisterForm, PostForm from django.contrib.auth.decorators import login_required from django.contrib.auth import login, logout, authenticate @login_required(login_url="/login") def home(request): return render(request, 'main/home.html') @login_required(login_url="/login") def create_post(request): if request.method =='POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect("/home") else: form = PostForm() return render(request, 'main/create_post.html', {"form": form}) This is my forms.py file from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Post class RegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ["username", "email", "password1", "password2"] class PostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "description"] This is my Post model from django.db import models from django.contrib.auth.models import User class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + "\n" + self.description … -
TemplateSyntaxError when tried to manage page on Django admin backend
I am new on Django CMS and i have experience with error when try to add a page or page type trough backend site. Below is the error i got. I am using Django 4.1.1 version, Django-cms 3.11.0. Any help or suggestion will be appreciated. TemplateSyntaxError at /admin/cms/pagetype/add/ Invalid block tag on line 101: 'page_submit_row', expected 'endif'. Did you forget to register or load this tag? Request Method: GET Request URL: http://localhost:8000/admin/cms/pagetype/add/ Django Version: 4.1.1 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 101: 'page_submit_row', expected 'endif'. Did you forget to register or load this tag? Exception Location: C:\project_data\python\myblog\env\lib\site-packages\django\template\base.py, line 557, in invalid_block_tag Raised during: cms.admin.pageadmin.add_view Python Executable: C:\project_data\python\myblog\env\Scripts\python.exe Python Version: 3.10.7 Python Path: ['C:\\project_data\\python\\myblog\\myblog', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\\python310.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Users\\Rosidin\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0', 'C:\\project_data\\python\\myblog\\env', 'C:\\project_data\\python\\myblog\\ and here is my settings.py SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-rt-cu)&d604(@1pmfi!@z^_etwo(jvm!k#&z3&yxb62ll+gz1#' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] X_FRAME_OPTIONS = 'SAMEORIGIN' SITE_ID = 1 # Application definition INSTALLED_APPS = [ 'djangocms_admin_style', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'simpleblog', 'sekizai', 'django.contrib.sites', 'cms', 'menus', 'treebeard', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
ElastiCache(redis) cluster mode enabled with django
I configured ElastiCache redis with cluster mode enabled. I want to connect ElastiCache with local Django. So I configured bastion host. I connected ElastiCache(non-cluster mode) with local Django. I tried cache.set(), cache.get(). It's OK. I installed 'Django-redis-cache' and 'settings.py' is like that. CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': 'localhost:6379', } } But I have problem when I connect ElastiCache(cluster mode) with django. I tried tunneling with ElastiCache configuration endpoint. When I use the same 'settings.py', error message is like that. 'SELECT is not allowed in cluster mode' So, I changed 'settings.py'. CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': 'localhost:6379', 'OPTIONS': { 'DB': 0 }, } } And then, error message is like that. 'MOVED 4205 xx.xx.xx.xxx:6379' What I have to do? There are no example which connect ElastiCache(cluster mode) with Django.