Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Couldn't show many-to-many fields from form on on HTML form in Django
I couldn't get my input data to many-to-many field data via the HTML form. How to solve this? This is my code: models.py class SetStaffSchedule(models.Model): # generated work for staffs by admins schedule = models.ManyToManyField('Staff') shift = models.DateTimeField("Shift") detail = models.TextField("Task Detail", max_length=200) def __str__(self): return self.shift def __str__(self): return self.detail forms.py from django import forms from attendance.models import SetStaffSchedule, Staff class SetStaffScheduleForm(forms.ModelForm): class Meta: model = SetStaffSchedule fields = ['schedule','shift', 'detail'] views.py def post(request): # posting schedules for staffs' work form = SetStaffScheduleForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save(); return redirect ('schedules') return render(request, 'post_schedules.html', {"form": form}) post_schedules.html {% csrf_token %} {{ form.as_p }} -
How to deploy app with Nginx, React, Webpack, Gunicorn, PostgreSQL, Django & DRF on AWS Elastic Beanstalk? How to handle static files with this app?
I'm new to AWS environment. I've few questions regarding AWS deployment. An important point to remember here is that I am using free tier of AWS. So I've limitations about resources. Question1: I've developed a web app on my local server (using VM with centos Linux) which uses React-SSR for the frontend using Express server. React CSR and SSR is generated using webpack. Backend uses Django as main framework, postgreSQL for database. Frontend and backend communicate with the help of Django Rest Framework. Gunicorn is used to run backend server. I want to use Nginx as reverse proxy server. How can I deploy this app on AWS Elastic Beanstalk? Can Amazon S3 be used to run React-SSR frontend? Question 2: This app serves images which'll be uploaded through backend. What's the proper way to handle images and static files with this kind of app? Should images be handled by nginx, react or django? How should I configure Django so that it stores image paths properly in its model(ImageField is used)? Where does Amazon S3 fit in this? Question 3: Can this app be made region agnostic under free tier? -
Django, accessing a foreign key from parent object works from shell but fails in Django
I have two models in my models.py : class Organisation (models.Model) : name = models.CharField(max_length=200, null=False) logo = models.ImageField(upload_to="organisations /logos/", null=True) class Profile (models.Model) : user = models.OneToOneField(User, on_delete=models.CASCADE) organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE) [...] My Profile model is an extension of the built-in User model from Django. I catch a user POST request using one of my views : class fillConventionView(APIView) : permission_classes = (IsAuthenticated,) def post(self, request): org = User.objects.get(pk=request.user.pk).profile.organisation.name As described here, I use the user's request to catch its user id (request.user.pk), and get the associated Profile, which works. Then, from the Profile I try to catch the associated Organisation, and Organisation name field. That operation fails providing the following error : name 'organisation' is not defined Though, the same line of code using Django Shell works : python 3 manage.py shell > User.objects.filter(pk=1).first().profile.organisation.name returns the correct organisation name. How come I can access a foreign key value in the shell and not in production in Django using the same line of code ? -
Using Django F expressions with many-to-many fields
I'm trying to write a Django query which filters on if a foreign key field A is contained in a collection B. Collection B is a many-to-many field on the model, and so I'm using F-expressions to try and compare the two. The actual query is with more complex model relations and using Subquerys and OuterRefs, but since OuterRef is a special type of F expression for use with the Subquery object, any guidance on how to use F-expressions with many-to-many fields would be really helpful. Here are the simplified models we're working with: class Instructor(models.Model): name = models.CharField() class Review(models.Model): instructor = models.ForeignKey(Instructor) instructors = models.ManyToManyField(Instructor) Where instructor is not necessarily in instructors The query we would like to do: Review.objects.filter(instructor__in=F('instructors')) After lots of searching on Google and StackOverflow, I couldn't find any examples of F expressions being used with many-to-many fields. Are they not compatible? Thanks in advance for any help! -
Django template adding javascript and jquery
I'm trying to add javascript static file in to my html. But i couldn't HTML: https://i.stack.imgur.com/Wo3pz.jpg URL: https://i.stack.imgur.com/Lq1IF.jpg JS: https://i.stack.imgur.com/S8xZZ.jpg FILE: https://i.stack.imgur.com/qTEao.jpg -
AUTH_USER_MODEL refers to model '' that has not been installed
I have a CustomUser that extends the AbstractUser as follows class CustomUser(AbstractUser): USERTYPE_CHOICES = [(1,"A"),(2,"B"),(3,"C")] usertype = models.IntegerField(choices = USERTYPE_CHOICES, default = 1) I have the following lines in my settings.py INSTALLED_APPS = [ ... 'login_register_service_hub.apps.LoginRegisterServiceHubConfig', ... AUTH_USER_MODEL = 'login_register_service_hub.CustomUser' Everything works as expected however: I am trying to implement a custom authentication backend and I do this by including the following from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model #Check for the is_active property class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None def get_user(self, user_id): UserModel = get_user_model() try: return UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None I update my settings.py with the following: AUTHENTICATION_BACKENDS = {'login_register_service_hub.EmailBackend',} However as soon as I run python3 manage.py runserver I get the following error "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'login_register_service_hub.CustomUser' that has not been installed The interesting remark is that the command fails only if I import ModelBackend (even if I comment out the EmailBackend definition) -
Data Reporting Technique to support Django, Python, HTML, CSS
Is there a Data Reporting Technique to support Django, Python, HTML, CSS. It should be able to generate multiple page Reports on the selected Paper Size while taking care of the Header, Footer and the Page Margins. -
Where am I suppose to add a USER to a GROUP in django?
In models.py i have the following code: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField("Nome",max_length=50) email = models.EmailField(max_length=256) # A CharField that checks that the value is a valid email address using EmailValidator. phone_number = models.CharField("Número de telemóvel", max_length=9) cc = models.CharField("Número de cartão de cidadão", max_length=8, unique=True) nif = models.CharField("Número de identificação fiscal", max_length=9, unique=True) address = models.CharField("Morada", max_length=200) cp = models.CharField("Código de postal", max_length=8) date = models.DateTimeField(auto_now_add=True) #guarda automaticamente a data a que foi criado def __str__(self): return str((str(self.name), str(self.cc), str(self.nif), str(self.date))) class AppUser(Profile): TYPES = [ ('A', 'Admin'), ('M', 'Medic'), ('S', 'Secretary'), ] type = models.CharField("Tipo",max_length=1, choices=TYPES) I want to check the type of a user and add it to a certain group. Where do i write that code? I know there is a way to do it in the shell but i was wondering if there is another way. Every time i create a user I'd like to add to the correct group based on the type. The following code is more or less what i want to happen: if type == 'A': user_id = Profile.user mygroup, created = Group.objects.get_or_create(name='Admin') a = User.objects.get(id=user_id) mygroup.user_set.add(a) mygroup.save() Also, i don't know if the code above is correctly … -
How to connect opencv code in django framework
Scene 1: I have written a code in openCV for live face detection using the webcam of my laptop... Scene 2: I have my Django based Website Now what i want is to connect my Django framework with this openCV code and directly detect live faces from the website Does anyone have any idea as of how to achieve it? -
why do I get this error django_select2.js was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type
I'm trying to make the select2 work in my django app via django_select2 library. I've done the installation of the library, setup in URL and the change required in the forms.py. I have also added {{ form.media.css }} and {{ form.media.js }}. When I try to access the page where its supposed to work, I get an error in the console 1. The script from “http://127.0.0.1:8000/static/django_select2/django_select2.js” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type. 2. Loading failed for the <script> with source “http://127.0.0.1:8000/static/django_select2/django_select2.js”. I have tried adding these in my settings.py file but I still get the error. import mimetypes mimetypes.add_type("text/css", ".css", True) Also there was an answer suggesting to put a space after the first line of django_select2.js, but I still got the same error. Any ideas guys? -
converting and multiply float to int in django templates
I am fetching some data from a stocks API and I get some values (stored in the DB as float) as follow: YTD Change 0.379996 daily % change 0.00854 my view is as follow: def get_stock(request): empty = True localStocks = Stock.objects.all() if len(localStocks) > 0 : empty = False return render (request,'get_stock.html',{'empty':empty, 'output':list(localStocks)}) and my template <section class="section-typography container u-readable"> <table> <thead> <tr> <th>Ticker</th> <th>Name</th> <th>Price</th> <th>Last Time</th> <th>% Change</th> <th>52W High</th> <th>52W Low</th> <th>YTD Change</th> </tr> </thead> <tbody> {% if not empty %} {% for list_item in output %} <tr> <td> {{list_item.symbol }}</td> <td> {{ list_item.companyName }}</td> <td> {{ list_item.latestPrice }}</td> <td> {{ list_item.latestTime }}</td> <td> {{ list_item.changePercent }}</td> <td> {{ list_item.week52High }}</td> <td> {{ list_item.week52Low}}</td> <td> {{ list_item.ytdChange }}</td> </tr> {% endfor %} {% endif %} </tbody> </table> </section> {% endblock %} the % change for the stock YTD is not 0.379996 but 37.99% and this is what I would like to display. Similarly the daily change is not 0.00854 but 0.85% . How can I manipulate the date either on the view or template to basically multiply it and display only the first 2 decimals of the float? -
How to get field edited by comparing before-edited instance to current instance
I'm currently trying to log field changed when making edits to a user, however, I'm struggling to compare the old user instance to the current user instance and retrieve the field(s) that are different. As of now when running the conditional inside the for loop, it prints all the fields related to the model, and not the field edited. I'm also struggling to get the value of the fields looped through. Method: def log_user_change(old_user_instance, request): user = User.objects.get(pk = old_user_instance.id) user_fields = user._meta.get_fields() old_user_fields = old_user_instance._meta.get_fields() ct = ContentType.objects.get_for_model(user) for old_user_fields in user_fields: if not old_user_fields in user_fields: field_values = getattr(old_user_instance, old_user_fields.attname) print('Changed field:') print(old_user_fields) print('Values:') print(field_values) """ ChangeLog.objects.log_updae( user = request, content_type = ct.pk, object_id = user.pk, changes = user_fields, ) """ View: def editUser(request, pk): # Query appropriate user based on pk returned in url user = User.objects.get(pk = pk) # Get the EditUserForm and add the user as instance edit_user_form = EditUserForm(instance = user) if request.method == 'POST': # Bind data to the form class, and add the user as instance edit_user_form = EditUserForm(request.POST, error_class=DivErrorList, instance = user) old_user_instance = User.objects.get(pk = pk) # Validate form inputs if edit_user_form.is_valid(): # Save edits edit_user_form.save() # Log change ChangeLog.log_user_change(old_user_instance, … -
How to read Objects from ManyToMany Relation class in django
I have made a class called friend where i want to connect users as followers. Here From this class i am unable to read the users those are following another user. For Eg if 'a' user fllows 'b' user. Then i want to get the names of user that followed b from the user id of b and display them as followers of a. This class is also not storing the userid of the following user and followed user. I am new to many to many relation field. Kindly help. Code in Models.py class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, related_name='follower', null=True,on_delete=models.CASCADE) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user = current_user ) friend.users.add(new_friend) Its function in views.py is def change_friends(request, operation, pk): friend = User.objects.get(pk=pk) if operation == 'add': Friend.make_friend(request.user, friend) elif operation == 'remove': Friend.lose_friend(request.user, friend) return redirect('home') Its url in urls.py is path('connect/<operation>/<pk>)',views.change_friends, name='change_friends') -
Passing an object to a form gives me __init__() got an unexpected keyword argument 'instance'
I'm just starting writing a view to update a form. When I bind an object to the form, so as to pre-populate the form with the data of the object being viewed, I get an error. I've read through the documentation and many examples and as far as I can see my code is correct, so I'm at a loss. view.py @login_required def entries_update(request, pk): journal_entry = get_object_or_404(JournalEntry, pk=pk) journal_entry_form = JournalEntryForm(instance=journal_entry) return render(request, 'journal/entries_update.html',{'journal_entry': journal_entry, 'journal_entry_form': journal_entry_form,}) forms.py class JournalEntryForm(forms.Form): # This can be simpliedied to a ModelForm date = forms.DateField(widget=DateTypeInput()) description = forms.CharField(required=False) def clean_date(self): data = self.cleaned_data['date'] #Check date is not more than 30d future if data > (datetime.date.today() + datetime.timedelta(30)): raise ValidationError('Date cannot be more than 30d future') if data < (datetime.date.today() - datetime.timedelta(90)): raise ValidationError('Date cannot be more than 90d past') return data models.py class JournalEntry(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) date = models.DateField(null=True, blank=False) TYPE = ( ('BP', 'Bank Payment'), ('YE', 'Year End'), ('JE', 'Journal Entry') ) type = models.CharField( max_length=2, choices=TYPE, blank=True, default='0' ) description = models.CharField(max_length=255, null=True, blank=True) def __str__(self): if self.description: return self.description else: return 'Journal Entry' + str(self.id) class Meta(object): ordering = ['id'] verbose_name_plural = 'Journal entries' Last item in the … -
Getting error in importing path and include from django.urls
I have created a sample project using Django but when I opened the file in IDE it shows error for importing path and include from django.urls module. The error statement is Cannot find reference 'include' in '__init__.py' and Cannot find reference 'path' in '__init__.py' -
Is there any free Report Builder or Technique supporting Django, PostgreSQL, Python and JavaScript
I am developer with knowledge of Django, Python, PostgreSQL, JavaScript and VueJS. I am interested to know if there is any free Report Builder or Technique by which I can generate multiple page Reports on the selected Paper Size while taking care of the Header, Footer and the Page Margins. -
Not able to get old user instance before edits, and compare fields to get field edited
I have a model for logging changes and is attempting to get the fields edited upon user edit to log it. I'm currently trying to loop through the old user object and the user object after edits to compare the field(s) through object._meta.get_fields(), and the plan is to log/get the field(s) that are different. One of the problems I have is that when I print the user object under ("#breakpoint 1"), I get the before-edited user object, but when I use it as a parameter in the method ("# breakpoint 2") it prints the edited user object, instead of the before-edited object. How can I fix this? Alternatively, is there a better way to log the fields edited? View def editUser(request, pk): # Query appropriate user based on pk returned in url user = User.objects.get(pk = pk) # Get the EditUserForm and add the user as instance edit_user_form = EditUserForm(instance = user) if request.method == 'POST': # Bind data to the form class, and add the user as instance edit_user_form = EditUserForm(request.POST, error_class=DivErrorList, instance = user) old_user_instance = user # breakpoint 1 print(old_user_instance) # Validate form inputs if edit_user_form.is_valid(): # Save edits edit_user_form.save() # Log change ChangeLog.log_user_change(old_user_instance, request.user.id) # Give … -
Django update monthly_score of each user with total likes for all their posts
I want to update the monthly_score field for every user's Profile. I have a Post model with a method to return the post's likes called like_count. How do I use Profile.objects.update(monthly_score=Subquery( )) to get the user's posts this month and return a sum of all their likes? I tried this but it didn't work Profile.objects.update(monthly_score=Subquery(Post.objects.filter(user=Profile.user, date_posted__month=today.month).aggregate(Sum(like_count)))) -
How can I prevent django from opening another window upon hitting the login button on the login page?
I am coding a small web app using django (version 3.0) and python (version 3.7.1). I use django's integrated authentification tool to manage user login and such things. The problem I am facing is, that when I log in with any user I get redirected to the next page, as I want it, but it does open in a new browser window and that is not something I want to happen. Since I do not really know where to start fixing this issue I can not really provide any information about what I already tried. But it only happens when I pass any next parameter to the login form (e.g. account/login?next=/general_information/ to get redirected to the general information page after successful login. It happens with any redirect url.) -
save and load one hot encoding for ML (Django Env)
I have been searching for tow days now and at seems I cannot grasp the solution. For a machine learning regression model, I need a hot encoding of some columns. The training data and model fitting is happening on my local PC. After this the model will be uploaded to the server for predictions. The problem is that new data was not part of initial encoding so I need to hot encode it in same way as learning data on my PC. I found out that I can save the encoder (sklearn.preprocessing -> OneHotEncoder). But I cannot manage to get the data into the correct format. To make it easiert to understan here I just created a notebook with some very simple dummy data. # Import pandas library import pandas as pd # initialize list of lists data = [['tom', 10], ['nick', 15], ['juli', 14]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age']) # print dataframe. df # hot encoding hot_Name = pd.get_dummies(df.Name) X = pd.concat((df[['Age']], hot_Name), axis=1) X # outside data # initialize list of lists data_new = [['michael', 20], ['jordan', 45]] # Create the pandas DataFrame df_new = pd.DataFrame(data_new, columns = ['Name', 'Age']) # … -
Reverse from POST method in django class based view (DetailView)
I have probably trivial question but I am newbie in Django and I don't know why I get error when I want to redirect here. I get proper url but I get error 'str' object has no attribute 'get'. What do I wrong? Form is correct and object is created in db. It's only about wrong redirect. Thanks for help. My urls.py: urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('user/<str:username>/', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('comments/delete/<int:pk>/', views.CommentDeleteView.as_view(), name='delete-comment'), path('about/', views.about, name='blog-about'), ] Error view -
DJANGO : Problem of mixing between URL of web pages and media files
I'm developing a website and sometimes I have a strange problem : the URL of the page is concatened with the URL of the images on this page, which means I cannot access to these images. It's a bit hard to explain so here is an example : I have a view called "mes_plats" that displays some informations about meals cooked by a cooker. The informations are displayed with a background located at static/media/img_background.jpg and everything works correctly. I have another view called "supprimer_plat" (url : supprimer-plat) whose purpose is to delete the informations about a particular meal. This view render the same html template as the other one but this time the template try to access the following url for the background : supprimer-plat/static/media/img_background.jpg. Obviously the background isn't displayed. So my question is, why does the url of the page concatened to the URL of the image in one case and not in the other ? And how can I solve it ? Thanks in advance ! views.py def mes_plats(request): return render(request, 'actualites/mes_plats.html', {'my_meals': Plat.objects.filter(chef=request.user.useradvanced.chef, date_prep__gte = date.today())}) def supprimer_plat(request, id): plat = get_object_or_404(Plat, id=id) plat.delete() return render(request, 'actualites/mes_plats.html', {'my_meals': Plat.objects.filter(chef=request.user.useradvanced.chef, date_prep__gte = date.today())}) urls.py urlpatterns = [ path('mes-plats', … -
Python opencv wait for resource to be free
My idea is using a Raspberry Pi for streaming video, for which Django will do the heavy lifting. In another process, I will also run some Celery workers, which capture a picture from the same camera every 5th seconds and send the picture to the public server. Following is the code to access the camera. Since there is only one camera and two independent processes want to access it, how can I make the line self.video = cv2.VideoCapture(0) wait for the camera to be free instead of throwing an exception? For my requirement a high latency is acceptable. Camera code import cv2 class VideoCamera(object): def get_frame(self): try: self.video = cv2.VideoCapture(0) success, image = self.video.read() self.video.release() ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() finally: self.video.release() video_camera = VideoCamera() def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') Streaming on local browser: from django.contrib import admin from django.http import StreamingHttpResponse from django.urls import path from DjangoWebcamStreaming.camera import video_camera, gen urlpatterns = [ path('monitor/', lambda r: StreamingHttpResponse(gen(video_camera), content_type='multipart/x-mixed-replace; boundary=frame')), path('admin/', admin.site.urls), ] Celery: from __future__ import absolute_import, unicode_literals import os from celery import Celery, shared_task from django.conf import settings from DjangoWebcamStreaming.camera import video_camera os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoWebcamStreaming.settings') app = … -
How can I show a loading animation in Django while the server is processing a view?
So I'm currently working on a Django project that has a view that takes quite a bit of time to load and it can be rather user unfriendly to keep the user wondering what's wrong with the website until the page loads. My website works in way such that the user would have a url such as: http://www.example.com/Name/JohnRichards Saved to their bookmarks. Upon visiting the above URL the server should display a loading message (probably with a GIF and AJAX or JS) of a loading screen until the server finishes loading data and then display it. Note: Just in case it matters, when he user goes to the above mentioned link, they won't be redirected there, rather, this would be their entry point since it's a url that they have saved in their bookmarks What I thought would work is as soon as somebody visits the page I would return some sort of a loading template of sorts, and then after the data processing has finished, I would return the final response. But I can't have two returns in a function. How could I add a loading screen of sorts between user using visiting the URL and the data processing … -
Is there is any way to convert this FBV to CBV in polls tutorial of djangoTutorial?
I have tried this but it is not near the solution. I am a beginner in Django. your response is very helpful for me. def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))