Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy Postgres11 to Elastic Beanstalk - Requires /etc/redhat-release
I'm having a hell of a time deploying my first app to Elastic Beanstalk and could really use some help. I cannot get Postgres11 to install though it is officially supported with RDS. ISSUE If I run eb deploy I get the message saying pg_config executable not found. It is required to build psycopg2 from source. /usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'project_urls' warnings.warn(msg) running egg_info creating pip-egg-info/psycopg2.egg-info writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: ... I suppose I'll need to add the repo? Fair enough. Next I try adding the repo as I have found in other posts across the internet: [ec2-user@ip-... etc]$ sudo yum -y install https://download.postgresql.org/pub/repos/yum/11/redhat/rhel-7-x86_64/pgdg-centos11-11-2.noarch.rpm Loaded plugins: priorities, update-motd, upgrade-helper pgdg-centos11-11-2.noarch.rpm | 5.6 kB 00:00:00 Examining /var/tmp/yum-root-cQJP_4/pgdg-centos11-11-2.noarch.rpm: pgdg-redhat-repo-42.0-4.noarch Marking /var/tmp/yum-root-cQJP_4/pgdg-centos11-11-2.noarch.rpm to be installed Resolving Dependencies --> Running transaction check ---> Package pgdg-redhat-repo.noarch 0:42.0-4 will be installed --> Processing Dependency: /etc/redhat-release for package: pgdg-redhat-repo-42.0-4.noarch --> Processing Dependency: /etc/redhat-release for package: pgdg-redhat-repo-42.0-4.noarch --> Finished Dependency Resolution Error: Package: pgdg-redhat-repo-42.0-4.noarch (/pgdg-centos11-11-2.noarch) … -
How to display data from two different models on the same HTML page
I have two tables one called called PlayerLkup, which contains info about the player and serves as a lookup table. I have another table (called BattingStats) which contains a player's stats (and the playerid). The BattingStats table is a one-to-many (playerid is listed multiple times, one time for each season they played). My data from PlayerLkup is displaying fine, and it is using the playerid in the URL address to retreive a specific player. My question is how do I use the data from my BattingStats model/table onto that same page? I'm assuming my views page is where the work needs to be done. Is there a way to have multiple models passed into one view? I've tried same url, different views. It didnt seem to work for me. What do I need to do? Any help here would be appreciated. I posted this question before (and have since deleted it) but someone mistakenly tagged it as a duplicate so it didn't receive any attention. models.py class BattingStats(models.Model): playerid = models.CharField(db_column='playerID', max_length=9) year = models.IntegerField(db_column='Year', blank=True, null=True) g = models.IntegerField(db_column='G', blank=True, null=True) ab = models.IntegerField(db_column='AB', blank=True, null=True) r = models.IntegerField(db_column='R', blank=True, null=True) hr = models.IntegerField(db_column='HR', blank=True, null=True) rbi = models.IntegerField(db_column='RBI', … -
How do I filter for leaf nodes in an MP_NODE
I have a tree model for categories like this: from treebeard.mp_tree import MP_Node class Category(MP_Node): ... And I want to get a queryset with only the leaf nodes. -
Django-allauth not saving additional field on custom SignupForm
I am unable to properly extend the django-allauth sign up form. The fields I need show up in my sign up form, but the rappa_name field does not get stored in my database. I followed this thread: How to customize user profile when using django-allauth But couldn't get it to work. My forms.py: from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm User = get_user_model() class UserCreationForm(UserCreationForm): rappa_name = forms.CharField(label = "Rappa Name") class Meta(UserCreationForm.Meta): model = User def signup(self, request, user): user.rappa_name = self.cleaned_data['rappa_name'] user.save() return user and my models.py class User(AbstractUser): # raooa name of user rappa_name = CharField(_("Rappa Name"), default='', max_length=255) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) I made sure that my settings.py has ACCOUNT_FORMS = { 'signup': 'myproject.users.forms.UserCreationForm', } I need the rappa_name to be saved as a field with the user, but it is currently not saving -
Running annotate or aggreagate on related objects and rendering in template?
I'm trying to do math/find the max/avg,etc. in my views and then render them in the template, but I can't seem to figure out how to get it to all work. The calculations need to be done over related objects and I feel like I've tried everything. At my wits end. views.py def program_detail_view(request, primary_key): survey = Survey.objects.get(pk=primary_key) maxResp = survey.objects.annotate(max_resp=Max('responseRelevance')) context = {'survey' : survey, 'maxResp': maxResp} return render(request, 'relevance/programStats.html', context=context) models.py class Survey(models.Model): ... class Choice(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) creationDate = models.DateTimeField(auto_now_add=True) pce = models.IntegerField( validators=[MaxValueValidator(4), MinValueValidator(1)], choices=radioChoices, ) interest = models.IntegerField( validators=[MaxValueValidator(4), MinValueValidator(1)], choices=radioChoices, ) responseRelevance = models.IntegerField(blank=True) template.html <li>Overall Relevance Score: {{ maxResp }}</li> I expect that the views will output the maximum response from the set of choices, but instead nothing shows up in the template no matter how I try to call it. I've tried the same for average and other annotate/aggregate functions. -
use of related manager with proxy models in Django
I have the following model structure: class Abstract_model(models.Model) # “Abstract model”, used to generate following 2 models. Abstract in this case is just a name foreignkey1 = models.ForeignKey("Proxy_model_1") foreignkey2 = models.ForeignKey("Just_a_Model") class Proxy_model_1(Abstract_model) # proxy model 1( main) class Meta: proxy = True class Proxy_model_2(Abstract_model)# proxy model 2(secondary) class Meta: proxy = True class Just_a_Model((models.Model) # The model. Main one... There are 1 base “abstract” model and 2 proxy models, inherited from the base model. Proxy_model_2 has many-to-one relationship to Proxy_model_1. All 3 models (Abstract_model + 2 proxy models has f/k to Just_a_Model) target (in theory) - Just_a_model.related_managet_to_proxy_model_2_set. update_or_create() Question is following: How to use related manager in this case? It is only possible to execute Just_a_Model .abstract_model_set.do_something, but I can not execute: Just_a_Model .proxy_model_1_set.do_something or Just_a_Model .proxy_model_2_set.do_something ,regardless on the fact that both 2 proxy models should inherit foreignkey1 and foreignkey2 fields (they should be connected to Just_a_model). I can execute Proxy_model_2.objects.update_or_create(foreignkey2_id=self.id), but would like to get to know how to use related manager in case of a proxy models. class Just_a_Model((models.Model) … … … def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.proxy_model_2_set.update_or_create(name=self.some_field_name ) # doesnt work self.abtract_model.do_something # does work!!! models.Model.save(self, force_insert=False, force_update=False, using=None, update_fields=None) # I could do … -
How to make existing model objects read-only but also be able to create a new one, using StackedInline class?
I have two models named 'Message' and 'Ticket'. Message has a Foreignkey to Ticket. I showed Messages of a Ticket in django admin, using StackedInline. But the problem is I want that the already created messages be read-only, while being able to create new message, too. I've also check bunch of questions; like this or this. But none of the was helpful! This is my code: models.py: class Ticket(models.Model): title = models.CharField(max_length=128) #... class Message(models.Model): text = models.TextField() ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) attachment = models.FileField(upload_to=some_url_pattern) sender = models.CharField(max_length=2, editable=False) admin.py: class MessageInline(admin.StackedInline): model = Message extra = 1 def get_readonly_fields(self, request, obj=None): if obj: return ['text', 'attachment'] else: return [] @admin.register(Ticket) class ResponderAdmin(admin.ModelAdmin): fields = ['title'] inlines = [MessageInline] As can be seen, I tried to achieve the goad by overriding get_readonly_fields but this is what happend: the page in admin As can be seen in the picture, every message inlines has been made read-only and I can not add a new message... Can anyone help me with this issue? -
How to see Django errors using NGINX and gunicorn
I have developed a Django app locally, and I am used to seeing the error messages on the webpage when things aren't correct with my programming. I have now moved this app over to digital ocean servers, using Ubuntu, NGINX, and gunicorn. Now when I have a problem in my Django code someplace, I get served very basic error messages from NGINX (or gunicorn?) on the webpage. Is there a method to see the full error log (like when the django app is being served on the local test server)? Or anyway to see more advanced error logs? DEBUG is set to True. -
Django 1.1 vs Django 2.2
I am new in Django, just made a simple blogging website and now I want to move in more complex projects. I recently find Django 1.1 ecommerce website tutorial which seems to be very nice, but I am concerned about its version. I need your advice at should I go with Django 1.1 here? how different are these two versions and what are some major changes to notice while following these tutorials? Thank you for your help! -
Retrieving user info using pyrebase
I've got this Javascript code which returns the token for Google Authentication: <script> function googleLogin(){ var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().useDeviceLanguage(); firebase.auth().signInWithPopup(provider).then(function(result) { // This gives you a Google Access Token. You can use it to access the Google API. var token = result.credential.accessToken; // The signed-in user info. var user = result.user; // ... alert(token) var csrftoken = '{{ csrf_token }}'; $.post("/api/login", {'csrfmiddlewaretoken': csrftoken, 'token': token}); }).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; // ... }); } </script> But, when I try to send this token to pyrebase to retrieve user information it returns INVALID_ID_TOKEN error This is the piece of code in which I send the token to pyrebase: user_info = auth.get_account_info(token) This is the error: requests.exceptions.HTTPError: [Errno 400 Client Error: Bad Request for url: https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=AIzaSyBUH-4_qFvkszGWxII8HyooOJNDqbltDKo] { "error": { "code": 400, "message": "INVALID_ID_TOKEN", "errors": [ { "message": "INVALID_ID_TOKEN", "domain": "global", "reason": "invalid" } ] } } -
How can to filter to display only sales for transactions that belong to logged in user in django framework class based view
class based view class SaleListView(ListView): model = Sale template_name = 'webapp/sale.html' context_object_name = 'sales' transaction model - a user can have many transactions class Transaction(models.Model): currency = models.CharField(max_length=20) amount = models.IntegerField() total_price = models.DecimalField(max_digits=7, decimal_places=2) date_purchased = models.DateTimeField() note = models.TextField(default="") owner = models.ForeignKey(User, on_delete=models.CASCADE) sale model - a transaction can have many sales class Sale(models.Model): amount_sold = models.IntegerField() total_price_sold = models.DecimalField(max_digits=7, decimal_places=2) date_sold = models.DateTimeField(default=timezone.now) note = models.TextField(default="") transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) -
No module named d while running python manage.py --settings=[mysettings]
While running command - python manage.py test --settings=todobackend.settings.test from terminal inside virtualenv I get the error ImportError: No module named d I'm running python 2.7 and Django 1.9.0 Hierarchy todobackend settings __init__.py base.py test.py manage.py test.py from base import * import os # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('MYSQL_DATABASE', 'todobackend'), 'USER': os.environ.get('MYSQL_USER', 'todo'), 'PASSWORD': os.environ.get('MYSQL_PASSWORD', 'password'), 'HOST': os.environ.get('MYSQL_HOST', 'localhost'), 'PORT': os.environ.get('MYSQL_PORT', '3306') } } base.py """ Django settings for todobackend project. Generated by 'django-admin startproject' using Django 1.11.20. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'YOUR_SECRET_KEY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'todos' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', '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', ] ROOT_URLCONF = 'todobackend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
how to retrieve id as hidden value in form so that the value get stored as foreign key in the database in django
I have a Django project and I encountered with a problem of form foreign key attribute. My project files are below : My Model.py File: appointment.html <div class="about"> <div class="abt-layer"> <div class="container"> <div class="about-main"> <div class="about-right"> <h3 class="subheading-w3-agile">Make an Appointment</h3> <!-- stats --> <div class="stats"> <div class="stats_inner"> <form method="post" > {{user.id}} {% csrf_token %} <input type="hidden" name="user_id" value="{{ user.id }}"> {{form}} <button type="submit" class="btn btn-agile btn-block w-100">Make An Appointment</button> </form> </div> </div> <!-- //stats --> </div> </div> </div> </div> </div> path('appointment/<user_id>',views.appointment,name='appointment'), def appointment(request, user_id): if request.method == 'POST': obj=User.objects.get(id=user_id) form = AppointmentForm(request.POST) if form.is_valid(): print('Hello') form.save() messages.success(request, f' Succesfully made an appointment!') return HttpResponse("success") # return redirect('users1:appointment') else: form = AppointmentForm(instance=request.user) context = {'form': form, } return render(request, 'home_temp/appointment.html', context) in models class Appointment(models.Model): user=models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) class Meta: unique_together = ('date', 'timeslot') DEPARTMENT = ( ('Neuro', 'NEUROLOGY'), ('Dental', 'DENTISTRY'), ('Cardio', 'CARDIOLOGY'), ('Pediatrics', 'PEDIATRICS'), ('Pulmonology', 'PULMONOLOGY'), ('Opthalmology', 'OPTHALMOLOGY') ) dpeartment=models.CharField(max_length=100, choices=DEPARTMENT) username=models.CharField(max_length=100) GENDER = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=10, choices=GENDER) phone=models.CharField(max_length=20,) email=models.EmailField(max_length=50) TIMESLOT_LIST = ( (1, '10:00 – 11:00'), (2, '11:00 – 12:00'), (3, '12:00 – 13:00'), (4, '13:00 – 14:00'), (5, '14:00 – 15:00'), (6, '15:00 – 16:00'), (7, '16:00 – 17:00'), (8, '17:00 … -
Django RelatedObjectDoesNotExist in model clean method but only when testing
I have this very weird behaviour where this function works fine in the application but raises an exception when called in a testing environment. I have this model class with this clean method: def clean(self): self._check_subcategory_consistency() # other checks # ... def _check_subcategory_consistency(self): # checks if the subcategory belongs to the category specified if self.subcategory.category != self.category: raise ValidationError({'subcategory' : 'this field does not belong to the correct category'}) This works fine on the application both when creating a new model instance or when updating one. But then when I test the view with a POST submission, the following error occurs: poi.models.PointOfInterests.subcategory.RelatedObjectDoesNotExist: PointOfInterests has no subcategory. Here is the test: class ViewTest(TestCase): @classmethod def setUpTestData(cls): # fill the DB with all the utility tables (category and subcategory) populate.populate() cls.factory = RequestFactory() cls.user = User.objects.create_user(username='user', password='secret') cls.point = populate.add_default_point() cls.point.save() # some other tests in the middle... def test_new_post(self): request = self.factory.post(reverse('new')) post_dict = model_to_dict(self.point) # avoid name clash with the already created point post_dict['name'] = 'new name' request.POST = post_dict # add mandatory thumbnail with open('static/images/placeholder.jpg', 'rb') as uploaded_image: request.FILES['thumbnail'] = uploaded_image request.FILES['thumbnail'].read() request.user = self.user response = views.new(request) self.assertEqual(response.status_code, 302) self.assertEqual(PointOfInterests.objects.all().count(), 2) PointOfInterests.objects.get(name='new name').delete() And also, here is the … -
Django: 'User' object has no attribute 'cleaned_data'
I'm analyzing a SignUp View for learning purposes. I want to understand if the SignUp View could be improved. It works now, but could it be improved? For example, if I use: username = user.cleaned_data.get('username') Instead of: username = user_form.cleaned_data.get('username') I get this errror: 'User' object has no attribute 'cleaned_data' Why? SignUp View: @transaction.atomic def signupView(request): ### #Some code to generate Deparments List, Province List and District List. ### if request.method == 'POST': print("SIGNUP REQUEST POST: ", request.POST) ##### peru = Peru.objects.all() department_list = set() province_list = set() district_list = set() for p in peru: department_list.add(p.departamento) department_list = list(department_list) if len(department_list): province_list = set( Peru.objects.filter(departamento__in=department_list).values_list("provincia", flat=True)) province_list = list(province_list) else: province_list = set() if len(province_list): district_list = set( Peru.objects.filter(departamento__in=department_list, provincia__in=province_list).values_list( "distrito", flat=True)) else: district_list = set() ##### user_form = SignUpForm(request.POST, request.FILES) profile_form = ProfileForm(district_list, province_list, department_list, request.POST, request.FILES) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.is_active = False user.save() username = user_form.cleaned_data.get('username') signup_user = User.objects.get(username=username) customer_group = Group.objects.get(name='Clientes') customer_group.user_set.add(signup_user) raw_password = user_form.cleaned_data.get('password1') user.refresh_from_db() # This will load the Profile created by the Signal profile_form = ProfileForm(district_list, province_list, department_list, request.POST, request.FILES, instance=user.profile) # Reload the profile form with the profile instance profile_form.full_clean() # Manually clean the form this time. It is … -
How can i save a form without a submit button in django
i have a doubt, i want to save a form and without use a submit button. Because, as you´ll see: i need to increase "cantidad" but i don't want to use a "sumbmit" button, otherwise, i need that the data (integers) will stay correctly in a database field. Because, in my models.py i have: cantidad = models.IntegerField(default=0) I want to modify the field 'cantidad' when the user increase or decrease Selection, as you see in the image and without a submit button. Is there a way to do this? Any help thank you!. -
Id seems to be not existent in django model: that's why no reverse match is found
I have a django model for which I am writing my delete view. I get an django.urls.exceptions.NoReverseMatch error. That is also logical since when I am trying to debug and I want to output my id with {{ model.id }} my view shows me no id at all. When I use the pk it passes in my urls. My model: class UrlTrack(models.Model): url = models.CharField(max_length=255, primary_key=True) counter = models.BigIntegerField(default=0) My view: class AnalyticsDeleteUrls(SingleObjectMixin, View): model = UrlTrack def get(self, request, *args, **kwargs): obj = self.get_object() if obj is not None: obj.delete() return redirect('list_history') My urls: path('history/delete/urls/<int:id>/', AnalyticsDeleteUrls.as_view(), name="history_url"), My template: {% for item in url_tracks %} <tr> <td>{{ item.url }}</td> <td>{{ item.counter }}</td> <td> <a class="btn btn-danger" href="{% url 'history_url' item.id %}"> Delete </a> </tr> {% endfor %} Why would the id be non existent? I though django passes that in automatically....? Any help is highly appreciated. Thanks in advance -
Mezzanine blog custom tag to show highest rated blogs
I'm very new to Mezzanine. I'd like to be able to create a custom blog tag similar to mezzanine.blog.templatetags.blog_tags.blog_recent_posts except it would be mezzanine.blog.templatetags.blog_tags.blog_top_rated_posts which would return the top n rated blog posts. -
Django objects.filter(date...) - template implementation
I've got a function which sends an email with expenses. Everything works fine, but I have no idea how to implement a small part of the code into a template and give for the user an option to choose a period of time. For example: user should choose a year and month from the template. def mail_from_web(request): email = EmailMessage('Your expenses', 'Hello there. Some text', 'email@from', ['email@to']) attachment_csv_file = StringIO() writer = csv.writer(attachment_csv_file, delimiter=',') writer.writerow(['Date', 'Customer', 'Car park']) for call in Call.objects.filter(date__year='2019', date__month='04').order_by('date'): writer.writerow([call.date_start.strftime("%Y-%m-%d"), call.customer, call.expenses]) email.attach('expenses.csv', attachment_csv_file.getvalue(), 'text/csv') email.send(fail_silently=False) return render(request, 'calls/mail_sent.html') Instead of this: objects.filter(date__year='2019', date__month='04') -
How to provide default value in Wagtail Page.title field?
All I need is just randomly generated page title, something among the lines: class MyBasePage(Page): title = models.CharField( default=uuid4, verbose_name=_('title'), max_length=255, help_text=_("The page title as you'd like it to be seen by the public") ) class OtherPage(MyBasePage): pass Currently I'm blocked by the following error: django.core.exceptions.FieldError: Local field 'title' in class 'MyBasePage' clashes with field of the same name from base class 'Page'. Any ideas how to achieve this? -
I am trying to show the output of machine learning on a webpage and i am using django for it, how to get the output on a webpage?
I am accessing the csv file using pandas pd.read_csv but the webpage shows server error 500.I am using django framework but i am unable to understand how to upload a csv file and then apply my machine learning algorithm written in a .py file on that csv to show the output. i expect the output to be the final answer after applying the machine learning algorithm to the csv fle(the prediction value), but getting the output as server error 500 -
how to save many to many field using django custom forms
how can i save many courses to the student table .I want to keep my design like this.This code is not saving the many to many field(courses) through AddStudentForm.It returns an error with courses variable. how can i save many courses to the student table .I want to keep my design like this.This code is not saving the many to many field(courses) through AddStudentForm.It returns an error with courses variable. models.py class Course(models.Model): title = models.CharField(max_length=250) price = models.IntegerField(default=0) duration = models.CharField(max_length=50) def __str__(self): return self.title class Student(models.Model): name = models.CharField(max_length=100) courses = models.ManyToManyField(Course) email = models.EmailField() image = models.ImageField(upload_to='Students',blank=True) def __str__(self): return self.name forms.py class AddStudentForm(forms.ModelForm): # courses = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Course.objects.all()) class Meta: model = Student fields = ['name','courses','email','phone','image'] def __init__(self, *args, **kwargs): super(AddStudentForm, self).__init__(*args, **kwargs) self.fields["courses"].widget = CheckboxSelectMultiple() self.fields["courses"].queryset = Course.objects.all() views.py def addstudent(request): courses = Course.objects.all() if request.method == 'POST': form = AddStudentForm(request.POST,request.FILES) if form.is_valid(): student = form.save(commit=False) course = form.cleaned_data['courses'] student.courses = course student.save() # student.save_m2m() # student.courses.set(course) # this method also didn't helped me messages.success(request, 'student with name {} added.'.format(student.name)) return redirect('students:add_student') else: # messages.error(request,'Error in form.Try again') return HttpResponse(form.errors) # this block is called and returns courses else: form = AddStudentForm() return render(request,'students/add_student.html',{'form':form,'courses':courses}) add_student.html … -
Django pytest test unauthorized access to a view
I'm trying to test a protected view. Unauthenticated user are redirect to login page. When I run the test, it raises django.cose.exceptions.PermissionDenied which is normal but how could I write it without getting a failure and how can I test if the redirection is correct? Here is what I've done. class TestProtectedRegistrationListView: """ Verify registration views are protected from unauthenticated access. """ def test_access_url( self, user: settings.AUTH_USER_MODEL, request_factory: RequestFactory ): view = RegistrationListView.as_view() request = request_factory.get("/admin_staff/registrations") request.user = user resp = view(request) assert resp == PermissionDenied -
Django how to use model DecimalField with additional character values?
I have an input box that must accept the following parameters: Empty Value ('') ZERO (0) Fail value ('x') I know that I can create a custom "fail" BooleanField that gets set to True if "x" is typed. However, I would like to know if it is possible add these values inside the DecimalField. Maybe, use CharField with Decimal Validation. However, trying to use it with CharField and Decimal Validation failed. So, I am not sure how else I can achieve this. Thanks! -
How to incorporate python logic in Django?
Where should the python logics such as sorting a list, printing a Tree be placed in Django. Also, How can we take input and store it in a list in Django?