Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting IntegrityError:unique constraint failed, Unique constrain is required
I am getting integrity error because of the unique key constraint, And I don't want to remove Unique constraint from there. I have tried python manage.py flush and make migration again but still its not working. Unique constraint is most required there as it is going to user as a unique username. Code as follow test.py from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='tatanano@nano.com', password='password1234' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email='tatanano@nano.com', password='password1234', name='test user full name' ) def test_users_listed(self): """Test user that are listed on user page""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Create and save new user""" if not email: raise ValueError('Users must have valid Email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """create super user with staff permission""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model that using email instead username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff … -
Making Django Signals Specific To Admin Save ONLY
I am currently working on a Django website. I would like to figure out how to make a post_save signal that is activated ONLY when I save from Django Admin. Right now, I have made a post_save function. This works for all intents and purposes, but another part of my code uses .save() to update an Integer within the main Event model (the integer represents the number of books submitted). I update the number of books submitted upon users loading the Event page. This causes extremely long load times when users try to access a page with all previous events since it runs my "book_organizer" function for every on the page when I only need it to run when I update and save event details directly from the admin page. @receiver(post_save, sender=Event) def save_post(sender, instance, **kwargs): if instance.books_read==True: book_organizer.organize_it(instance) post_save.connect(save_post, sender=Event) What I would like to do, is make it so that my current save_post function runs ONLY when I hit the "Save" button from Django admin. I would like to avoid overriding the save function as I read that it is not recommended. -
Django admin not showing models - version 2.2
I am using Django 2.2. I don't know what I'm missing. models.py from django.db import models class Efesto(models.Model): nombre = models.CharField(max_length=150) tipo = models.ForeignKey(Color, blank=True, null=True, on_delete=models.CASCADE) .... def __str__(self): return self.nombre admin.py from django.contrib import admin from estrategia import models # Register your models here. admin.register(models.Efesto) Do I need anything else? When I open the admin, I can't see the Efesto model there. The admin.py file is created automatically by the startapp command. The urls include ... path('admin/', admin.site.urls), It has being a while since I code django, and this used to be enough to get the models registered. The app is included in settings.INSTALLED_APPS correctly. Any advice will help. -
TypeError: force_login() missing 1 required positional argument: 'user'
Test cases not able to run because of TypeError: force_login() missing 1 required positional argument: 'user' test_admin.py from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client self.admin_user = get_user_model().objects.create_superuser( email='tata@nano.com', password = 'password1234' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email='tata@nano.com', password='password1234', name = 'Ratan jamshed tata' ) def test_users_listed(self): """Test user that are listed on user page""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) Error : >docker-compose run app sh -c "python manage.py test && flake8" Creating test database for alias 'default'... System check identified no issues (0 silenced). E.... ====================================================================== ERROR: test_users_listed (core.tests.test_admin.AdminSiteTests) Test user that are listed on user page ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/core/tests/test_admin.py", line 14, in setUp self.client.force_login(self.admin_user) TypeError: force_login() missing 1 required positional argument: 'user' I have imported import authenticate, login in django.contrib.auth but still its not working. -
Use JavaScript to add dynamic fields on Django admin site
I'm using Django 2.2 with Python 3.7, my question have two parts: The main goal, is to create dynamic fields over models on admin page, so for example, I have a CharField with multiple choices, and only that charfield is being show with a null value, so if I change it to some option another charfield will appear below with more options to choose, of course, all the charfields are defined in models.py, just hidden from the admin site until the condition is met, I think the best approach will be use JavaScript, I added the /media/ folder to my project but I didn't understand well how to integrate the javascripts on the admin site, any help over that? I'm a beginner on JavaScript, I don't even know how to access the models attributes to use the .show() and .hide() methods, can anyone point me into the right direction to establish simple if conditions to show or to hide the fields based on another one? My admin class that holds the model I want to hide and show fields is the following one: class RecipesAdmin(admin.ModelAdmin): fieldsets = [ ("Title/Description", {"fields": ["recipe_title", "recipe_ingredients"]}), ("Ingredients sequence", {"fields": ["sequence"]}), ("Recipe Sequence", {"fields": ["motor1", … -
Coalesce must take at least two expressions
I'm using Django and Python 3.7. I want to write a Coalesce expression to help me write a larger Django query. I have Coalesce( F("votes") - Subquery(relevant_hour_stats.values('votes_threshold')[:1]), output_field=models.FloatField()) Here is the expression in context ... qset = ( ArticleStat.objects .all() .annotate( shifted_article_create_hour=ExtractHour(ExpressionWrapper( F('article__created_on') + timedelta(seconds=avg_fp_time_in_seconds), output_field=models.DateTimeField() )) ) .annotate( votes_above_threshold=( Coalesce( F("votes") - Subquery(relevant_hour_stats.values('votes_threshold')[:1]), output_field=models.FloatField()) ), ) .filter( votes_above_threshold__gt=0, ) ) but this is resulting in a Coalesce must take at least two expressions complaining about the line output_field=models.FloatField() as far as I can tell, I have two expressions. What else could the error be referring to? -
(admin.E116) The value of 'list_filter[3]' refers to 'groups', which does not refer to a Field
While trying to create my own user model and admin, the test gives the following error. : (admin.E019) The value of 'filter_horizontal[0]' refers to 'groups', which is not an attribute of 'account.User'. : (admin.E019) The value of 'filter_horizontal[1]' refers to 'user_permissions', which is not an attribute of 'account.User'. : (admin.E116) The value of 'list_filter[1]' refers to 'is_superuser', which does not refer to a Field. : (admin.E116) The value of 'list_filter[3]' refers to 'groups', which does not refer to a Field. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self,username,email,password=None, **extra_fields): user=self.model( username=username.lower(), email=self.normalize_email(email), **extra_fields) #user name is converted into lowercase user.set_password(password) user.save(using=self._db) return user def create_superuser(self,username,email,password=None): user = self.create_user( username,email ) user.set_password(password) user.is_superuser=True user.is_staff =True user.save(using=self._db) return user class User(AbstractBaseUser): username=models.CharField(max_length=255,unique=True) email=models.EmailField(max_length=255,unique=True) password=models.CharField(max_length=255) is_staff =models.BooleanField(default=False) is_active=models.BooleanField(default=True) objects=UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from . import models # Register your models here.'''' class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display=['username','email'] admin.site.register(models.User,UserAdmin) admintest.py from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( username='admin', password='123', email='fda@gmail.com' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( username='mantis', password='123', email='111' … -
django-comments: How to order comments by posted date?
I'm trying to order comments in my app from recent to oldest. I'm using https://github.com/django-fluent/django-fluent-comments Because I'm using threaded comments, I have to use the {% render_comment_list for object %} Otherwise, If I use {% for comment in comment_list reversed %}, the comments are in the right order, but the formatting of replies is wrong (it doesn't preserve threading) I'm basically trying to achieve {% render_comment_list reversed for object %} How can I do this? -
Tweaking relevance scores of Elasticsearch
I'm currently setting up search functionalities in my Django project using Django-Haystack and Elasticsearch and I was wondering if there's any ways I can change the relevancy of my search results. For example, I'm able to enter a query for the destination value like Las+Vegas and it works fine, but when I get the results, I can see objects that correspond to another destination like Laos. So what can I do to get the results that match with the exact given destination and nothing else? My Models: class Product(models.Model): destination = models.CharField(max_length=255, default='') title = models.CharField(max_length=255, default='') slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='') description = models.TextField(default='') ptags = TaggableManager() image = models.ImageField(default='') timestamp = models.DateTimeField(auto_now=True) def _ptags(self): return [t.name for t in self.ptags.all()] def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug}) def __str__(self): return self.destination I'm using a custom forms.py like this: from haystack.forms import FacetedSearchForm class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag = data.get('ptags', []) super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() if self.ptag: query = None for ptags in self.ptag: if query: query += u' OR ' else: query = u'' query += u'"%s"' % sqs.query.clean(ptags) sqs = sqs.narrow(u'ptags_exact:%s' % query) return sqs … -
Text going over edge of screen
I am styling my website with Bootstrap3 in HTML. The page seems to be a little too big, and I am able to scroll horizontally, even though my browser is at normal scale. In head block, I also set the scale to match device size. https://imgur.com/bl8XbyE {% load bootstrap3 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> #I included scaling to match device size <title>Learning Log</title> {% bootstrap_css %} {% bootstrap_javascript %} </head> And I never adjusted the size in body block <body> <!-- Static navbar --> <nav class="navbar navbar-default navbar-static-top"> <div class="containter"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> </button> <a class="navbar-brand" href="{% url 'learning_logs:index' %}"> Learning Log</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'learning_logs:topics' %}">Topics</a></li> </ul> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a>Hello, {{ user.username }}.</a></li> <li><a href="{% url 'users:logout' %}">log out</a></li> {% else %} <li><a href="{% url 'users:register' %}">register</a></li> <li><a href="{% url 'users:login' %}">login in</a></li> {% endif %} </ul> </div><!--/.nav-collapse --> </div> </nav> <div class="container" <div class="page-header"> {% block header %}{% endblock header %} </div> <div> {% block content %}{%endblock content %} </div> </div> <!-- /container --> </body> </html> -
I get unrecognized option '--wsgi-file' when trying to run uwsgi
I'm setting up a test Python App on a Ubuntu server. I've installed nginx, Python and uWSGI. Nginx is able to host static files, but I get the error "uWSGI Error Python application not found" when I try to access a Python app. I have created a file named "app.py", which is a simple "Hello World" app. This file is added to the same directory as the static html file. The static file comes up, so nginx appears to be working. When I tried to access the Python app, I got the error "uWSGI Error Python application not found". I searched for this error and one recommendation is from https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html. It mentions I had to run the following command: uwsgi --http :8000 --wsgi-file test.py I changed the port number and file name to what I have on my server. But I get the error: uwsgi: unrecognized option '--wsgi-file' I googled this error and a link mentioned I would have to install the python plugin: uwsgi options --wsgi-file and --module not recognized But when I did the commands in this url, it says I already have the newest version. If I just type "uwsgi" on the command prompt, it would give … -
Does every model in a Django app have to have a corresponding reusable app created
I'm new to Django and trying to understand the preferred means of operation when building an application Let's say i'm making an e-commerce application that allows sellers to sign up, upload their products etc and allows buyers to sign up, add products to their cart and place orders. They're all part of the same "web application". So there's the shop, buyer and sellers and ofcourse the site admin. Would this mean I have a shop app, buyer app and seller app? since they'll all have their profile pages. Or they can all be together a single app? -
How to configure nginx, gunicorn make Django to service dynamic video url
Django app 'myvideoproj' with 2 pages. Page1 list videos. Click a link of a video redirects to page 2. Page 2 plays the video. It works: page 1 list all videos. page 2 plays the video. Video files are not under static. Then, configure nginx, gunicorn for the django app in production server. Page 1 is able to list video. Page 2 does not play the vide. I think nginx configuration is not configured correctly for page 2. Please help! settings.py hostname = socket.gethostname() SERVER_LIST = { 'myserver’': { 'movie_dir': '/path/my/home/video/', # store all video 'siteicon_url': 'www.mydomain.com:8000', 'url_playmovie': www.mydomain.com:8000/playvideo/', }, } SERVER = SERVER_LIST[hostname] MOVIES_DIR = SERVER['movie_dir'] URL_VIDEOLIST = SERVER['siteicon_url'] URL_PLAYMOVIE = SERVER['url_playmovie'] if DEBUG: STATIC_ROOT = os.path.join(BASE_DIR, '/static') else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( (os.path.join(SITE_ROOT, 'static/')), MOVIES_DIR, # Make sure page 2 is able to find real location of video, which is NOT under static. ) Page 1 html sample. User can click it. <a href=".....mydomain.com:8000/playvideo/myvideo_sample.mp4"> <img src="data:image/png;base64,..blablathumbnail..==" atl=""> </a> Page 2 html sample. Without nginx, gunicorn (start django server in command line), it plays the video. WITH nginx, gunicorn (start nginx service and gunicorn service, it does … -
How to set up a select menu to sort the context list
I am trying to set up a form to order the list of products I am receiving from the view function and display it on the template again. How do I go about achieving this? (Better if it's without reloading of page)? I am pretty new to Django and web app development in general, so intrigued to know what possibilities do I have here. I tried reading a bit around, found some keywords like AJAX and GET/POST requests but couldn't make sense of them or how to go about implementing them in my current framework. Here's my template: <select> <option value="">Sort by</option> <option value="1">Price - ASC</option> <option value="2">Price - DESC</option> <option value="3">Title - ASC</option> <option value="4">Title - DESC</option> </select> {% for product in all_products %} {% if forloop.first %}<div>{% endif %} {% endfor %} The views.py: def home_view(request, *args, **kwargs): context = { 'all_products':Product.objects.all() } return render(request,"home.html",context) Now I want functionality to select an option from the form on my template and the products data is sorted accordingly. It'd be a great help if you guys could at least guide me to the right way to learn about techniques to achieve this kind of a result or if you have … -
How do you create a custom table in Django that is not many-to-many?
I have the following schema: class Website(models.Model): identifier = models.CharField( verbose_name=_('Identifier'), max_length=20, unique=True, validators=[validate_external_id], ) class Page(models.Model): campaign = models.ForeignKey( "mediabuying.Campaign", blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_('Current Campaign'), related_name="campaign", ) class Campaign(models.Model): account = models.ForeignKey( Account, blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_('Account'), ) class Account(models.Model): network = models.CharField( max_length=40, verbose_name=_('Network'), ) Now I am interested to create a table, Website_Network, that consists of rows of (website_id, network) which is a shortcut for (website_id, website.page.campaign.account.network). This is not a many-to-many relationship table because I am mapping pk (website_id) to a string (network). How should I go about accomplishing this? -
Django 2 login middleware
I'm trying to find out what's the standard way to create and use a login middleware in Django 2.2. All the questions here are very old and Django 1 based. The documentation doesn't actually help too much. Is there any updated example? -
How do I sort two converged lists by datetime?
I have converged two different lists. How do I sort them by date/time? foo = get_list_or_404(Comments, equoes=user) foo2 = get_list_or_404(Comments, User=user) info = (foo+foo2) for x in info: print(x.dt) Everything I am looking for comes up in the printout, but I need to sort it by time. How would I go about this? (This is how it prints, the last two being from the added list.) 2019-05-03 17:12:55.611679+00:00 2019-05-03 17:58:08.319295+00:00 2019-05-03 18:13:19.608188+00:00 2019-05-03 15:06:43.242201+00:00 2019-05-03 14:47:19.166391+00:00 -
how to load a url path on timeout
class QuizTake(FormView): form_class = QuestionForm template_name = 'question.html' result_template_name = 'result.html' single_complete_template_name = 'single_complete.html' def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied try: self.logged_in_user = self.request.user.is_authenticated() except TypeError: self.logged_in_user = self.request.user.is_authenticated if self.logged_in_user: self.sitting = Sitting.objects.user_sitting(request.user, self.quiz) else: self.sitting = self.anon_load_sitting() if self.sitting is False: return render(request, self.single_complete_template_name) return super(QuizTake, self).dispatch(request, *args, **kwargs) def get_form(self, *args, **kwargs): if self.logged_in_user: self.question = self.sitting.get_first_question() self.progress = self.sitting.progress() else: self.question = self.anon_next_question() self.progress = self.anon_sitting_progress() if self.question.__class__ is Essay_Question: form_class = EssayForm else: form_class = self.form_class return form_class(**self.get_form_kwargs()) def get_form_kwargs(self): kwargs = super(QuizTake, self).get_form_kwargs() return dict(kwargs, question=self.question) def form_valid(self, form): if self.logged_in_user: self.form_valid_user(form) if self.sitting.get_first_question() is False: return self.final_result_user() else: self.form_valid_anon(form) if not self.request.session[self.quiz.anon_q_list()]: return self.final_result_anon() self.request.POST = {} return super(QuizTake, self).get(self, self.request) def get_context_data(self, **kwargs): context = super(QuizTake, self).get_context_data(**kwargs) context['question'] = self.question context['quiz'] = self.quiz if hasattr(self, 'previous'): context['previous'] = self.previous if hasattr(self, 'progress'): context['progress'] = self.progress return context def form_valid_user(self, form): progress, c = Progress.objects.get_or_create(user=self.request.user) guess = form.cleaned_data['answers'] is_correct = self.question.check_if_correct(guess) if is_correct is True: self.sitting.add_to_score(1) progress.update_score(self.question, 1, 1) else: self.sitting.add_incorrect_question(self.question) progress.update_score(self.question, 0, 1) if self.quiz.answers_at_end is not True: self.previous = {'previous_answer': guess, 'previous_outcome': is_correct, 'previous_question': self.question, 'answers': self.question.get_answers(), 'question_type': {self.question .__class__.__name__: True}} … -
How to fix django-ratings error 'No module named 'forms''
I have installed the django-ratings app, followed the instruction provided, yet I am still having some trouble making it work. I cannot add rating field to my model. I get an error: site-packages/djangoratings/fields.py", line 4, in <module> import forms ImportError: No module named 'forms' I've checked fileds.py, it tries to import forms, however, the forms.py file is in the directory. What can I do to fix it? Can anyone see what I might have done wrong? Or could you suggest any other package with similar functionality (rating that uses cookies to prevent multiple voting)? -
Django + React on the same developing server/port
I'm trying to launch my React on the same server and port that Django runs (the django managed server). It seems ULRs are correctly setted because I can load /public/index.html React page, but its not able to load my app, just the static HTML. It ocours when I launch django server: python manage.py runserver When I launch React app from: npm start (Node), it works fine, and I can start the Django server (different port, same localhost); they work together like that, but it's not what i want. Exploring code, I see that if I start React app with Node server, a script line is automatically added (see last tag): <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="/manifest.json" /> <!-- Notice the use of in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will work correctly both with client-side routing and … -
Django regex to validate form to not accept 'http' or 'https' in message body
I tried to use regexvalidators from django to validate form so that it does not contain http or https (many spammers using link) but it doesn't work. Thanks in advance from django import forms from django.core.validators import RegexValidator from antispam.honeypot.forms import HoneypotField class ContactForm(forms.Form): name = forms.CharField(max_length=50) email = forms.EmailField() phone = forms.CharField(max_length=11) message = forms.CharField(widget=forms.Textarea, validators=[RegexValidator(regex=r'http(s)?|HTTP(s)?', message="I don't accept link", code="invalid")]) spam_honeypot_field = HoneypotField() -
How to scale chat application database?
I have made a chat application where for now I am storing complete history of chat of all the users. I am using django as backend and postgres as the database. I am nearing 100k daily active users which makes around 1 million messages per day. So I am wondering how to scale the postgres data horizontally? I have heard that sharding is not simple in SQL databases and also they have limit to scaling. Like I have heard that Google's big table can scale to 100 of petabytes while postgres is hard to scale to that level. Is it true? If not, how to scale at moment? Also, how to tackle with messages history, they will eventually get too big to handle? Another question is should I shift to another dataset to handle scaling like mongodb or Cassandra or anything else, because it makes me fear that eventually I will have to scale to billions of messages per month level and if I can shift now that would be better. I don't want to over think or over analyse but just want to get perspective of how to go about it -
How to show only one result if it is not unique in a Jquery Autocomplete and Django
I just finished adding an autocomplete with Jquery in my Django project and it seems to be working fine by showing me the result. The only problem is that I want to search by destination, not title and since I have multiple objects that have the same destination value and my autocomplete is set up to show 5 results, I get 5 time the same result. How can set this up to make the autocomplete show only one result if it is not unique. Here's a link to the image of the problem: https://imgur.com/SGWIR8X I use this custom Javascript code for the autocomplete: $(function () { 'use strict'; $('#q').autocomplete({ serviceUrl: "http://127.0.0.1:8000/search/autocomplete/", minChars: 2, dataType: 'json', type: 'GET', onSelect: function (suggestion) { console.log( suggestion.value + ', data :' + suggestion.data); } }); }); My Views.py autocomplete function: def autocomplete(request): sqs = SearchQuerySet().autocomplete( content_auto=request.GET.get( 'query', ''))[ :5] s = [] for result in sqs: d = {"value": result.destination, "data": result.object.slug} s.append(d) output = {'suggestions': s} return JsonResponse(output) My Models.py: class Product(models.Model): destination = models.CharField(max_length=255, default='') title = models.CharField(max_length=255, default='') slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='') description = models.TextField(default='') ptags = TaggableManager() image = models.ImageField(default='') timestamp = models.DateTimeField(auto_now=True) def _ptags(self): return [t.name … -
Exception Value: name 'template' is not defined
Initially, the validation check worked, and in which case it generated an error message. But when I used inheritance with mixins so that there was logic to get an strange error. Views.py class TagCreate(LoginRequiredMixin, ObjectCreateMixin, View): model_form = TagForm template = 'blog/tag_create.html' raise_exception = True Utils.py class ObjectCreateMixin: model_form = None template = None def get(self, request): form = self.model_form() return render(request, self.template, context={'form': form}) def post(self, request): bound_form = self.model_form(request.POST) if bound_form.is_valid(): new_obj = bound_form.save() return redirect(new_obj) return render(request, template, context={'form':bound_form}) #Here is an error in django debugger Forms.py class TagForm(forms.ModelForm): class Meta: model = Tag fields = ['title', 'slug'] widgets = { 'title': forms.TextInput(attrs={'class':'form-control'}), 'slug': forms.TextInput(attrs={'class':'form-control'}), } def clean_slug(self): new_slug = self.cleaned_data['slug'].lower() if new_slug == 'create': raise ValidationError('Slug may not be "Create"') if Tag.objects.filter(slug__iexact=new_slug).count(): raise ValidationError('Slug must be unique. We have "{}" slug already'.format(new_slug)) return new_slug -
Django Rest + React: how to restrict domain origin of requests
I am currently building a web application. My front-end is developed using React and Axios (for API call requests). It is served directly by Nginx on app.mydomain.com My back-end is developed using Django and Django Rest. It is served with Nginx and Gunicorn on api.mydomain.com. It only serves API endpoints. So the front-end and the back-end are separated. I would like only my front-end (app.mydomain.com) to be able to make API requests to my Django Rest backend. I would like to prevent any other domain, any clients such as postman, insomnia, curl or any script to make API requests to my backend. I have already set CORS in Django Rest. However, I can still make requests to the backend using curl or any other client. Do you have any idea of what I could do to achieve this? Thanks a lot in advance for you answers.