Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Class Based Views not rendering variables in Template
i'm pretty new to django and already have read a lot about class-based views before coming here. I'm trying to build a one page website, with dynamic blocs that can be written from the django admin. My problem is that i cannot manage to render variables from my database in my template. I'm quite lost. Here's what i wrote: models.py from django.db import models from tinymce.models import HTMLField class MyResume(models.Model): subline = models.CharField(max_length=200) content = HTMLField() class Meta: verbose_name = "My Resume" verbose_name_plural = "My Resume" def __str__(self): return "My Resume" class AboutMe(models.Model): subline = models.CharField(max_length=200) content = HTMLField() cover_img = models.ImageField(upload_to="about_me") class Meta: verbose_name = "About me" verbose_name_plural = "About me" def __str__(self): return "About me" class Experience(models.Model): subline = models.CharField(max_length=200) pres_content = models.TextField() exp_content = HTMLField() date_exp = models.IntegerField() class Meta: verbose_name = "Experience" verbose_name_plural = "Experiences" def __str__(self): return "Experience" class ProjectPost(models.Model): title = models.CharField(max_length=200) technology = models.CharField(max_length=100) subline = models.CharField(max_length=200) content = HTMLField() project_post_cover = models.ImageField(upload_to="projectpost_cover") class Meta: verbose_name = "Project Post" verbose_name_plural = "Project Posts" def __str__(self): return self.title class BlogPost(models.Model): title = models.CharField(max_length=200) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField() blogpost_thumbnail = models.ImageField(upload_to="blogpost_thumbnail") class Meta: verbose_name = "Blog Post" verbose_name_plural = "Blog … -
Reverse for 'api' not found. 'api' is not a valid view function or pattern name with rest-framework
I have a few api with django-rest-framework, my routing is like this below. set /api/genres under /api from rest_framework import routers from django.conf.urls import url from django.conf.urls import include router = routers.DefaultRouter() router.register(r'genres', GenreViewSet) urlpatterns = [ url(r'^api/',include(router.urls), name='api'), path('', views.index, name='index'), Now I want to use this url in template, so I tried two patterns, but both shows error. How should I make the link for api?? <a href="{% url 'api' %}">api</a> Reverse for 'api' not found. 'api' is not a valid view function or pattern name. <a href="{% url 'genres' %}">genre</a> Reverse for 'genres' not found. 'genres' is not a valid view function or pattern name. -
First time using Django, can't access DJango Admin Error 500
I just started learning django. I followed all the instruction on the tutorial 'Writing your first Django app', but when i come to Django Admin part i got an error. When i try to open localhost:8000/admin it gives me Server Error 500 Error Image i don't know whats wrong with my code because it is my first time using Django. Here is my code : setting.py 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/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '0$kj@4&yn)qu$$bmx+w@bn%!ee(r6br-+ks!54z#*gtl#tf8sc' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'django.db.backends.mysql', 'NAME': 'python_db', 'USER': 'root', 'PASSWORD': '', … -
Middleware ContentNotRendered Django issue
I think this might be a Django 3.0 issue, as this script worked in previous Django installations, but I'm getting an error with this middleware. class Middleware(MiddlewareMixin): def process_request(self, request): ... try: view, args, kwargs = resolve(request.path) # for testing print('view(request, *args, **kwargs): %s' % view(request, *args, **kwargs)) return view(request, *args, **kwargs) except: raise Http404 The result of the print is: view(request, *args, **kwargs): <TemplateResponse status_code=200, "text/html; charset=utf-8"> The error is: ContentNotRenderedError at / The response content must be rendered before it can be accessed. Request Method: GET Request URL: https://podcast.kevinrose.com/the-kevin-rose-show/ Django Version: 3.0 Exception Type: ContentNotRenderedError Exception Value: The response content must be rendered before it can be accessed. Exception Location: /app/.heroku/python/lib/python3.7/site-packages/django/template/response.py in content, line 127 Python Executable: /app/.heroku/python/bin/python Python Version: 3.7.6 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python37.zip', '/app/.heroku/python/lib/python3.7', '/app/.heroku/python/lib/python3.7/lib-dynload', '/app/.heroku/python/lib/python3.7/site-packages', '/app/.heroku/src/redwoodlabs', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf', '/app/.heroku/python/lib/python3.7/site-packages/odf'] Server time: Fri, 31 Jan 2020 18:10:22 -0800 A friend helped me with this script, so I'm a bit lost. I'm sure it's something small. -
Django array query param is not giving results
I am trying to get the results from an array as explained here: https://docs.djangoproject.com/en/dev/ref/models/querysets/#in http://127.0.0.1:8000/blogs?years=['2018', '2019'] http://127.0.0.1:8000/blogs?years=[2018, 2019] Turns out ['2018', '2019'] is not what i am getting as years , even though visually they look exactly the same. I even tried using getlist as explained here how to get multiple results using same query params django this does produce the desired results def get_queryset(self): years = self.request.query_params.get('years') return self.queryset.filter(year__in=years) Any clue on what am i doing wrong here? I tried all options it does not work, while i type in the below statement it works perfectly fine def get_queryset(self): return self.queryset.filter(year__in=['2018', '2019']) -
Django Allauth Add Checkbox To Signup That Gets Submitted To The Database
How do you add a checkbox required boolean field to the allauth signup form that does not allow the user to sign up unless the checkbox is checked? I am not sure if I need to edit the actual allauth files themselves or do something within one of my own project's apps (which is what I tried to do below). What I have tried so far: Forms.py: class CaptchaSignupForm(SignupForm, CaptchaRequirement): captcha = CaptchaField() is_age_compliant = forms.BooleanField(required=True,initial=False,label='Are you at least 13 years old?') field_order = ['username', 'email', 'password1', 'password2', 'is_age_compliant', 'captcha',] def __init__(self, *args, **kwargs): super(CaptchaSignupForm, self).__init__(*args, **kwargs) self.fields['captcha'].widget.attrs['class'] = 'form-control mt-2' self.fields['captcha'].widget.attrs['placeholder'] = 'Enter text from the image' self.fields['is_age_compliant'].widget.attrs['class'] = '' self.fields['is_age_compliant'].widget.attrs['type'] = 'checkbox' pass class Meta: model = Profile fields = ('is_age_compliant') def signup(self, request, user): user.profile.is_age_compliant = self.cleaned_data['is_age_compliant'] user.save() return user Models.py: from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) is_age_compliant = models.BooleanField(default=False) I got the checkbox to show up on the signup form but the data for that checkbox does not submit to the database. The profile table does not even show up in admin after makemigrations and migrate. -
I get a weird error while trying to migrate in Django
I am trying to make a todo-app in Django. It was going well until I get the following error: : (admin.E108) The value of 'list_display[2]' refers to 'due_date', which is not a callable, an attribute of 'TodoListAdmin', or an attribute or method on 'todolist.TodoList'. The models file: from django.db import models from django.utils import timezone # Create your models here. class Category(models.Model): #The Category table name that inherits models.Model name = models.CharField(max_length=100)#Like a varchar class Meta: verbose_name = ("Category") verbose_name_plural = ("Categories") def __str__(self): return self.name #name to be shown when called(Whatever tf that means) class TodoList(models.Model): #Todolist able that inherits models.Model title = models.CharField(max_length=250) #This is apparently a varchar content = models.TextField(blank=True) #A text field created = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) #Presents a date. category = models.ForeignKey(Category, on_delete=models.PROTECT, default="general") #A foreignkey. class Meta: ordering = ["-created"] #ordering by the created field. def __str__(self): return self.title #Name to be sown when called. The admin file: from django.contrib import admin from . import models # Register your models here. class TodoListAdmin(admin.ModelAdmin): list_display = ("title", "created", "due_Date") class CategoryAdmin(admin.ModelAdmin): list_display = ("name",) admin.site.register(models.TodoList, TodoListAdmin) admin.site.register(models.Category, CategoryAdmin) The views file: from django.shortcuts import render,redirect from .models import TodoList, Category # Create your views here. def index(request): … -
Django Nested Serializer not serializing the foreign key object
I know that this question has been asked before, but I've tried so many different solutions and just cannot seem to get it to work. All I am attempting to do is display one object within another on an api call. In this simple example, lets say that I have an artist object and a track object. When I serialize the track object, I would like for the artist object that it refers to using a foreign key to be displayed. Here is my models.py: from django.db import models class Artist(models.Model): artist_name = models.CharField(max_length=100) class Track(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE, verbose_name='Artist' ) track_name = models.CharField(max_length=100) and my serializers.py from rest_framework import serializers from . import models class ArtistSerializer(serializers.ModelSerializer): class Meta: model = models.Artist fields = '__all__' class TrackSerializer(serializers.ModelSerializer): artist = ArtistSerializer(read_only=True) class Meta: model = models.Track fields = ('id', 'track_name', 'artist') If anyone could help, it would be greatly appreciated! Thanks -
Django 1.4 How to customize elements inside MultipleChoiceField
I've set the widget on the MultipleChoiceField with: self.fields['field_1'] = forms.MultipleChoiceField( choices=[(c.name, str(c)) for c in customers], widget=forms.CheckboxSelectMultiple() ) This ultimately spits out some html where each choice in choices gets an <input> in a <label> in an <li> in a <ul>. I'd like to set a class on every <li>. I need to remove the bullet point set next to each <li>, change the font size, maybe even style the checkbox. All CSS stuff. How can I do that? Thanks! -
How to properly reconnect via SSH after screen detached
I'm working on a Django project that is hosted in a remote server, and in my work we connect through a computer which has Mobaxterm. The thing is, I'm not at all experienced, and the connection broke (or I broke it, I don't know), and then I wrote screen -r -d which is what I used to use to make the git pull and then the supervisorctl restart just to apply the changes I did on my local project. After the disconnection, it said there were no screens to detach, so after searching online, I managed to get into a screen, and then made my way to the correct path so that I could do python manage.py etc..., and I activated the virtualenv. The thing is, I'm having errors I didn't have, so I don't know if I have to do something else. For example, when I try to do python manage.py showmigrations , I get an error saying: FileNotFoundError: [Errno 2] No such file or directory: '/webapps/project_name/app_name/logs/dialogflow.log' And different errors occur when I do python manage.py makemigrations , python manage.py migrate, etc. What could the last screen I was working on had and not this one? My ex-coworker, who … -
KML file downloaded save to DB in django postgres with framework selenium
I'm doing a project that contains information from a GPS, that when the server is started it downloads all the information with the coordinates of the object to a KML file, but now i can't save it to a DB in postgres on django. I need that when the files are downloaded that they are being saved on the database, on the pointfield oject class Device(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # NOQA (ignore all errors on this line) location = models.PointField(null=True, blank=True) address = models.CharField(max_length=100) city = models.CharField(max_length=50) timezone = TimeZoneField() @property def shortened_id(self): """Get shortened version of id.""" return str(self.id)[-12:] def get_gps_file_download(): CHROMEDRIVER_EXECUTABLE_PATH = '/usr/bin/chromedriver' USERNAME = '' PASSWORD = '' chrome_options = Options() chrome_options.add_argument('--no-sandbox') # chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-dev-shm-usage') prefs = {"download.default_directory" : os.path.join(settings.BASE_DIR, ' ')} chrome_options.add_experimental_option("prefs",prefs) # browser = webdriver.Chrome(options=chrome_options, executable_path=CHROMEDRIVER_EXECUTABLE_PATH) browser = Chrome(chrome_options=chrome_options, executable_path=CHROMEDRIVER_EXECUTABLE_PATH) browser.get(' ') # .until(ec.visibility_of_element_located((By.ID, "txtUserName"))) WebDriverWait(browser, 10) browser.switch_to.frame(0) gps_signin_email_input = browser.find_element_by_id('txtUserName') gps_signin_email_input.send_keys(USERNAME) gps_signin_password_input = browser.find_element_by_id("txtAccountPassword") gps_signin_password_input.send_keys(PASSWORD) gps_signin_button = browser.find_element_by_id("btnLoginAccount") gps_signin_button.click() session_id = '' for cookie in browser.get_cookies(): print(cookie) if cookie['name'] == 'ASP.NET_SessionId': print(cookie['value']) session_id = cookie['value'] break WebDriverWait(browser, 10) response = subprocess.check_output( """curl ... > file1.txt""" % (session_id,), shell=True, ) # print(json.loads(response.decode("utf-8"))) file_list = ['file1.txt'] devices_list = [] for x in range(len(file_list)): with … -
crispy form data not displayed correctly from database
class UserInfoForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( ) super(UserInfoForm, self).__init__(*args, **kwargs) self.fields['score'].widget.attrs['readonly'] = True class Meta: model = UserInfo exclude = ['user','is_vetted','contact','leaderboard','policy','reviewer','reasons','hear'] class UserInfo(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) organization = models.ForeignKey(to=Organization, default=None, null=True, blank=True,on_delete=models.CASCADE) reasons = models.TextField(max_length=2000, blank=True, help_text="Specifies why this user wants to join AGP") hear = models.CharField(max_length=500, blank=True, help_text="Specifies how this user heard about AGP.") score = models.IntegerField(default=0) is_vetted = models.BooleanField(default=False, help_text="Specifies if this user's credentials have been vetted and approved by an AGP admin.") contact = models.BooleanField(default=True, help_text='Specifies if this user is to be included in the contact list for internal contact.') leaderboard = models.BooleanField(default=True, help_text='Specifies if this user is to be included in the leaderboard.') policy = models.BooleanField(default=True, help_text="Specifies if this user has accepted the terms of the AGP user policy.") mail_list = models.BooleanField(default=True, help_text='Specifies if this user is to be included in the monthly email contact list.') reviewer = models.BooleanField(default=False, help_text='Specifies if this user is an artifact reviewer. If True, artifacts will be assigned to them.') def __unicode__(self): return self.user.username SO I have above code, am including in my html page crispy UserInfoFOrm, its all working but the only problem is the way data is displayed. … -
Do I need to sign out a user if they leave my homepage and signed on through their Google account?
I'm developing a login page for my Django application and am using Google login for users to gain access. My question is if they sign on successfully, do I need some way to change the state of their sign on for security purposes? Might be a silly question but I honestly have no idea and want to be sure. -
django returns more objects than it should
My problem is related to getting the one instance of the model. The filtering condition I give is unique and I should receive only one instance. It returns 7 instead (all of them). Model: class Movie_dates(models.Model): #// signals appended - Creates this model straight after new Movie has been added main_movie = models.ForeignKey(Movies, on_delete=models.CASCADE) date = models.DateField(auto_now_add=False) time = models.ManyToManyField(Hours) This model is being created automatically (x7) after creating the main model. Date field is incremented datetime.now() + timedelta.days(i) And my views: if request.session.get("user_choice"): user_choice = request.session.pop("user_choice") movie_date = user_choice["date"] movie_hour = user_choice["hour"] movie = Movies.objects.get(pk=pk) dates = Movie_dates.objects.get(main_movie=movie, date=datetime.strptime(str(movie_date), "%Y-%M-%d").date()) The user_choice content is visible in my views and for sure it's been converted to date format. I still receive all of the objects instead of the only one with particular date provided. Appreciate for help. -
Download Bootstrap From Command-line on Windows 10
On Windows 10, if I have a directory named "static", is there an easy way to download the latest version of Bootstrap (whatever version it is at the time) and jQuery into to "static" directory from a command line? I'm looking into how to do this with cURL or wget but I'm not familiar enough with those yet to know. I'm asking in the context as a aspiring Django developer. Would save a lot of time to quickly download these frameworks as-needed. -
Django Allauth Sign Up Prevent User From Creating Account Unless They Are 13 or Older
I need help modifying the allauth sign up page and the associated admin.py, models.py, and forms.py to ask a user if they are 13 or older to comply with COPPA law. I do not want any user to sign up for my site unless they select "yes i am 13 or older" either in a dropdown menu or a checkbox. If no is selected, a validation error pops up saying "parent permission required". I at least want to store their response in my database to protect myself from COPPA. I realize that anybody could just lie about their age but I would at least have a track record of them saying that they lied about their age in my database. I do not want to store their age or their birthdate in my database since it is PII. I want to display in the database their username and a yes or no response to the question if they are 13 or older. Using the latest version of allauth. I didn't change anything because I don't want to mess anything up. All I did was copy the allauth files to my project so everything can be edited. -
Django model inherit from one of several models
I am new in Django an have trouble figuring out the right way of making model inheritance. Let assume that I am making some kind of food app. I would then have a model for meet, a model for fruit, a model for vegetables and so on. My question is: How can I make a nutrition content model, which can inherit from all of the above models but only from one at a time? For instance nutrition content of apple should only inherit from the fruit model. If there was only one food model type I would use ForeignKey to handle the inheritance. I guess this is not an option when there are several options for models to inherit from. I would like to use on_delete=models.CASCADE for the nutrition content model. Hence the request for inheritance. Any suggestions will be appreciated. -
How to split a List of Dictionary into 2 seperates list of dictionaries with equality check
I am currently working on a Website which will detect the user games and the time. In my webapplication the user can set the games as finished (played). I successfully created a list of dictionary and the one game which got played to the end. I think a bit of Code illustration would help. That is my code which should generate two seperate list of dictionaries. played_games_entries does actually work. I try it with an else but it doesn't work as I intendet. I know the problem but it is hard to explain and I dont now what my approach should be. If I am honest I am a bit confused because the if statement works and the else statement not. def get_name_and_due(request, played_games, games_list): open_games_entries = [] played_games_entries = [] for game in games_list: for played_game in played_games: due_perc = convert_due_into_percentage(game['due'], request.session.get('max_due')) if game['game_name'] == played_game['played_game_name']: played_games_entries.append({'name': game['game_name'], 'due': due_perc}) break else: pass Here are my values for the parameters played_games and game_list. games_list = [ {'index': '1', 'game_name': 'Temtem', 'due': '00:30:04'}, {'index': '2', 'game_name': 'The Forest', 'due': '10:00:30'}, {'index': '3', 'game_name': 'The Witcher 3: Wild Hunt', 'due': '50:15:25'}, {'index': '4', 'game_name': 'STAR WARS Jedi: Fallen Order', 'due': '18:15:00'} … -
Django: check if user liked post and corresponding comments in template
In user profile page I am displaying posts and comments of the persons that the user is following. I want to check and display like symbol for the posts and comments liked by user. What is the best way to test if user liked post and comment in the template? Post model: class Post(models.Model): author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,) title = models.CharField(max_length=200,null=True) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) slug = models.SlugField(unique=True, blank=True) nLikes = models.IntegerField(default= 0) Comment model: class Comment(models.Model): post = models.ForeignKey('Post', related_name='comments',on_delete=models.CASCADE,) author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) slug = models.SlugField(unique=True, default=uuid.uuid4) nLikes = models.IntegerField(default= 0) Post like model: class PostLike(models.Model): post = models.ForeignKey('Post', related_name='related_post',on_delete=models.CASCADE,) user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,) liked_date = models.DateTimeField(default=timezone.now) comment like model: class CommentLike(models.Model): comment = models.ForeignKey('Comment', related_name='related_comment',on_delete=models.CASCADE,) user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,) liked_date = models.DateTimeField(default=timezone.now) my template will be similar to this. I am adding simplified version here just to make things easy {% for post in post_queryset %} <div> {{ post.text }} </div> {% for comment in post.comments.all %} </div> {{ comment.text }} </div> {% endfor %} {% endfor %} What is the best way to check if the post and comment liked by the user? I am thinking of using … -
Delete blog post older than 30 days Automatically
I want to Automatically delete blog post that are older than 30 days in my Django project. I don't know how to go about it. -
Extending user profile update problem in django-rest nested serializer
In Django admin interface data updated well but when attempt to update some info in postman. This shows the error "django.contrib.auth.models.User.profile.RelatedObjectDoesNotExist: User has no profile." I am following django rest documentation https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers but what`s wrong with my code my serializers.py from django.contrib.auth.models import User from rest_framework import serializers from accounts.models import Profile, Address, Contact, Religious, Contact, Gender from rest_framework.response import Response class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = [ "village", "postoffice", "postcode", "upazila", "district", "city", "state", "country", ] class ReligiousSerializer(serializers.ModelSerializer): class Meta: model = Religious fields = ["religious"] class GenderSerializer(serializers.ModelSerializer): class Meta: model = Gender fields = ["gender"] class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = [ "phone", "social_link", ] class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = [ "birth_date", ] class AccountSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=False, allow_null=True) address = AddressSerializer(required=False, allow_null=True) gender = GenderSerializer(required=False, allow_null=True) religious = ReligiousSerializer(required=False, allow_null=True) contact = ContactSerializer(required=False, allow_null=True) class Meta: model = User fields = [ "id", "username", "email", "password", "first_name", "last_name", "profile", "address", "gender", "religious", "contact", ] extra_kwargs = { "username": {"required": True}, "email": {"required": True}, "password": {"required": True}, } read_only_fields = ("username", "email") # write_only_fields = ("password",) # username no updatable def update(self, instance, validated_data): profile_data = validated_data.pop("profile") address_data … -
Problem getting Django, CodePipeline and https working
I have been trying to add https to a website. Firstly, I followed these instructions: https://aws.amazon.com/premiumsupport/knowledge-center/elastic-beanstalk-https-configuration/ To make it clear, I have an application load balancer not a classic load balancer. I copied the following files into the .ebextensions folder, created certificates in certificate manager and made adjustments to route52 and the load balancer section of elastic beanstalk so that it listens to https requests on port 443. As far as I can tell everything works because when I change the url from http://.... to https://... the website works and the browser shows the lock. I have included a copy of the list of files that I have included in .ebextensions: https-backendsecurity.config: # See the following on setting up https on eb: # https://aws.amazon.com/premiumsupport/knowledge-center/elastic-beanstalk-https-configuration/ # Resources: # Add 443-inbound to instance security group (AWSEBSecurityGroup) httpsFromLoadBalancerSG: Type: AWS::EC2::SecurityGroupIngress Properties: GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]} IpProtocol: tcp ToPort: 443 FromPort: 443 SourceSecurityGroupId: {"Fn::GetAtt" : ["loadbalancersg", "GroupId"]} # Add 443-outbound to load balancer security group (loadbalancersg) httpsToBackendInstances: Type: AWS::EC2::SecurityGroupEgress Properties: GroupId: {"Fn::GetAtt" : ["loadbalancersg", "GroupId"]} IpProtocol: tcp ToPort: 443 FromPort: 443 DestinationSecurityGroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]} https-lbsecuritygroup.config # See the following on setting up https on eb: # https://aws.amazon.com/premiumsupport/knowledge-center/elastic-beanstalk-https-configuration/ # option_settings: # Use … -
File upload from Angular to Django with FromControll
I setup an angular form that send some data by using Form Control to Django, then in view, just data received from request and store to database. The field processing is dynamic and I don't set the value of form data to related field on Django model. The issue is with file handling, that not working 1- I try with simple creation the file input and then send file input data like other but it is not okay, and doesn't work. 2- I follow this video https://www.youtube.com/watch?v=-36YauTh4Ts, but it works with form data that has diffrent structor than FormControl, and make me force to do some hard assigning coding. const data = new FormData(); data.append('title', this.title); data.append('cover', this.cover, this.cover.name); 3- I try with ngx-mat-file-input, and a related guide here , but this is also used FormData. Question is, How sending file data from angular form to Django server using FormControl (ReactiveForm)? Here is my codes component form #documentEditForm="ngForm" (ngSubmit)="CreateCompany()"> <mat-form-field> <ngx-mat-file-input formControlName="com_logo" placeholder="Logo"></ngx-mat-file-input> <mat-icon matSuffix>folder</mat-icon> </mat-form-field> </form> companyForm = new FormGroup({ com_logo: new FormControl(), }); and the django create function def create(self, request): company = CompanyForm(request.data, request.FILES) if company.is_valid(): company = company.save() serializer = CompanySerializer(company) return JsonResponse(serializer.data, safe=False) else: return … -
How to have dynamic or variable number of inputs in Django form
I have a teacher portal where teachers can create tests having multiple choice questions and a correct answer. Now, on the student portal, students can take the test and submit it like a form and get the score. But since each test would have variable number of questions, How do I create a django form of variable to get the student's input(radio buttons) for each question? I tried storing the number of questions in the test model( I have a 'test' model and a 'questions' model which references to 'test' using foreign key). But if this is the right approach, How do I create a for loop in views.py to receive each input and also how would I write a for loop in the template to create a form of variable length and how would I give a different name to each input(radio) of the form in for loop? -
How to stop Graphql + Django-Filters to return All Objects when Filter String is Empty?
Using: Django 3.x [ Django-Filters 2.2.0, graphene-django 2.8.0, graphql-relay 2.0.1 ] Vue 2.x [ Vue-Apollo ] I have a simple Birds Django-Model with Fields like name, habitat and applied different Filters on these Fields like icontains or iexact. My Goal was to apply a simple search field in my Frontend (Vue). So far it works, but whenever this Filter Value is empty or has blanks (see Example 3), Graphql returns all Objects. My first approach was on the FrontEnd and to use some kind of logic on my input value, like when String is Empty/blank send isnull=true . But then i thought that Django should handle this in the first place. I guess this Issue relates to my filters (see Django < relay_schema.py) or in other words do i have to apply some kind of logic on these Filters? In the moment i try to customize some filterset_class but it feels like this would maybe too much, maybe i missed something? So i ask here if maybe someone has some hints, therefore my question is: How to stop Graphql + Django-Filters to return All Objects when Filter String is Empty? GraphiQL IDE Example 1 query {birdsNodeFilter (name_Iexact: "finch") { edges …