Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom ID field with if condition
I am going to set the custom id with the name of "membership_num" with the increment number by 1, in every new register athlete with a prefix for each record like: if the "goal field in model" is "gym" it should generate the ID: description: N-Gym-Year Month Day then the number N-G-20120700001 N-G-20120700002 N-G-20120700003 if the "goal field in model" is "fitness" it should generate the ID: description: N-Gym-Year Month Day then the number N-F-20120700001 N-F-20120700002 N-F-20120700003 Models.py class Athlete(models.Model): first_name = models.CharField(max_length=50) membership_num = models.CharField(max_length=255, blank=True, editable=False) goal = models.CharField(max_length=10, choices=[('gym', 'Gym'), ('fitness', 'Fitness')]) I found and tried the following solution in stackoverflow but it does not generate the correct ID... def save(self, *args, **kwargs): # super().save(*args, **kwargs) if not self.membership_num: prefix = 'N{}'.format(timezone.now().strftime('%y%m%d')) prev_instances = self.__class__.objects.filter(membership_num__icontains=prefix) if prev_instances.exists(): last_instance_id = prev_instances.last().membership_num[-4:] self.membership_num = prefix + '{0:04d}'.format(int(last_instance_id) + 1) else: self.membership_num = prefix + '{0:04d}'.format(1) super(Athlete, self).save(*args, *kwargs) please help me.... -
TemplateDoesNotExist at / in django
enter image description here from .shortcuts import render from .models import Post Create your views here. def list_of_post(request): post = Post.objects.all() template = 'post/list_of_post.htenter code hereml' context = {'post': post} return render(request, template, context) It should work. -
Django - can't get modelchoice FK while submitting form
I have a custom form form signup, referencing a "categorie" model on a modelChoiceField. As I try to submit it, it fails on getting the reference to the model and raises the following error : IntegrityError at /marketplace/signsupplier/ null value in column "categorie_id" violates not-null constraint DETAIL: Failing row contains (55, , , , , , null). It's as if it loses all posted datas, but I can see in the debug that categorie_id is well passed in the POST datas. Here is my model.py : class Supplier(models.Model): phone_regex = RegexValidator(regex=r'^(87|89)\d{6}$', message="Entrez un numéro de portable Polynésien valide") user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) enseigne = models.CharField(max_length=128, blank=False, null=False) vini = models.CharField(verbose_name="Vini",validators=[phone_regex], max_length=8, blank=False, null=False) numero_tahiti = models.CharField(max_length=9, blank=False, null=False) immat_rcs = models.CharField(max_length=9, blank=False, null=False) categorie = models.ForeignKey(Categorie, on_delete=models.DO_NOTHING) labels = models.CharField(max_length=128) my forms.py : class SignupSupplierForm(UserCreationForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=True,label="Prenom") last_name = forms.CharField(required=True,label="Nom") vini = forms.CharField(required=True, max_length=8,validators=[phone_regex]) enseigne = forms.CharField(required=True, max_length=128, label="Enseigne") numero_tahiti = forms.CharField(required=True, max_length=9, label="Numéro Tahiti") immat_rcs = forms.CharField(required=True, max_length=9, label="Immatriculation RCS") categorie = forms.ModelChoiceField(required=False,queryset=Categorie.objects.all()) labels = forms.CharField(required=False,max_length=128, label="Labels (option)") class Meta(UserCreationForm.Meta): model = User fields = ('email','first_name','last_name') @transaction.atomic def save(self): user = super().save(commit=False) user.is_supplier = True user.save() supplier = Supplier.objects.create(user=user) supplier.vini = self.cleaned_data.get('vini') supplier.enseigne = … -
how to host Django Web application on Apache or wamp? [closed]
I have created simple django web application but I don't want to host it on third party server(heroku, pythonanywhere.com). I want to host it on apache server on intranet. How can I do it? -
"rest_framework CSRF token failed" but it's already in the request header as "X-CSRF-Token"
Already checked other topics and tried the answered solutions but the problem stays still. My put/post requests are return with an error. detail: "CSRF Failed: CSRF token missing or incorrect." Although I am sending CSRFToken inside the header axios.defaults.headers.common['X-CSRF-Token'] = CSRF_TOKEN; And there it is the CSRF By the way, in settings.py I gave the authentication classes 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], Additionally views.py class ProjectViewSet(viewsets.ViewSet): permission_classes = [IsAuthenticated | IsSuperUser] # retrieve works without a problem def retrieve(self, request, pk=None): queryset = Project.objects.all().filter(company_user=self.request.user) project = get_object_or_404(queryset, pk=pk) serializer = ProjectSerializer(project) return Response(serializer.data) def update(self, request, pk=None): # CSRF request problem pass def partial_update(self, request, pk=None): # CSRF request problem pass and urls.py router = DefaultRouter() router.register('project', views.ProjectViewSet, basename='project') urlpatterns = router.urls Do I missing something here? Why do I keep having the CSRF error? -
Understanding request.data in djnago view
I tried looking at different resources on the internet regarding this request and request.data in django, but I couldn't fully understand it. Why this request parameter is kept inside the function? What are we passing in this request parameter?? Also, what does this request. data do?? def index(request): content = { 'Blogdata': Blog.objects.all(), } return render(request, 'index.html', content) def somefunction (request): data=request.data As you can see I have two functions above both of them have request paramter inside the function. Also, I need the explanation on this request.data as this has to be used multiple times. -
Email is not sending in django after deploy in Cpanel
I just deploy a Django web app in Cpanel. But SMTP email is not working in Cpanel. It works only on my local machine. I don't have much knowledge about Cpanel. Here is my code for setting.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'my gmail' EMAIL_HOST_PASSWORD = 'password' -
django channel async consumer stop receiving after call non-stop function
this is the function thats call inside async consumer ,after it listen_some_change() is called ,it stops receiving new message def listen_some_change(self): #self.get_volume() conn = psycopg2.connect(user=DB_USER,password=DB_PASSWORD,host=DB_HOST, port=DB_PORT,database=DB_DATABASE) curs = conn.cursor() curs.execute("LISTEN some_changes;") seconds_passed = 0 while True: conn.commit() if select.select([conn],[],[],5) == ([],[],[]): seconds_passed += 5 #print ("{} seconds | mydevices_volume_change notification ...".format(seconds_passed)) else: conn.poll() conn.commit() while conn.notifies: notify = conn.notifies.pop() payload = json.loads(notify.payload) print(payload) -
How to save MantToMany filed attribute in databse?
I am making an api in django rest framework. I have created three models in Linkeddata, Individuals group, Event. I have another model Keybase which is another app and have ManyToMany relation with Individual, group and Event. Linked data is in ManyToMany Relation with Individual group and event. While adding data in database,I came to a problem where I dont know How I should save keybase and LinkedData data in Individual, Group and Event table. Here is my code: models.py from django.db import models from account_management.models import User from django.utils import timezone from keybase_management.models import Keybase from django.utils.translation import gettext as _ from django.contrib.postgres.fields import ArrayField import datetime from .validators import validate_event_date, validate_expiry_date # Create your models here. GENDER = [('male', _('Male')), ('female', _('Female')), ('other', _('Other'))] class LinkedData(models.Model): type = models.CharField(default='', max_length=225) query = models.CharField(default='', max_length=225) data = models.JSONField(default={'key': 'value'}) class Portfolio(models.Model): class Meta: abstract = True user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=225, default='') created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) expire_on = models.DateTimeField(default=timezone.now() + datetime.timedelta(hours=1), validators=[validate_expiry_date]) # targets=models.ForeignKey() keybase = models.ManyToManyField(Keybase) linked_data = models.ManyToManyField(LinkedData) addresses = ArrayField(models.CharField(default='null', max_length=225)) phone_numbers = ArrayField(models.CharField(default='0', max_length=11)) descriptions = ArrayField(models.CharField(default='null', max_length=225)) def __str__(self): return self.title @staticmethod def get_all_portfolios(): pass def create_portfolio(self): pass def add_phone_numbers(self): … -
how to make sub pages url in django
In my online store django project, I want to create a sub-page which shows the details of a product that is listed in a page. in urls.py I created the urls for both pages like bellow: path('wwqm', views.water_quality_sensor , name='wwqm'), path('wwqm/<str:water_sensor_title>', views.water_sensor_item, name='water_sensor_item'), in this scenario, a bunch of items are being shown in wwqm. user click on a product and the water_sensor_item should load up. I know its not important but here is views.py: def water_quality_sensor(request): queryset_list = Water_quality_sensor.objects.order_by('-product_name').filter(is_published=True) context = { 'water_quality_sensor': queryset_list, } return render(request, 'products/water_quality_sensor.html', context) def water_sensor_item(request, water_sensor_title): water_sensors = get_object_or_404(Water_quality_sensor, title=water_sensor_title) context = { 'water_sensors': water_sensors } return render(request, 'products/water_sensor_item.html' , context) I try to build the url for each item based on a parameter that is passed to its view(products title). In my templates, I try to create a link like the following: <a href="{% url 'water_sensor_item' w_q_sensor.title %}" class="card hoverable mb-4 text-dark" > one my products' title is 3725. when I click on that product in the main page, I get the following error: Django Version: 3.1.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'water_quality_sensor' not found. 'water_quality_sensor' is not a valid view function or pattern name. What am I doing wrong? -
How to fetch database data based on dropdown selected value in Django?
I uploaded questions into database with dropdown values like PAPER1, PAPER2 etc.., In my template page if i click on PAPER1 i should get only PAPER1 questions. How to fetch the data like that? please help me. models.py: class Questions(models.Model): paper = models.CharField(max_length=10, default='None') qs_no = models.IntegerField(default=None) question = models.TextField(max_length=500) option_a = models.CharField(max_length=100) option_b = models.CharField(max_length=100) option_c = models.CharField(max_length=100) option_d = models.CharField(max_length=100) ans = models.CharField(null=True, max_length=50) forms.py: PAPER_CHOICES = ( ('default', 'None'), ('paper1','PAPER1'), ('paper2','PAPER2'), ('paper3','PAPER3'), ('paper4','PAPER4'), ('paper5','PAPER5'), ('paper6','PAPER6'), ('paper7','PAPER7'), ('paper8','PAPER8'), ('paper9','PAPER9'), ('paper10','PAPER10'), ) class QuestionsForm(forms.ModelForm): paper = forms.CharField(widget=forms.Select(choices = PAPER_CHOICES)) class Meta: model=Questions fields=[ 'paper', 'qs_no', 'question', 'option_a', 'option_b', 'option_c', 'option_d', 'ans', ] views.py: def render_questions(request): print(f'user in render_questions is {request.user.username}', flush=True) if not request.user.is_authenticated: return render(request, 'login.html') else: global exam_session exam_session = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) print(f"session id in render ques is {exam_session}", flush=True) questions = Questions.objects.all() ques = [] qs_no = 1 for q in questions: que = {} que['qs_no'] = qs_no qs_no = qs_no + 1 que['question'] = q.question que['id'] = q.id que['option_a'] = q.option_a que['option_b'] = q.option_b que['option_c'] = q.option_c que['option_d'] = q.option_d ques.append(que) print(f"ques: {ques}", flush=True) return render(request, 'report.html', {'ques': ques}) template.html: <form id="myform" name="myform" action="answer" method="POST"> {% csrf_token %} <div class="questionContainer"> … -
How to change Div width with scroll
I have a contact form towards the bottom of my webpage and I would like to run an animation each time the form section of my webpage is viewed. I have been successful in running it, however I would like to run a second animation when scrolling away from the form. The animation is just an underline underneath the contact tab. The result I am trying to achieve is increasing the width of the underline (contact tab) when contact form is viewed and decreasing the underline width when scrolling away from it. I have created two separate ccs files to call when needed. Here is my code. css files (increase width animation) underLineAnimate.css #contactLink{ background-image: linear-gradient(#00bbcb, #00bbcb); background-position: bottom center; /*Adjust the background-position to move the line*/ background-size: 60% 2px; /*Adjust the background size to control length and height*/ background-repeat: no-repeat; padding-bottom: 4px; /* this can also control the position */ animation-name: forContactL; animation-duration: 2s; } @keyframes forContactL { from {background-size: 10% 2px;} to {background-size: 60% 2px;} } decrease width animation underLineDecrease.css #contactLink{ background-image: linear-gradient(#00bbcb, #00bbcb); background-position: bottom center; /*Adjust the background-position to move the line*/ background-size: 0% 2px; /*Adjust the background size to control length and height*/ background-repeat: no-repeat; … -
Django 500 (Internal Server Error). Failed to load resource. Javascript
Working on Django project. I'm trying to implement the follow button like on Instagram. I'm trying to send fetch request when I press the follow button and update the followers count on the back end. and later get a response on the updated count and update the innerHtml on the page. but I'm getting the following error. if someone can help me out if would be great. index.js:13 Fetch failed loading: POST "http://127.0.0.1:8000/follow". It is showing error below in fetch code failed to load resource: the server responded with a status of 500 (Internal Server Error) Here is my code: URL path("follow", views.follow, name="follow"), Model class User(AbstractUser): followersCount = models.IntegerField(blank=True) followingCount = models.IntegerField(blank=True) def __str__(self): return f"{self.username}" class FollowList(models.Model): userName = models.CharField(max_length=64) followersList = models.ManyToManyField(User, blank=True, related_name="followers") followingList = models.ManyToManyField(User, blank=True, related_name="following") View: @csrf_exempt @login_required def follow(request): # Composing a new email must be via POST if request.method != "POST": return JsonResponse({"error": "POST request required."}, status=400) # get data user = request.user currentUser = user.username a = User.objects.get(username = currentUser) data = json.loads(request.body) user_name = data.get("username") b = User.objects.get(username= user_name) status = data.get("status") try: a1 = FollowList.objects.get(username=currentUser) b1 = FollowList.objects.get(username=user_name) except FollowList.DoesNotExist: a1 = FollowList(username=currentUser) b1 = FollowList(username=user_name) a1.save() b1.save() … -
Subtract tags in Django
Im been wondering if it is possible to subtract two tags variable in Django something like this, thanks for the help {% for user_information in values.qs %} <td>{{user_information.amount|floatformat:2|intcomma}} - {{user_information.amount_paid|floatformat:2|intcomma}} </td> {% endfor %} -
How to add a unique code for every classroom in django
So, I am trying to build a simple elearning platform with django. What I want to achieve is that for every classroom that a teahcer creates, a unique 6 digit code is also generated, and when a student enters that code, he is admitted inside the classroom. I have a classroom model like this: class Classroom: name = models.CharField(max_length=20) code = models.IntegerField() def __str__(self): return self.title I really don't think an IntegerField would do the work here. Can anyone help me out? -
How do i filter specific set of data from mongo db using django
I need to fetch states list based on country id. The following code is working states_query = States.objects.all() states_result = StatesSerializer(states_query, many=True) but when i use states_query = States.objects.all().filter(country_id=id) states_result = StatesSerializer(states_query, many=True) it is not fetching the results. I am new to mongo db. Please help me with this. Thanks in advance -
Adding custom javascript audio recording filed to wagtail admin interface
I would like to add custom javascript audio recorder to the admin page in Wagtail. It have been suggested to customize the Time-Date widget which already uses Js. I've modified the original widget to the following code but it seems like it's more complicated than I thought. Demo of the recorder that I want to use is available at Mozilla's MediaRecorder-examples Here is the Js code and html for it. The code so far is: import json from django import forms from django.conf import settings from django.forms import widgets from django.utils.formats import get_format #from wagtail.admin.datetimepicker import to_datetimepicker_format from wagtail.admin.staticfiles import versioned_static # ~ DEFAULT_DATE_FORMAT = '%Y-%m-%d' # ~ DEFAULT_DATETIME_FORMAT = '%Y-%m-%d %H:%M' # ~ DEFAULT_TIME_FORMAT = '%H:%M' class AdminDateInput(widgets.DateInput): template_name = 'wagtailadmin/widgets/date_input.html' def __init__(self, attrs=None, format=None): default_attrs = {'autocomplete': 'off'} fmt = format if attrs: default_attrs.update(attrs) if fmt is None: fmt = getattr(settings, 'WAGTAIL_DATE_FORMAT', DEFAULT_DATE_FORMAT) self.js_format = to_datetimepicker_format(fmt) super().__init__(attrs=default_attrs, format=fmt) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) config = { 'dayOfWeekStart': get_format('FIRST_DAY_OF_WEEK'), 'format': self.js_format, } context['widget']['config_json'] = json.dumps(config) return context @property def media(self): return forms.Media(js=[ #versioned_static('wagtailadmin/js/date-time-chooser.js'), versioned_static("css/custom.js") ]) -
How to create a custom response for permission classes like IsAuthenticated in Django Rest Framework?
How can I create custom response for permission classes The response now is: {"detail": "Authentication credentials were not provided."} The response I want: { "status": 403, "message": "Authentication credentials were not provided", "response": {....} } -
Django rq-scheduler: jobs in scheduler doesnt get executed
In my Heroku application I succesfully implemented background tasks. For this purpose I created a Queue object at the top of my views.py file and called queue.enqueue() in the appropriate view. Now I'm trying to set a repeated job with rq-scheduler's scheduler.schedule() method. I know that it is not best way to do it but I call this method again at the top of my views.py file. Whatever I do, I couldn't get it to work, even if it's a simple HelloWorld function. views.py: from redis import Redis from rq import Queue from worker import conn from rq_scheduler import Scheduler scheduler = Scheduler(queue=q, connection=conn) print("SCHEDULER = ", scheduler) def say_hello(): print(" Hello world!") scheduler.schedule( scheduled_time=datetime.utcnow(), # Time for first execution, in UTC timezone func=say_hello, # Function to be queued interval=60, # Time before the function is called again, in seconds repeat=10, # Repeat this number of times (None means repeat forever) queue_name='default', ) worker.py: import os import redis from rq import Worker, Queue, Connection import django django.setup() listen = ['high', 'default', 'low'] redis_url = os.getenv('REDISTOGO_URL') if not redis_url: print("Set up Redis To Go first. Probably can't get env variable REDISTOGO_URL") raise RuntimeError("Set up Redis To Go first. Probably can't get … -
Django - Javascript error 404 how do i solve this?
I am working with Open Layers API page1:someone puts in list of cities they'd visit page2:the route is displayed using data from GeoJson This works well without Django but with Django i am getting error 404 data .geojson not found project structure maps form admin urls views manage(my python file) models apps maps admin urls settings static main.js styles.css libs(for openlayers) v6.4.3 ol.css ol.css.map ol.js ol.js.map data.GeoJson package.Json templates home.html (form) result.html (output) enter image description here -
AttributeError at /api/module/list/
I want many to many fields to be displayed in module serializer instead of id, these are my serializers class TrainerSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', ] class ModuleSerializer(serializers.ModelSerializer): trainer = serializers.CharField(source='trainer.username') class Meta: model = Module fields = ['id', 'title', 'duration', 'trainer', 'publish_choice'] and this is the error message Got AttributeError when attempting to get a value for field `trainer` on serializer `ModuleSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Module` instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'username'. -
JSON fields serializer errors in Django rest framework
when I do input data then I want to check the data key is valid or not by Django rest API JSON serialize field. I have a JSON serializer in serializers.py like as class EmployBasicInfoSerializers(serializers.Serializer): basic_info = serializers.JSONField() designation = serializers.JSONField() academic_info = serializers.JSONField() address = serializers.JSONField() password = serializers.JSONField() and my views function is: def employ_create(request): if request.method == 'POST': json = JSONRenderer().render(request.data) stream = io.BytesIO(json) data = JSONParser().parse(stream) data_serializer = EmployBasicInfoSerializers(data=data) if data_serializer.is_valid(): pass return Response({'data_status':data_serializer.errors}, status=rest_framework.status.HTTP_400_BAD_REQUEST) Then I input JSON data like as: { "basic_info": { "name":"tushar", "gender":"male", "date_of_birth":"2020-08-22", "age":27, "phone_number":8667, "email":"mntushar25@gmail.com" }, "designation":{ "id": 2 }, "academic_info":[ { "degree":"hsc", "last_passing_institution_name":"hgygjhgy", "last_passing_year":"2020-08-22" }, { "degree":"hsc", "last_passing_institution_name":"hgygjhgy", "last_passing_year":"2020-08-22" } ], "address":{ "house_no":8787, "village_name":"kushtia", "post_office":"daulatpur", "thana_name":"daulatpur", "district_name":"kushtia" }, "password":"admin" } But I get errors form data_serializer validation. The errors are: { "data_status": { "name": [ "This field is required." ], "gender": [ "This field is required." ], "date_of_birth": [ "This field is required." ], "phone_number": [ "This field is required." ], "email": [ "This field is required." ] } } I can't understand why these errors occur. pls, help me to solve the errors..... -
Django Angular Lazy Loading and routing not working
I am using Django and angular 10. I am implementing lazy loading on angular side, this works fine when I run angular app independently. However, with Django same router fails to load. To integrate with Django and Angular, I am serving build file found in dist from Django using home url and corresponding html file code is added below Django URL patterns url(r'^home/$', home), url(r'^home/login', home), url(r'^home/moduleone/childurl', home), url(r'^home/moduletwo', home), Angular router const routes: Routes = [ { path: 'login', component: SignInComponent }, { path: 'moduleone', component: HomeComponent, children:[{path:'childurl',component: ChildComponent}]}, //normal router which maps to router home/moduleone/childurl on angular side { path: 'moduletwo', loadChildren: () => import('./moduletwo/moduletwo.module').then(m => m.moduletwo) }, //lazy module ]; So when I access url http://localhost:4200/home/moduleone/childurl --> works fine, because this is not lazy loaded module http://localhost:4200/home/moduletwo ---- does not works fine, because this is lazy module on angular side Home page Html file <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Home pag</title> <base href="/home"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <!--<link rel="stylesheet" href="node_modules/@forevolve/bootstrap-dark/dist/css/bootstrap-dark.css" />--> <link rel="stylesheet" href="static/dist/project/styles.css"></head> <body data-spy="scroll" data-target="#navbar" data-offset="72" class="position-relative"> <app-root></app-root> <script src="static/dist/project/polyfills.js" defer></script> <script src="static/dist/project/scripts.js" defer> </script><script src="static/dist/project/vendor.js" defer></script> <script src="static/dist/project/main.js" defer></script> <script src="static/dist/project/runtime.js" defer></script> <script src="static/dist/project/polyfills.js" defer></script> <script src="static/dist/project/scripts.js" defer></script> … -
CSRF cookie not set Django cross-site iframe in chrome
I'm trying to use an iframe of my django site in a different domain, however whenever I submit a form, It says the CSRF cookies is not set. This occurs in chrome and safari. I am running Django 3.1.0. I've tried adding the following settings in my settings.py: SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SECURE = True X_FRAME_OPTIONS = 'ALLOWALL' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = None CSRF_COOKIE_HTTPONLY = False CSRF_TRUSTED_ORIGINS = [ 'otherdomain.com', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] Further, I can confirm the csrf token is being set in the form using: {% csrf_token %} Lastly, I've also added the @xframe_options_exempt decorator to the form page. Edit: I am also using the render method to display the form as recommended by the documentation. Edit2: For some more context, this form functions fine when it is used in the host domain (not an iframe) Unfortunately the csrf exempt decorator is not an option for me. I've tried clearing my cookies, though it does not solve my problem. Any help would be greatly appreciated! -
django.db.utils.ProgrammingError: relation "blog_category" does not exist
I started a Django project and I am not sure what I am missing. Prior to this error, I deleted the database, and deleted the migrations as well because I wanted the post to have an UUID. I got this error when I created my docker-compose-prod.yml file and all the django security stuff in the settings.py file(I am assuming all the security code I wrote in the settings.py file work because the warning signs do not show up): django.db.utils.ProgrammingError: relation "blog_category" does not exist As of right now, I am not sure what I am doing wrong? Also, I do not want to delete the migrations or make any changes within the database because I have the "post data" and I remember I ran into this issue a long time ago, but decided to ignore it(Meaning I went with the delete the migrations). More detail version of the error: web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.8/site- packages/django/db/backends/utils.py", line 86, in _execute web_1 | return self.cursor.execute(sql, params) web_1 | psycopg2.errors.UndefinedTable: relation "blog_category" does not exist web_1 | LINE 1: ...log_category"."name", "blog_category"."name" FROM "blog_cate... ... web_1 | File "/code/datablog_project/urls.py", line 30, in …