Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image getting saved twice in media folder django Imagefiled PIL
I am trying to resize the image in form's save method that extends modelform. I open the image and resize it then saves it using PIL in the save method of form. But in the media folder that has all the save images it saves two images one that is resized and other that was original. I guess that must be because of the form's save getting called after PIL's save has been called. Is there a way to save only the resized image. def save(self): mymodel = super().save(commit=False) checkpath = mymodel.picture1 image = Image.open(checkpath) image = image.resize((33,33), Image.ANTIALIAS) image.save(checkpath.path) mymodel.save() It saves two images in media folder first is a.jpg that is the orignal name of the image and other is akjdsfj.jpg random name. The second must have been formed when model's save got called. Is there a way to stop this behaviour and save only one image that is resized. -
Django run external py script on html click
since im beginner to Django framework and python language. I need help. I need to run external python script from html button also to get value from html and show the output back to web page. Example workflow: Input text : "hello", click "submit" on html button. Run world.py : receive "hello" as variable. Add "world" Post it back to the same html page and shows "helloworld" . -
Django dynamic forms - How to setup dynamic forms click event
Basically, I am rendering a template and passing a python dictionary to the template that contain some image urls obtained from the model. My task is to when user clicks on any image. It submits that image url back to views.py file without refreshing the page and then it calls an api in view which generates a grey scale image which is passed as JsonResponse in django template. And then I show it by using document.getElementById('classified_image'). My problem is how do I setup the id of form/list and how to make a single click event to handle them view.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.http import HttpResponse, JsonResponse from django.views.generic import View from example import function_used_in_app, open_image from classifier.models import UserImage import json class HomeView(View): def get(self, request): template_data = { 'images': UserImage.objects.all(), 'ids': UserImage } ids = Counter() return render(request, 'classifier/base.html', template_data) def post(self, request): if request.FILES.get('uploaded_image'): image = request.FILES["uploaded_image"] UserImage.objects.create(image=image).save() original_image = UserImage.objects.all().last().image.url else: original_image = request.POST['selected_image'] function_used_in_app(open_image(original_image[1:]), 0.4, 0.5, 0.6, 0.1, 0.2) classified_image = '/media/classified_images/example_gray.png' print(original_image) print(classified_image) return JsonResponse({'error': False, 'message': 'Uploaded Successfully', 'original_image': original_image ,'classified_image': classified_image}) base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta … -
How can I block calls from unknown domains/IP to my REST API?
I want to block calls to my Django REST API (www.backend_django.com) from unknown origins, for example, I have a website under the domain "www.example.com" I want to allow only to this site to be able to do request to my API. In order to do this, I have configured Django-Cors-Headers in the following way: DEBUG = False ALLOWED_HOSTS = ["www.backend_django.com", "backend_django.com"] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'https://backend_django.com', 'https://www.backend_django.com', 'https://example.com', 'https://www.example.com', ) CSRF_TRUSTED_ORIGINS = [ 'backend_django.com', 'example.com'] In order to test it, I have done a call from Postman using my computer and have successfully done a request still to the API. Did I set up something bad in the settings? How can I archive this? -
Github Oauth Web Flow CORS
I have a project that consist of a Django rest server back-end and a vue js front end. I am trying to authenticate with GitHub using their oauth2 web flow. So far I seem to get blocked by CORS or Github returns not found. I have tried a different couple approaches but so far have had the best results with the following: In my front end I authenticate with GitHub which returns an temporary code. I then post the code to my back-end which then makes a request to get an access token from GitHub which returns a CORS error. I am assuming this is because the front-end and back-end servers are on different domains which is causing problems. The interesting thing to me is if I copy the code and then make the call in postman it works fine and returns the access code. Why does it work in postman which isnt on the same domain and what I am doing wrong? Some points that maybe of interest: I have Django CORS installed my GitHub callback points to my front-end I tried making all the calls from the front end but still get blocked by CORS The CORS error … -
Click on username and get redirected to the profile
I'm writing an application and I want to be able to click on the username and go to the profile of the user. I have searched a lot around and didn't find anything that I wanted. I have something like this: I want that when I press on Admin, I will be redirected to the profile with all the information that is saved through the Model that I created. class Farmer(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=50) age = models.IntegerField() province = models.CharField(max_length=100) company_name = models.CharField(max_length=30) phone_number = PhoneNumberField(null=False, blank=False, unique=True) products = models.CharField(max_length=200) def __str__(self): return self.name.username How can I achieve something like this? I thought that I need to write a function inside my views.py but I'm stuck and don't know how to go further. def profile(request): # something here.. return render(request, 'home_page/profile.html') -
Automate Elasticsearch index creation on django app startup
I want to automatically check and create (if not existing) the elasticsearch index of my app on startup, this is my current situation which is not working: echo "Checking if Elasticsearch index is setup" { cat <<EOF | python /manage.py shell from elasticsearch import Elasticsearch HOST_URLS = ["elasticsearch:9200"] es_conn = Elasticsearch(HOST_URLS) INDEX_NAME = "posts" res = es_conn.indices.exists(index=INDEX_NAME) if res == True: print("Elasicsearch index seems already setup, skipping") else: print("Elasicsearch index not setup yet, creating ...") import subprocess subprocess.Popen("y | python manage.py search_index --rebuild", shell=True, stdout=subprocess.PIPE).communicate()[ 0].decode('utf-8').strip() EOF }>/dev/null which again results in: "the '{}' indexes? [n/Y]: ".format(", ".join(index_names))) | EOFError: EOF when reading a line python manage.py search_index --rebuild comes from: https://github.com/sabricot/django-elasticsearch-dsl/ -
Django migrate value invalid literal
I have problem with Django migrate function. I was trying to add new field to my user model and it looks like this. class UserProfile(models.Model): """ Model to represent additional information about user """ user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='profile' ) bio = models.TextField( max_length=2000, blank=True, default='' ) # we use URL instead of imagefield because we'll use 3rd party img hosting later on avatar = models.URLField(default='', blank=True) status = models.CharField(max_length=16, default='', blank=True) name = models.CharField(max_length=32, default='') balance = models.BigIntegerField(default='0') def __str__(self): return self.user.username balance is new what I added, and after that I'm receving messages like Operations to perform: Apply all migrations: accounts, admin, auth, authtoken, contenttypes, forums, posts, sessions, threads Running migrations: Applying accounts.0005_userprofile_balance...Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Rade\Desktop\rengorum-master\backend\env\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) … -
problem writing/understanding Django Custom managers
I have problems with Django's custom managers. It may be simple but I did not understand the managers very well. here is my code : class Season(models.Model): id = models.AutoField(auto_created=True, primary_key=True) sku = models.CharField(max_length=16, default=secrets.token_urlsafe(8), editable=False) title = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=64, unique=True) tutorial = models.ForeignKey(Tutorial, on_delete=models.DO_NOTHING) created = models.DateTimeField(auto_now_add=True) objects = models.Manager() # Default Manager custom_obj = SeasonManager() # Custom Manager in (managers.py) def __str__(self): return self.title class Lesson(models.Model): id = models.AutoField(auto_created=True, primary_key=True) sku = models.CharField(max_length=16, default=secrets.token_urlsafe(8), editable=False) title = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=64, unique=True) content = models.TextField() season = models.ForeignKey(Season, on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Video(models.Model): id = models.AutoField(auto_created=True, primary_key=True) sku = models.CharField(max_length=16, default=secrets.token_urlsafe(8), editable=False) title = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=64, unique=True) content = models.TextField() view = models.PositiveIntegerField(default=0) lesson = models.ForeignKey(Lesson, on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) video_file = models.FileField(upload_to='tutorialApp/videos') video_length = models.CharField(max_length=32) def __str__(self): return self.title The structure is like this: every season has some lessons, each lesson has some videos and each video has a length. I want to write a manager that shows the sum of video lengths in a season. ( a manager that shows how many minutes of videos there are in a season … -
Is there documentation for class option for Django fieldset?
In the Django admin docs, it mentions fieldsets. The example they specify a class collapse. This class will make the fieldset collapsible in the admin page. I found 2 other examples of a classes one could use. I found looking for a list of other classes I can use is wide or extrapretty. Other than these examples I have not been able to find anything else about the class option in the fieldset. -
How to get the price, duration of the twilio call?
I am trying to implement my programmable voice using TwiML, and I am unable to get the JSON API response, as shown in the tutorial. # views.py def start_campaign(request, campaign_id): try: campaign = Campaign.objects.get(pk=campaign_id) account_sid = 'XXXX' auth_token = 'XXXX' client = Client(account_sid, auth_token) phone_numbers = Contact.objects.filter(phone_book=campaign.phone_book) custom_url = 'http://XXXX.ngrok.io/assets/' + str(campaign_id) for phone_number in phone_numbers: call = client.calls.create( method='GET', url=str(custom_url), to=str(phone_number), from_='+12563804721' ) # I don't want to print it I just wanted to see if this works print("Call Status: {}\nCall Duration:{}\nCall Cost:{}".format(call.status, call.duration, call.price)) except Campaign.DoesNotExist: raise Http404("Campaign Does Not Exist") context = { 'campaign': campaign } return render(request, "CallCenter/start_campaign.html", context) def view_assets(request, campaign_id): try: campaign = Campaign.objects.get(pk=campaign_id) except Campaign.DoesNotExist: raise Http404("Campaign Does Not Exist") context = { 'campaign_text': campaign.campaign_text } return render(request, "CallCenter/create_xml.xml", context, content_type='application/xml') # urls.py urlpatterns = [ path('', index, name="index"), path('view-campaigns', view_campaigns, name='view-campaigns'), path('detail-campaign/<int:campaign_id>', detail_view_campaign, name='detail-campaign-view'), path('start-campaign/<int:campaign_id>', start_campaign, name='start-campaign'), path('assets/<int:campaign_id>', view_assets) ] I want a JSON response, as shown in the docs, but I am unable to figure out how to approach it. The output comes as Call Status: queued Call Duration: None Call Cost: None The output shown above comes right after the call is initiated and after I disconnect the call I … -
Django using default db for unit tests instead of test db
When I run manage.py test django is using my default database instead of a test one. Am I misunderstanding something from the docs? According to the docs, the default behaviour is that, "separate, blank databases are created for the tests". I set the "TEST: NAME" value just to make sure, but the docs state that's only needed if I want to configure the test database name instead of the default test_{dbname} DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "HOST": "0.0.0.0", "NAME": "mydb_db", "USER": "postgres", "PASSWORD": "postgres", "PORT": 5432, "TEST": {"NAME": "test_mydb_db"}, } } class SimpleTest(unittest.TestCase): def test_get_user_authorized(self): client = Client() breakpoint() >>> (Pdb) from django.db import connection >>> (Pdb) connection.settings_dict['NAME'] 'mydb_db' If I read or create data in the unit test, data is from mydb_db and not test_mydb_db as I expected. Additional Notes Database is being setup using docker compose. Not sure if that affects anything: services: db: container_name: postgres image: postgres:9.6 restart: always volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "5432:5432" environment: POSTGRES_DB: mydb_db POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres PGPASSWORD: postgres -
how to filter two foreign keys in django
int() argument must be a string, a bytes-like object or a number, not 'ForwardManyToOneDescriptor' class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,blank=True,null=True) Remarks = models.TextField(max_length=500,null=True,blank=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE,null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,blank=True) Courses= models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,null=True,blank=True) Sections= models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE,null=True) Subjects= models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE,null=True) Employee_Users= models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,null=True) Start_Date = models.DateField(null=True,blank=True) End_Date = models.DateField(null=True,blank=True) Remarks = models.TextField(max_length=500) def __str__(self): suser = '{0.Employee_Users}' return suser.format(self) can you guys help me on how to filter the StudentsEnrollmentRecord(Education_Levels) to SubjectSectionTeacher(Education_Levels) because it is really hard to understand the django-filter, i waste already 2 days for this error. -
Prepop fields with values when another field is checked in Django
In my Django database I have the following: skipUserPII = models.BooleanField(default=False) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) address1 = models.CharField(max_length=100) Sometimes, I will create a user manually. In that case, I won't want to fill in their PII every time. So I have created a new variable "skipUserPII" that if checked fills in all PII values with "na" (as compared to having to manually fill in all my PII fields with some default value, allowing me to save the form in Django admin). I'm trying to accomplish this by using the following code below, however it is giving me a "Please correct the errors below" error. def clean(self): if self.skipUserPII == True: def checkNone(field, value): if field == None: field = value checkNone(self.first_name, 'NA') checkNone(self.last_name, 'NA') checkNone(self.address1, 'NA') I've tried putting this in clean and in save -- neither work. Is there another place this code should go? -
heroku works locally but not in server shows "ERROR: connecting to localhost:5037"
In my project Iam referring to "pure python ADB client" which is working fine locally. But after deployment when I try to run the application using "Heroku open" it shows ERROR: Connecting to localhost:5037 [Errno 111] Connection refused. Is adb running on your computer? I tried with 127.0.0.1 but still, it shows error. def getConnected_devices(request): """Connect the devices via usb or WIFI through adb and get the device details dynamically and update the status of device""" client = AdbClient(host="localhost", port=5037) devices = client.devices() usb connected device should be recognized properly in the heroku cloud. -
Django - Getting specific data from model
I'm trying to make a booking system (for apartments). The idea is that users can pick a start date and an end date and book the apartment if it isnt alrdy booked. I have a Reservation model with a "start_date" and a "end_date" that I use to determine the dates for the apartment booking. Users the JQuery Ui Date Picker (a small calendar) to pick dates. The "unavailable" dates are grayed out. This is how I did that : <script type="text/javascript"> var unavailableDates = ['{{ reservation.all.0.start_date|date:"d-m-Y" }}', '{{ reservation.all.0.end_date|date:"d-m-Y" }}']; console.log(unavailableDates); function unavailable(date) { dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear(); if ($.inArray(dmy, unavailableDates) == -1) { return [true, ""]; } else { return [false, "", "Unavailable"]; } } $(function () { $("#datepicker").datepicker({ dateFormat: 'MM-dd-yy', beforeShowDay: unavailable }); }); </script> I am using ... {{ reservation.all.0.start_date|date:"d-m-Y" }} ...to gray out the date in the calendar. My reservation model looks like this: class Reservation(models.Model): apartment = models.ForeignKey(Apartment, related_name='reservations', on_delete=models.CASCADE, blank=True, null=True) start_date = models.DateField(blank=True, null=True, unique=True) end_date = models.DateField(blank=True, null=True, unique=True) name = models.CharField(default="", max_length=200, unique=True) def __str__(self): return self.name And in my view I have: reservation = Reservation.objects.filter(apartment__pk=apartment_id) apartment = get_object_or_404(Apartment, pk=apartment_id) Since I … -
How to create and update model with multiple "ManyToMany" and "through" relations?
Im creating a Rest API for my mobile app in django-rest-framework. My app is similar to MyFitnessPal, so my users have their own food history, where are their meals and each meal have list of food products. For now when I register user I'm creating a new, empty FoodHistory for him. So as next I want to add option to add/update those meals. When user wants to add food products to "Breakfast" with date 10-10.2019 I want to check if meal "Breakfast" with that date already exist in user's history. If not, create it (and set "meal_date" parameter to date from request), if yes, take Food product form DB using it's ID (it's already created) and add it to user's history with "food_weight" parameter. I dont know how to do it when I have multiple ManyToMany and through relations. I know that I have to override "create" and "update" methods in serializers.py and "post" method in my "api.py" but now Im even not sure which serializer should be in my APIView (api.py) class as "serializer_class". models.py class Food(models.Model): name = models.CharField(max_length=255) brand = models.CharField(max_length=255, default="") energy_value = models.DecimalField(max_digits=6, decimal_places=3) fats = models.DecimalField(max_digits=6, decimal_places=3) saturated_fats = models.DecimalField( max_digits=6, decimal_places=3, default=0) carbohydrates … -
AttributeError: module 'django.db.models' has no attribute 'TextFeild'
I was using it with 2.0.7 django , then i tried with 2.2.6 also, this seems to persist. from django.db import models # Create your models here. class Product(models.Model): title=models.TextFeild() description=models.TextFeild() price=models.TextFeild() -
Django-allauth - form with additional registration fields
I'm using django-allauth to authenticate the user. The configuration of my project looks something like this: INSTALLED_APPS = [ [...] 'authentication', 'django.contrib.sites', # 3rd party 'allauth', 'allauth.account', 'allauth.socialaccount', ] #<======================================================DJANGO ALLAUTH=================================================> AUTH_USER_MODEL = 'authentication.CustomUser' # emaillogin_project/settings.py EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` "django.contrib.auth.backends.ModelBackend", # `allauth` specific authentication methods, such as login by e-mail "allauth.account.auth_backends.AuthenticationBackend", ) SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_SESSION_REMEMBER = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True # ocpjonalnie emaillogin_project/settings.py LOGIN_REDIRECT_URL = 'seller:home' #redirect ACCOUNT_LOGOUT_REDIRECT_URL = 'seller:home' #rediect #login form ACCOUNT_FORMS = {'signup': 'authentication.forms.SimpleSignupForm'} My custom user model: from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): age = models.CharField(max_length=20, blank=True, null=True) def __str__(self): return self.email template.html (I use standard fields for crispy field as in the example) [...] {{ form.email|as_crispy_field }} [...] And my forms.py file for which I have questions (I don't understand how it works). 1.) The form in this configuration creates the user and writes the first name (in object), saving the age does not work. Why? class SimpleSignupForm(SignupForm): age = forms.CharField(max_length=30, label='First Name') first_name = forms.CharField(max_length=30, label='First Name') def __init__(self, *args, **kwargs): super(SimpleSignupForm, … -
build login using Django and Angular error credential not provided
i'm try to build a basic login app using Django backend and Angular like fronted, when i use the login component and write the correct credential username and password in the form, then redirect to another component sendme this error, Important: the login giveme the token but then after the login and redirect to another component ,error error Authentication credentials login form with correct credentials username passowrd settings .py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAdminUser', ), 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ], 'NON_FIELD_ERRORS_KEY': 'global', } url .py path('auth/login/', obtain_jwt_token), path('auth/refresh-token/', refresh_jwt_token), login component.ts and .html constructor( private authService: AuthService, private router: Router, ) { } login(username: string, password: string) { this.authService.login(username, password).subscribe( success => this.router.navigate(['categorias']), error => alert('Error al Conectar Datos ') ); } <input class="form-control form-control-sm" #username type='text' placeholder='username'> <input class="form-control form-control-sm" #password type='password' placeholder='password'> <button class="btn btn-primary" (click)="login(username.value, password.value)">login</button> -
How to fix SystemCheck Error in Django 2.2.5
I'm setting a simple Python web app. The example comes from https://www.codementor.io/rogargon/simple-django-web-application-tutorial-du107rmn4. Why is the code breaking? I tried adding the following code: from django.contrib.contenttypes.fields import GenericForeignKey && from django.contrib.contenttypes.models import ContentType class Review(models.Model): RATING_CHOICES = ((1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')) rating = models.PositiveSmallIntegerField('Rating (stars)', blank=False, default=3, choices=RATING_CHOICES) comment = models.TextField(blank=True, null=True) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) date = models.DateField(default=date.today) class Meta: abstract = True class ShopReview(Review): restaurant = models.ForeignKey(ShopInfo, on_delete=models.CASCADE) class Article(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) title = models.CharField(max_length=55) # ... def __str__(self): return self.title -
Django Simplified EAV Implementation, similar to Google Form
I am trying to implement a project, similar to Google forms. We have multiple ActivityType (analogous to a Google form). For example, home verification is an ActivityType. Each ActivityType can have multiple question. Like "What is the home address?", "How many neighbours?". Each question can have a different type, like TextField, ChoiceField etc. Each ActivityType can have multiple submissions. Each submission can have answers to some or all questions in the activity. How do I implement it most logically and succinctly? My Approach (and Questions) Using Django admin, several ActivityType can be defined. Each ActivityType contains several questions using StackedInline. Questions are stored as a json array in the ActivityType model itself. How do I show model's JSON array into a StackedInline? The Response model contains submissions. It just contains a ForeignKey to ActivityType. Response form should be rendered, conforming to the structure defined by question JSON array. How to use a custom form for this? My code models.py class ActivityType(models.Model): activity_name = models.CharField(max_length=200) questions_json = JSONField() class ActivityAnswers(models.Model): activity_event = models.ForeignKey("ActivityEvent", on_delete=models.SET_NULL) user = models.ForeignKey(User, on_delete=models.SET_NULL) answers = JSONField() forms.py class ActivityTypeQuestionForm(forms.ModelForm): Q_TYPES = ( ('multiple_choice', 'Multiple Choice'), ('text_field', 'Text Field'), ('integer_field', 'Integer Field'), ) question_name = forms.CharField(max_length=200) question_type … -
Django / Bootstrap Error: Parameter "form" should contain a valid Django Form
I have a Django app called 'Accounts' that extends the Django default User model. I want each user to be able to update their account, which is a model called UserProfile using the generic.UpdateView. I get the following error when I go to the UpdateView URL: BootstrapError at /accounts/user-profile/5/edit/ Parameter "form" should contain a valid Django Form. I've included my code below. Thank you! models.py from django.db import models from django.contrib import auth # Create your models here. class User(auth.models.User,auth.models.PermissionsMixin): readonly_fields = ('id','pk') def __str__(self): return self.username class UserProfile(models.Model): user = models.OneToOneField(auth.models.User,on_delete=models.CASCADE) join_date = models.DateTimeField(auto_now=True) profile_pic = models.ImageField(upload_to='profile_pics',default='media/block-m.png') skills = models.TextField() major = models.CharField(max_length=128) grad_year = models.CharField(max_length=4) clubs = models.TextField() #make FK to Clubs opt_in = models.BooleanField(default=True) def __str__(self): return self.user.username forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import UserProfile from django import forms class UserCreateForm(UserCreationForm): class Meta: model = get_user_model() fields = ('first_name','last_name','username','email','password1','password2') def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) # self.fields['username'].label = 'Username' # self.fields['email'].label = 'Email Address' # self.fields['password1'].label = 'Password' # self.fields['password2'].label = 'Confirm Password' class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('profile_pic','grad_year','opt_in') views.py from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth.mixins import( LoginRequiredMixin, PermissionRequiredMixin ) from django.urls … -
Django CharField TypeError: __init__() got an unexpected keyword argument 'empty_value'
The Django suggest that I can set the empty_value for a CharField: https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.CharField.empty_value I'm trying to change my field from: my_field = models.CharField(max_length=80, blank=True) to: my_field = models.CharField(max_length=80, blank=True, null=True, empty_value=None) I'm getting this error when I try to create the migration: File "/Virtualenv/python3.7/site-packages/django/db/models/fields/init.py", line 1039, in init super().init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'empty_value' The reason is because I want to set a unique_together on the model that includes my_field and other fields, with the following behavior: If my_field is NULL, I want the unique_together clause to always allow other combinations because NULL != NULL in SQL. If my_field is not NULL, I want the unique_together clause to check for uniqueness against the other field(s). I do not want validation that is not database validation like a clean or validate_my_field method or similar. -
How to deploy django project on Centos 7?
https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-centos-7 I followed the tutorial above to deploy my django project on my CentOs 7 VPS. But at the end when I enter my web site I encounter default Apache welcom page. Is there something missing in this tutorial ?