Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Login/Authenticate user by clicking email link?
Hey Everyone I am working on creating a custom EmployeeForm in which the form is for Business Administrators, to add employees. This creates a new user Account in the database. In order to give this employee access to the platform, a temporary unique password is also set for them. On creation, an email is sent to the new employees account email providing them with their email, and randomly generated password. I would like to also include a link to send them straight to the Change password view. With the click of this link, I want it to login the user, so that they don't have to go to the login page themselves, so that they are already authenticated/logged in, and all they have to do is type in their new password. I'm wondering if it is possible to log this user in automatically with the click of the "change password" link? I am also wondering if there is even a possible way to not even set a random password, and allow the user to just click the email link, and they are free to set their initial password themselves. (Note: password is not a required field, so the employee account … -
Is there a standard/commonly-used decision table library for python?
So here's the problem I'm having, and I'm sure it's a common one. I have a pre_save trigger set up for a model such that before a model instance is saved to the database, a series of checks and modifications are made to it depending on the characteristics of some of its fields, some aggregate values calculated with respect to other instances of the model and other models, and some threshold constants for the model. What I have right now works, but it is an ungodly mess of if-else statements that is completely unmaintainable. Obviously a decision table is required, but I can't seem to find anything besides the odd github project with only a few stars. Because of this I've made my own decision table class that seems to work on its own (yet to integrate into my project), but I'd much rather use something that has been widely tried and tested if it exists. Maybe there is something specific to django, that I've overlooked? Any suggestions would be greatly appreciated! -
Using DRF and React for Contact form
I haven't seen anybody accept the form like this using DRF. I'm practically listing all of the fields for the POST method. Is it safe to do so? class ContactForm(generics.ListCreateAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializer @action(methods=['GET'], detail=True) def testing_env(self): return Response({'Works': 'ayyy'}) @action(methods=['POST'], detail=True) def create_contact(self, request): data = request.data print(data) contact = Contact.objects.create(name=data['name'], email=data['email'], subject=data['subject'], message=data['message']) contact.save() return Response({'Success': 'it went good'}) And here's the React Form: handleSubmit(event){ event.preventDefault(); let data = this.state axios({ method: 'post', url: FormURL(), data:{ name: this.state.name, email: this.state.email, subject: this.state.subject, message: this.state.message, } }) } -
Django Project DEPLOYMENT - SECRET KEY
I'm deploying a Django Project on pythonanywhere. This is my first time doing anything of this kind, and I forgot to delete the secret key of my project before pushing it to GitHub (my GitHub account is private), so now the secret key is available in the code in GitHub. Is that a big problem ('cause I still didn't understand what is the key used for)? Is there a way to fix this? I read some articles online and they suggest to keep the key in envoirment variable or stored in a file but I don't have any idea of how to do that or how to change the fact that now the key is available on my GitHub account and on python anywhere since I did git clone. Can someone help me please? -
how to customize a modelform for multiple question
Right now I am able to store an object for the current question which is defined in views.py. A student comes and selects a specific Teacher and answers the question from multi-choice. But this is for one question that is assigned this way. I want my codes to work like: One selection field for Teacher for the entire form. One rating choice for each question. What is the best way to implement an evaluation system form? models.py RATING_CHOICES = ((1, "Weak"), (2, "Average"), (3, "Good"), (4, "Excellent")) class Question(models.Model): question = models.CharField(max_length=200) def __str__(self): return self.question class Teacher(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Student_Answer(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) forms.py class AnswerForm(ModelForm): class Meta: model = Student_Answer exclude = ['question'] widgets = { 'answer': RadioSelect(choices=RATING_CHOICES)} views.py def index(request): form = AnswerForm() question = Question.objects.get(id=1) if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.question = question form.save() return HttpResponseRedirect('/redirected/') else: form = AnswerForm() context = { 'question': question, 'form': form } return render(request, 'index.html', context) index.html <form action="{% url 'index'%}" method="POST"> {% csrf_token %} {{ form.teacher }} <br> {{ question }} <br> {{ form.answer }} <input type="submit" … -
django html video tag
I'm trying to do a project in django. I created the HTML-CSS page. I'm playing a video in the background of my HTML page. When I run this on local, I can see the video playing in the background. But when I add my HTML page's codes to django it doesn't show up. My video tag in html code(source part) like this; src="homevideo.mp4" type="video/mp4" IN DJANGO; project name : lubdub appname : accounts views.py def home(request): return render(request,'accounts/home.html') setting.py STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), ) templates videos homevideo.mp4 Would anyone help me plase? I'm so confused.Thx -
How to deploy Django app with PostgreSQL on GCP at minimum cost for minimal server load?
I need to deploy a Django app using PostgreSQL as the database on Google Cloud Platform. Since the app is only for my personal use, it has a minimal server load. I tried a solution by deploying my app on an F1 App Engine standard environment(us-central1 region) and ran a PostgreSQL instance on an f1-small compute engine(us-central1 region). Both these are provided in GCP free tier in the us-central1 region. But it seems a VPC serverless connector is needed for app engine standard to access Postgres on compute engine on internal IP address.(which is billed as 2 e-2 micro instances). Is there a better way of deploying it on GCP or connecting App engine standard with compute engine private IP, which incurs lesser cost? -
Django not logging anything levels less than WARNING
I am not sure why django is not logging anything less than "WARNING" level. I have this code in the view: logger = logging.getLogger(__name__) def profile_data(request): logging.info("INFO PROFILE DATA!!") logging.debug("DEBUG PROFILE DATA!!") logging.warning("WARNING PROFILE DATA!!") logging.error("ERROR PROFILE DATA!!") and this in my settings.py: # Logging LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, 'filters': { # information regarding filters }, 'formatters': { '<simple_format>': { 'format': '{levelname} {message}', 'style': '{', } }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/logs/log_file1.log', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler' }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, 'root': { 'handlers': ['file', 'console'], 'level': 'DEBUG', } } } As you can see, I try to set everything to the DEBUG level, it doesn't work, I only see this is the warning and error level in the terminal: WARNING:root:WARNING PROFILE DATA!! ERROR:root:ERROR PROFILE DATA!! -
how to use if and else in my django forloop
I am trying to use an if else statement in my django template so that if the bars exist it displays them but if not then it lets me know that there are no bars available. template.html <div class="row"> {% for bar in bars %} <div class="col-md-4 col-lg-4 col-sm-12 col-xs-12" style="margin-bottom: 25px!important;"> <div class="single-promotions text-center"> <div class="promotions-img"> <img src="{{bar.image.url}}" class="img-fluid" style="height: 350px; width: 100%;" alt=""> </div> <div class="promotions-details"> <h4>{{bar.name}}</h4> <h5><span>{{bar.opening_time}} -</span><span> {{bar.closing_time}}</span></h5> <h5>{{bar.address}}</h5> <a href="{% url 'reserve' bar.pk %}" class="read-more">Book a Table</a> </div> </div> </div> {% endfor %} </div> I have tried some methods but it didn't display any thing whether the bars existed or not -
unable to upload image to s3 from django app
When a user creates a new account on my website, an image is created(generated) and is supposed to be uploaded to s3. The image is successfully created(verified by running the ls command on the server in the media directory) but it's not getting uploaded to s3. However, when I try uploading an image for a user account from the admin panel, changes are correctly reflected in s3 (i.e newly uploaded image from admin panel is shown in s3 bucket's directory). I aim to auto-upload the generated image to the s3 bucket when a new account is created. views.py def signup(request): if request.method == "POST": base_form = UserForm(data=request.POST) addnl_form = AddnlForm(data=request.POST) if base_form.is_valid() and addnl_form.is_valid(): usrnm = base_form.cleaned_data['username'] if UserModel.objects.filter(user__username=usrnm).count()==0: user = base_form.save() user.set_password(user.password) user.save() #print(img) addnl = addnl_form.save(commit=False ) addnl.user = user img = qr.make_image() #create a qr code image, full code not included. img.save('media/qrcodes/%s.png'%usrnm) addnl.qr_gen = 'qrcodes/%s.png'%usrnm addnl.save() else: messages.error(request,base_form.errors,addnl_form.errors) else: base_form = UserForm() addnl_form = AddnlForm() return render(request,'app/signup.html',{'base_form':base_form,'addnl_form':addnl_form} ) models.py class UserModel(models.Model): . . . qr_gen = models.ImageField(upload_to='qrcodes',default=None,null=True,blank=True) settings.py DEFAULT_FILE_STORAGE = 'project.storage_backend.MediaStorage' storage_backend.py from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' default_acl = 'public-read' file_overwrite = False Please help me fix the issue. Thanks. -
uWSGI can't find python3 plugin - open("./python3_plugin.so"): No such file or directory
I have tried all solutions in the stackoverflow but still I could not find a solution for me. as you can see in the pluginsdir python3 plugin is available but uwsgi say its not. [uwsgi] ini file [uwsgi] vhost = true plugins-dir = /usr/lib/uwsgi/plugins plugins = python3 socket = /var/run/domain.org.sock master = true enable-threads = true processes = 2 wsgi-file = /var/www/domain.org/config/wsgi.py virtualenv = /var/www/domain.org/env chdir = /var/www/domain.org ls -la /usr/lib/uwsgi/plugins drwxr-xr-x 2 root root 4096 Dec 18 21:44 . drwxr-xr-x 3 root root 4096 Dec 18 21:44 .. ... -rw-r--r-- 1 root root 199896 Apr 11 2020 python38_plugin.so lrwxrwxrwx 1 root root 38 Dec 18 21:44 python3_plugin.so -> /etc/alternatives/uwsgi-plugin-python3 uwsgi --ini /etc/uwsgi/apps-available/domain.org.ini [uWSGI] getting INI configuration from /etc/uwsgi/apps-available/domain.org.ini open("./python3_plugin.so"): No such file or directory [core/utils.c line 3732] !!! UNABLE to load uWSGI plugin: ./python3_plugin.so: cannot open shared object file: No such file or directory !!! *** Starting uWSGI 2.0.19.1 (64bit) on [Fri Dec 18 21:52:29 2020] *** compiled with version: 9.3.0 on 18 December 2020 13:15:35 -
How to add unix timestamp in milliseconds in django model?
Suppose I want add creation time and update time in django model. How to add this in model and get this through in rest api in django? -
How i can upload multiple images in django to different parts of an article on a site?
Hello I am trying to allow users to use images in articles how i can upload multiple images to different parts of an article on a site? And the best way to do it? It's not a problem for me to upload multiple images to one place, but I don't know how to do it in different places. Any help would be much appreciated! -
How can I set up the scss/sass file in django?
Im working on a personal project and im using django. In this project I like to use scss/sass style file, but I dont know how to install and set up in my Django project. Any help will be appreciated Thank u! -
How can I use django validation form with ajax/form validation?
I try to implement popup before form validation. popup contains data recovered form an ajax query. it works but it is not optimized as I have lost django validation form: if my form is not valid, no error messages are displayed for now, the only way I manage to "solve" this issue, is to use the same ajax query to test for form validation and display error message but it is the not the good way to do that How can I manage to use django validation form with ajax/form validation? JS var prevent_edit = false; var prevent = false; $("#form_unblind_edit").submit(function (event) { if (!prevent_edit) { event.preventDefault(); } }); function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } // affichage des informations sur le patient sélectionné pour la ré-allocation $("#unblind_edit").on("click", function (event) { var csrftoken = getCookie('csrftoken'); var patient = $("#id_pat").val(); var treatment = … -
Django Popup modal which displays form options/selection
I am building an application with has a few forms where people can select options from my database. I found the django-popup-view-field (image below). When you click on the search icon on the form, a modal opens where you can search all database options by name or letter, and select them as an entry in your form. The downside of this method is that the value you display in the form needs to be your primary key. I would rather use the default pk of django since it is much more reliable than for instance a name or other text field. Also, this solution requires quite some code and I have a feeling that this can be done more efficiently. In addition, having an id as pk makes CRUD way easier. Do any of you have suggestions or links to documentation where they try to achieve a similar thing? -
I'm trying to make a blog. I want to display all the post belongs to same date in detailed view on one page?
I'm trying to make a blog where I want to display all the blogs posted on same date on one page in detailed view. models.py class Article(models.Model): article_name= models.CharField(max_length=255) article_data=models.TextField() image=models.FileField(blank=True,null=True) video=models.FileField(blank=True,null=True) module_name=models.ForeignKey(Module, on_delete=models.CASCADE) paper_name=models.ForeignKey(Paper, on_delete=models.CASCADE) subject_name=models.ForeignKey(Subject, on_delete=models.CASCADE) topic_name=models.ForeignKey(Topic, on_delete=models.CASCADE) subtopic_name=models.ForeignKey(SubTopic, on_delete=models.CASCADE) created_at = models.DateField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() def __str__(self): return self.article_name def get_absolute_url(self): #return reverse('dca_detail', args=(str(self.id))) return reverse('home') views.py from django.shortcuts import render from django.views.generic import ListView, DetailView, DateDetailView, CreateView , UpdateView, DeleteView from dca.models import Article from dca.forms import ArticleForm from django.urls import reverse_lazy from django.http import request def home(request): return render(request, 'home.html') class dca_list(ListView): model = Article template_name= 'dca.html' ordering= ['id'] class dca_detail(DetailView): model= Article template_name= 'dca_detail.html' class add_dca(CreateView): model = Article form_class= ArticleForm template_name = 'add_articles.html' success_url= reverse_lazy('dca_list') # fields = '__all__' # fields = ('article_name','article_data',) class update_dca(UpdateView): model = Article template_name = 'update_dca.html' fields='__all__' success_url= reverse_lazy('dca_list') class delete_dca(DeleteView): model = Article template_name = 'delete_dca.html' success_url= reverse_lazy('dca_list') can someone help me what should be the code in my template? The schema of the output is as follows: POSTS on DD/MM/YYYY where clicking on the posts should display all the detailed views of posts posted on same date. -
What is the most efficient and scalable way to set up a React front-end for Django?
I'm building a web-project that will have a React based front-end backed by a Django REST back-end. I'm trying to figure out the most efficient way to set-up and connect both applications into one. Here is the set-up I have in mind, creating a frontend/ folder inside my Django project directory. ProjectDirectory/ manage.py core/ __init__.py settings.py urls.py asgi.py wsgi.py frontend/ src Is the standard and scalable way to implement Django and React together? -
Django - add context to request to be used by the view
Using Django I want to implement some middleware that will calculate some context that is to be used by the view itself. For example, I have a middleware that looks at the request, and adds the user's permissions to the request, or some user configuration. The view looks at these permissions and decides how to handle the request using it. This saves the need for multiple views (and multiple parts within the view) to query for this information. I'm wondering what is the correct way to do that. One option is to just add request.user_permissions=... directly on the request. But is there some documented and expected way to do that? -
Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed
https://www.youtube.com/watch?v=AlJ8cGbk8ps i followed this video and when i do this command django-admin makemessages -l ar it gives me this error CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. and i have installed pip install python-gettext any aswers? Thanks in advance -
Asynchronous execution of a function inside Django
This is how the views.py file would look like for example. The user will make some post request and trigger a CPU intensive execution which will take a long time to finish. I want to return a response to the user with some message denoting that execution started and maybe some unique execution id. The point being the user does not need to wait for the execution to end. So I am starting the time-consuming function in a separate thread, and whenever it finishes execution, it will make entry to some remote database. Is this a good approach to achieve the same or are there any potential vulnerabilities with this approach? Note: Although the function takes a long time to finish, it is essentially a small service, with probably one instance needed to run in production. import threading from rest_framework.views import APIView from rest_framework.response import Response def async_function(x): time.sleep(10) print(f'[*] Task {x} executed...') class MainFunctionView(APIView): def get(self, request): return Response({'val': 1}) def post(self, request): #req = ExecutionRequest(request) t1 = threading.Thread(target=async_function, args=(request.data.get('val'),)) t1.start() return Response('exection started') Thanks in advance. -
Forbidden HTTP 403 DRF + ReactJS request.session
I am working on a Quiz Application using DjangoRestFramework and ReactJS. My App is comprised of two apps, api and frontend. In my api app, I have multiple API views for many different things. One of my API Views is called JoinQuiz. When I call it on my frontend, I get this error in the console: Forbidden: /api/join-quiz [16/Dec/2020] "POST /api/join-quiz HTTP/1.1" 403 58 I don't think my problem is due to a CSRF error because my other API views are working perfectly fine. I may be wrong on this point. [16/Dec/2020] "GET /api/get-question?id=3 HTTP/1.1" 200 10009 [17/Dec/2020 01:15:47] "POST /api/create-quiz HTTP/1.1" 201 11959 I suspect that my request.session may be the issue because when I go directly to /api/join-quiz and make a POST request with my code, nothing goes wrong and I have a successful post. Files Views.py class QuizView(generics.ListAPIView): queryset = Quiz.objects.all() serializer_class = QuizSerializer class GetQuiz(APIView): """ Searches for a quiz given its code and returns the Quiz with is_host info""" serializer_class = QuizSerializer lookup_url_kwarg = 'code' def get(self, request, format=None): # This is an HTTP GET request code = request.GET.get(self.lookup_url_kwarg) if code != None: # Check if code is not equal to None quiz = Quiz.objects.filter(code=code) … -
How to validate request.POST.get() is not None and not empty is there any easy way to handle?
i am trying to validate my request.POST.get() data if it is null or empty i am redirecting to error page i tried this way if there is better way to handle this please let me know. given_name = request.POST.get('given_name') surname = request.POST.get('surname') gender = request.POST.get('gender') DOB = request.POST.get('DOB') email = request.POST.get('email') phone = request.POST.get('phone') address = request.POST.get('address') if given_name == "" or given_name == None or surname == "" or surname == None or gender == "" or gender == None or DOB == "" or DOB == None or email == "" or email == None or phone == "" or phone == None or address == "" or address == None: -
"Too many redirects" error with naked domain on PythonAnywhere Django web app + Google Domains, but www works?
I've been messing with the settings for my Google Domains DNS for "mollygeerling.com" as my PythonAnywhere web app will work fine if the address is "www.mollygeerling.com" but not the naked domain. I think this has something to do with my DNS settings and/or my Django settings.py file (allowed hosts includes both the www and naked domains which I thought would fix it but it does not). I am using the Google Domains name servers and I have DNSSEC turned on. At PythonAnywhere I have "force HTTPS" turned on. My guess is something in my Google Domains subdomain forwarding is wrong. Any help appreciated! -
Why does a field(liked_songs) show for a userprofile in admin/ but not when I query the database
ORM queries >>> from comparison.models import UserProfile, Song, Album >>> UserProfile.objects.all() <QuerySet [<UserProfile: kb>, <UserProfile: Daniella>]> >>> Song.objects.all().values_list("pk", flat=True) st' <QuerySet [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, '...(remaining elements truncated)...']> 6, 17, 18, 19, 20, '...(remaining elements truncated)...']> >>> UserProfile.objects.get(id=2) <UserProfile: Daniella> >>> UserProfile.objects.get(id=2).liked_songs.all()[0:20] <QuerySet []> >>> UserProfile.objects.get(id=1) <UserProfile: kb> >>> UserProfile.objects.get(id=1).liked_songs.all()[0:5] <QuerySet [<Song: Emotionally Scarred>, <Song: Lonely Child>, <Song: Really Love>, <Song: Another Life>, <Song: Bitches Ain't Shit>]> >>> models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None , null= True) liked_songs = models.ManyToManyField("Song", null=True , default=None, related_name="users_that_liked_me") class Meta: db_table = "UserProfile" def __str__(self): return self.user.first_name class Album(models.Model): Album_name = models.CharField(max_length=40) class Meta: db_table= "Album" def __str__(self): return self.Album_name class Song(models.Model): track_name = models.CharField(max_length=250) artiste_name= models.CharField( max_length=200) album = models.ForeignKey(Album, on_delete= models.CASCADE, null=True, default=None, related_name = "songs") class Meta: db_table="Song" def __str__(self): return self.track_name views.py(one which uses the models) def liked(request): try: sp = Spotify(auth_manager=oauth) liked = sp.current_user_saved_tracks(limit=30)['items'] spotify_user = sp.current_user() user__ , created = User.objects.get_or_create(username=spotify_user['uri'], first_name=spotify_user["display_name"]) userprofile = UserProfile.objects.get_or_create(user=user__)[0] a = [] for idx, item in enumerate(liked): track = item['track']["name"] artist= item["track"]["artists"][0]["name"] album_ = item["track"]["album"]["name"] tracks = item['track'] val = tracks['name'] + " - …