Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
<FallbackStorage: request=<WSGIRequest: GET ''>>
Hi I have following setup: Views.py def employerSignupView(request): if request.method =="POST": form = EmployerSignupForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) messages.success(request,'Hooray !! you have account with us now!!') return redirect('home') else: messages.success(request, 'There has been problem registering new account with us. Please try again') form=EmployerSignupForm() form=EmployerSignupForm() return render(request, 'employerSignup.html', {'form': form}) urls.py urlpatterns = [ path('', views.home, name='home'), path('signup/employer/', views.employerSignupView, name='employerSignup'), path('signup/jobSeeker/', views.jobSeekerSignupView, name='jobSeekerSignup'), path('login/', views.user_login, name ='login'), path('logout/', views.user_logout, name='logout'), path('myaccount/',views.myaccount, name='myaccount'), ] forms.py class EmployerSignupForm(forms.ModelForm): username= forms.CharField(max_length=200, widget=forms.TextInput({"placeholder": "Username", "class": "form-control", "type": "text"})) email= forms.EmailField(widget=forms.TextInput({"placeholder": "Your email", "class": "form-control", "type": "email"})) first_name = forms.CharField(max_length=50, widget=forms.TextInput({"placeholder": "Buisness Name", "class": "form-control", "type": "text"})) last_name =forms.CharField(max_length=50, widget=forms.TextInput({"placeholder": "Type", "class": "form-control", "type": "text"})) password1 =forms.CharField(widget=forms.TextInput({"placeholder": "Password", "class": "form-control", "type": "password"})) password2 =forms.CharField(widget=forms.TextInput({"placeholder": "Re-type Password", "class": "form-control", "type": "password"})) streetAddress = forms.CharField(widget=forms.TextInput({"placeholder": "Street Address", "class": "form-control", "type": "text"})) suburb = forms.CharField(widget=forms.TextInput({"placeholder": "Suburb", "class": "form-control", "type": "text"})) postcode = forms.CharField(widget=forms.TextInput({"placeholder": "Postcode", "class": "form-control", "type": "text"})) phoneNumber = forms.CharField(widget=forms.TextInput({"placeholder": "Phone Number", "class": "form-control", "type": "tel"})) website = forms.CharField(widget=forms.TextInput({"placeholder": "Website", "class": "form-control", "type": "url"})) class Meta: model= Employer fields= ('first_name', 'last_name','username' ,'email', 'streetAddress', 'suburb', 'postcode', 'phoneNumber', 'password1', 'password2' ) models.py class User(AbstractUser): class Role(models.TextChoices): ADMIN = 'ADMIN', … -
How to Integrate my Python with Django and HTML
Hi I'm extremely new to Django, like yesterday new. I was scouring the web for hours searching for a way to integrate a simple Python project I made to Django in order to keep me on track. I want to use Django as I'm going to be using Django in my classes soon and would like to learn. Is there any way I can do this? WANTS: I want to use Python for my backend & Django framework to link some HTML, CSS, and possible JavaScript to make thing look nice. Python Timer Project import time import os from threading import Thread def userTimeSet(): while True: try: hours = int(input("Number of hours? ")) minutes = int(input("\nNumber of minutes? ")) if hours > 0 and minutes > 0: interval_sec = (hours*3600)+(minutes*60) print(f"hours and minutes to seconds checking: {interval_sec}") elif hours > 0 and minutes == 0: interval_sec = (hours*3600) print(f"hours to seconds checking: {interval_sec}") elif hours == 0 and minutes > 0: interval_sec = (minutes*60) print(f"minutes to seconds checking: {interval_sec}") else: print("invalid.") futureTime = timeConfirmation(hours, minutes) # create and start the daemon thread print('Starting background task...') daemon = Thread(target=timeCheck, args=(futureTime, interval_sec,), daemon=True, name='Background') daemon.start() print('Main thread is carrying on...') time.sleep(interval_sec) print('Main … -
Django application slow due to multiple foreign keys
I'm having trouble displaying and modeling in django with multiple foreign keys. When displaying or creating it takes a long time as I have a lot of data. For example when trying to create with CreateView it takes a long time, or when trying to display the stored data. Is there any way to optimize the creation and at the time of display? The models with multiple foreging key and ManyToManyField are the following: class Player(models.Model): name = models.CharField("Nombre", max_length=100, blank=True, null=True) player = models.ForeignKey(Socio, on_delete=models.CASCADE, related_name="player_socio") division = models.ForeignKey(Division, on_delete=models.CASCADE,related_name="player_division", blank=True, null=True) goals = models.IntegerField("Goles", default=0) league = models.ForeignKey("League", on_delete=models.CASCADE, related_name="player_league") class Team(models.Model): team = models.CharField("Equipo", max_length=50, blank=True, null=True) league = models.ForeignKey("League", on_delete=models.CASCADE, related_name="team_league", blank=True, null=True) players = models.ManyToManyField(Player, blank=True, related_name="player_team") class Match(models.Model): league = models.ForeignKey(League, on_delete=models.CASCADE, related_name="match_league") date = models.DateField("Fecha", default=timezone.now) week = models.IntegerField("Semana", default=0) team_1 = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="team_1_goal") team_2 = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="team_2_goal") class Goal(models.Model): goal = models.IntegerField("Goles", default=0) match = models.ForeignKey(Match, on_delete=models.CASCADE, null=True, blank=True, related_name="match_goals") player = models.ForeignKey(Player, on_delete=models.CASCADE, null=True, blank=True, related_name="player_goal") league = models.ForeignKey("League", on_delete=models.CASCADE, related_name="player_league_goal") And when creating or displaying the data I use class-based views. I tried to display the data with select2 but it's still slow. Thank you in advance -
Multiple django instances on Apache Windows using the same virtual host
I have a WAMP Server 3.2 (Apache 2.4.46) installed on Windows 10 (64-bits), it is exposed to the local company network. I need to deploy several django projects under the same host - the company network doesn't allow another ServerName. Is it possible at all? Daemon Processing is not an option since this is Windows. My httpd-vhosts.conf: <VirtualHost *:80> ServerName XXXXXXXXXXXX DocumentRoot "d:/projects" WSGIPassAuthorization On WSGIScriptAlias /site1 "d:\projects\site1\site1\wsgi_windows.py" WSGIScriptAlias /site2 "d:\projects\site2\site2\wsgi_windows.py" WSGIApplicationGroup %{GLOBAL} <Directory "d:\projects\site1\site1"> <Files wsgi_windows.py> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Files> </Directory> <Directory "d:\projects\site2\site2"> <Files wsgi_windows.py> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Files> </Directory> Alias /static "d:/projects/site1/static" <Directory "d:/projects/site1/static"> Require all granted </Directory> </VirtualHost> Example of wsgi_windows.py for site1: activate_this = r'C:/Users/XXXXX/Envs/XXXXXX/Scripts/activate_this.py' exec(open(activate_this).read(),dict(__file__=activate_this)) import os import sys import site site.addsitedir(r'C:/Users/XXXXX/Envs/XXXXXX/Lib/site-packages') sys.path.append(r'D:/Projects/site1') sys.path.append(r'D:/Projects/site1/site1') os.environ['DJANGO_SETTINGS_MODULE'] = 'site1.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Right now I have Apache running only site1. If I try to reach site2 I got a error 404 "Page is not found" and Django error page listing the available urls for site1 (I have DEBUG=True). Is it possible to get both site1 and site2 working? -
How do I handle dependency injection in Django?
I am currently trying to manage dependency injection in a django application. I found this thread (Is this the right way to do dependency injection in Django?) and tried the following simple example based on what I found there. /dependencyInjection/serviceInjector.py from functools import wraps class ServiceInjector: def __init__(self): self.deps = {} def register(self, name=None): name = name def decorator(thing): """ thing here can be class or function or anything really """ if not name: if not hasattr(thing, "__name__"): raise Exception("no name") thing_name = thing.__name__ #Set the name of the dependency to the name of the class else: thing_name = name #Set the name of the dependency to a name specified in the register function self.deps[thing_name] = thing # I don't think we will be doing this //Elias return thing return decorator def inject(self, func): @wraps(func) def decorated(*args, **kwargs): new_args = args + (self.deps, ) return func(*new_args, **kwargs) return decorated init.py from backend.dependencyInjection.serviceInjector import ServiceInjector si = ServiceInjector() /core/articleModule.py from backend.core.IarticleModule import IarticleModule from models import Article from backend.__init__ import si @si.register() class articleModule(IarticleModule): def getArticleByLioId(self, lioId: str) -> Article: return Article.objects.get(lioId = lioId) /services/articleManagementService.py from backend.services.IarticleManagementService import IarticleManagementService from backend.models import Article from backend.__init__ import si @si.register() class articleManagementService(IarticleManagementService): @si.inject … -
@apollo/client useLazyQuery .then() triggers even when there's an error (React/graphene-django)
I have a graphene-django backend with a me query that returns an exception: You do not have permission to perform this action if the user is not logged in. From React I'm calling the query like this: const [getMe] = useLazyQuery(ME_QUERY); // query not important React.useEffect(() => { getMe() .then((meRes) => { console.log('Hit the .then()'); if (meRes.data && meRes.data.me) { setUser(meRes.data.me); } }) .catch(() => { console.log('Hit the .catch()'); }); }, []) The response I get from the backend: {"errors":[{"message":"You do not have permission to perform this action","locations":[{"line":2,"column":3}],"path":["me"]}],"data":{"me":null}} I would expect that @apollo/client would recognize this as an error and my console would output Hit the .catch(), but for some reason it's not hitting the catch at all and only outputs Hit the .then(). Why would that response resolve instead of reject in @apollo/client? I only have this issue with queries, not with mutations which work as expected. For instance if I call this mutation: const [createUser, { data, loading, error }] = useMutation(CREATE_USER_MUTATION); createUser({ variables: { email, password1, password2, }, }).then(() => { console.log('this should not be hit'); }); And I receive this response: {"errors":[{"message":"['This password is too short. It must contain at least 8 characters.', 'This password is … -
How to return a random number asynchronously using AJAX and Django
As a beginner I apologize to being not particular as you wish, but hopefully you'll understand my problem. What I am trying to achieve is simply returning a random value every 1.5 seconds without manually refreshing the browser. So far my code looks like this and it works, but I am convinced that my approach is kind of weird and around. Is there any possibilty to have just one function that actually does the same as these two or any cleaner way to achieve this? views.py: def generate_random(request): return render(request, "form.html") def generate_number(request): return HttpResponse(randint(0, 30)) my form.html is: <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> </head> <body onload="getRandomInt();"> <h2 id="result"></h2> <script> function getRandomInt() { setTimeout(function () { $.get("url", function(data, status){ $('#result').html(data); }); getRandomInt(); }, 1500) return false; } </script> </body> and urls.py: urlpatterns = [ path('',generate_random), path('url',generate_number), ] -
Use a related field in lookup_field in Django REST framework
I have a user model and a profile model that is created automatically when a user is registered. In my view for retrieving the user profile, I am trying to get the user profile using the username but DRF uses pk by default. So I added a lookup field with the username but DRF can't seem to resolve it: my profile model: class Profile(TimeStampedModel): user = models.OneToOneField('User', on_delete=models.CASCADE, related_name='customer_profile') bio = models.TextField(blank=True) image = models.URLField(blank=True) def __str__(self): return self.user.username my profile serializer: class ProfileSerializer(serializers.ModelSerializer): username = serializers.StringRelatedField(source='user.username', read_only=True) bio = serializers.CharField(allow_blank=True, allow_null=True) image = serializers.SerializerMethodField() class Meta: model = Profile fields = ['username', 'bio', 'image'] def get_image(self, obj): if obj.image: return obj.image return 'https://static.productionready.io/images/smiley-cyrus.jpg' my profile retrieving view: class ProfileRetrieveAPIView(generics.RetrieveAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'username' def retrive(self, request, username, *args, **kwargs): try: profile = Profile.objects.select_related('user').get( user__username = username ) except Profile.DoesNotExist: ProfileDoesNotExist serializer = self.serializer_class(profile) return Response(serializer.data, status=status.HTTP_200_OK) my profile endpoint: urlpatterns = [ # .... path('profiles/<str:username>', views.ProfileRetrieveAPIView.as_view()), ] I am getting the error: Cannot resolve keyword 'username' into field. Choices are: bio, created_at, id, image, updated_at, user, user_id What am I doing wrong? -
Django debugger vs running From terminal
I'm trying to authenticate a basic django webapp with my firebase cloud db. So the problem is when i login normally providing the appropriate username and password, the login is sucessfull and i get redirected to the home page. But when i run a debugger i get an error saying : Internal Server Error: /login/ Traceback (most recent call last): File "c:\Users\moham\OneDrive\Desktop\Granular\web solution\web_solution\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "c:\Users\moham\OneDrive\Desktop\Granular\web solution\web_solution\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\moham\OneDrive\Desktop\Granular\web solution\Chosen_granular\apps\authentication\views.py", line 26, in login_view if (firebase_authentication(user.email,password)): AttributeError: 'NoneType' object has no attribute 'email' And this is how my login view function looks like. def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if (firebase_authentication(user.email,password)): #user = auth.get_user_by_email(user.email) #request['uid']=user.uid login(request, user) return redirect("/") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "accounts/login.html", {"form": form, "msg": msg}) -
Why is it not showing me the permissions or the group on django?
enter image description here Why is it not showing me the permissions or the group on django? -
Annotate queryset models with fields from "through" model
This seems like it should be easy, but I've been unable to find an answer despite lots of googling. I have two models joined by a many-to-many relationship through a third model that has some additional fields. class User(AbstractUser): pass class Project(models.Model): name = models.CharField(max_length=100, unique=True, blank=False) description = models.CharField(max_length=255, blank=True) users = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='projects', through='UserProject') # additional project fields class UserProject(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) favorite = models.BooleanField(default=False) last_used = models.DateTimeField(default=timezone.now) what I want is to be able to access a given user's projects along with the favorite and last_used fields for that user for each project. I cannot figure out how to do that using annotations or any other method on a call to user.projects. If I call the through relationship directly (i.e., user.userproject_set), I can add fields from the project with a single sql query by calling, e.g., user.userproject_set.select_related('project').annotate(name='project.name'), but then the models in the resulting queryset are UserProjects, not Projects, which is not what I want. Writing a sql query to do what I want would be trivial (it would basically be the same query Django produces to join the Project fields to the UserProject queryset). Is there a way to get … -
nginx, uwsgi, django. uwsgi runs fine as normal user, fails when started by root, even with su -u nonroot
I am trying to get nginx, Django, and uwsgi to work 'as specified' in the docs (well, ok, https://uwsgi.readthedocs.io/en/latest/tutorials/Django_and_nginx.html anyway). Everything works perfectly as long as I start uwsgi as NON-root user. In trying to get past this, I created a little script (the commented-out commands are things I've tested, sorry if they are confusing): #!/bin/bash cd /home/lunchspace/FridayLunch/ uwsgi --ini lunchspace_uswgi.ini #uwsgi --socket /home/lunchspace/lunchspace.sock --module FridayLunches.wsgi #uwsgi --emperor /etc/uwsgi/vassals Running the above as the user 'lunchspace', I get: lunchspace@lunchspace:~/FridayLunch$ ../runuwsgi [uWSGI] getting INI configuration from lunchspace_uswgi.ini *** Starting uWSGI 2.0.20 (64bit) on [Fri Sep 23 19:29:55 2022] *** compiled with version: 7.5.0 on 13 September 2022 22:35:31 os: Linux-4.15.0 #1 SMP Tue Jan 25 12:49:12 MSK 2022 nodename: lunchspace.org machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/lunchspace/FridayLunch detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! chdir() to /home/lunchspace/FridayLunch your processes number limit is 62987 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to UNIX address /home/lunchspace/FridayLunch/lunchspace.sock fd 3 Python version: 3.6.9 (default, Jun 29 … -
How to make multiple urls in django?
Learning django, can't create multithreaded url How to display, for example, the brand of an audi car by url 127.0.0.1:8000/cars_brand/audi/Audi_TTS ? Now it says None I don't know what else to add here, but stackoverflow doesn't skip my question for the reason: It looks like your post is mostly code; please add some more details. views from django.shortcuts import render from django.http import HttpResponse # Create your views here. cars_brand_dict = { "audi": ["Audi_RS_2_Avant", "Audi_A8_W12", "Audi_TTS"], "bmw": ["BMW_M135i_xDrive", "BMW_M240i_xDrive_Coupe", "BMW_M3_Competition"], "volkswagen": ["Volkswagen_Caddy","Volkswagen_Multivan","Volkswagen_Crafter_Pritsche"], } cars_model_dict = { "audi_dict" :{ "Audi_RS_2_Avant": "ссылочка Audi_RS_2_Avant", "Audi_A8_W12": "ссылочка на Audi_A8_W12", "Audi_TTS": "ссылочка на Audi_TTS", }, "bmw_dict" :{ "BMW_M135i_xDrive": "ссылочка на BMW_M135i_xDrive", "BMW_M240i_xDrive_Coupe": "ссылочка на BMW_M240i_xDrive_Coupe", "BMW_M3_Competition": "ссылочка на BMW_M3_Competition", }, "volkswagen_dict" :{ "Volkswagen_Caddy": "ссылочка на Volkswagen_Caddy", "Volkswagen_Multivan": "ссылочка на Volkswagen_Multivan", "Volkswagen_Crafter_Pritsche": "ссылочка на Volkswagen_Crafter_Pritsche", } } def get_info_about_car_brand(request, car_brand): description = cars_brand_dict.get(car_brand, None) return HttpResponse(description) def get_info_about_car_model(request, car_brand, car_model): description = cars_model_dict.get(car_model) return HttpResponse(description) default urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('cars_brand/', include("car_store.urls")), ] my urls from django.urls import path from . import views urlpatterns = [ # path('', admin.site.urls), path('<car_brand>', views.get_info_about_car_brand), path('<car_brand>/<car_model>', views.get_info_about_car_model), ] -
linking JavaScript code to Django database upon clicking on a button
I'm asked to work on a networking website that is like Twitter. I work with HTML,CSS, Javascript for the client-side and Django for the server-side. I'm trying to link between Javascript and Django using JSON and fetch as I want to create a button in each of the users' profile that upon being clicked by the registered user, it makes the registered follow the profile as it is saved in django database as a model containing the follower(follower) and the user followed(following) but upon clicking on follow button (in user.html) it doesn't save any data in the database in models.py: class follow(models.Model): follower = models.ForeignKey("User",on_delete=models.CASCADE, related_name="follower") following = models.ForeignKey("User",on_delete=models.CASCADE, related_name="following") in user.html(contains the script): <html> <head> <script> document.addEventListener('DOMContentLoaded',function(){ document.querySelectorAll('input').forEach(input =>{ input.addEventListener('click', function(){ console.log(input.id); let follow_username = input.id fetch('/follow/'+ follow_id, { method:'PUT', body: JSON.stringify({ follow: true }) }) }) } ) }); </script> </head> <body> <h2>{{x.username}}</h2> <form> {% csrf_token %} <input type="submit" value="follow" name ="follow" id={{x.username}}> </form> </body> </html> in urls.py: from django.urls import path from . import views urlpatterns = [ path("follow/<str:name>", views.Users, name="follow") ] in views.py: def Users(request, name): x = User.objects.get(username = name) if request.method == 'PUT': data = json.loads(request.body) if data.get('follow') is not None: user = request.user … -
Are user provided translations for user provided templates possible with the django template engine?
In my webapp, I'd like to allow users who want to deploy an instance to write their own templates. Specifically, I would like to include a template for a data protection declaration using the include tag and have this point to a location which users can define in their settings. However, this would not be translatable, as all translated strings have to be in django.po and that file is in version control. Is there a way to extend django.po, e.g. use an include statement to point it to a second, user generated translations file, similar to how I can include templates within other templates? -
Importing python file to views and dynamic url
I have a particular function established in a task.py file. I want to create a views file in django which imports task.py file,calls the function,links it to dynamic url and displays output using HttpResponse. I have tried but my server just doesn't run. I'm a beginner. -
Django setting up view to change settings.py one-off settings
I'm nearly done with my Django app and I was wondering if it's to create a custom page where the app user admin will be able to cahnge one-off overall app settings like language, timezone, currency, URL slug, app limits (e.g. Max number of xyz, default abc etc) etc Is this possible? Feel like I'm missing a trick here. Any advice or resoucrces would be great. -
How to use python 'in' operator with generator class queryset results in function?
I need to check if a <class 'str'> value exists in a list generated by queryset. Now, this works perfectly when used in a view. my_string = 'Granny Smith' my_query = Orchard.objects.all().values_list('apples', flat=True).iterator() if my_string in my_query: print('This works ok', type(my_string), type(my_query)) # Print: 'This works ok, <class 'str'>, <class 'generator'> The problem occurs, when I try to pass queryset results as a parameter in a function: def my_function(queryset_data): other_string = 'Granny Smith' if other_string in queryset_data: print('There is Belle de Boskoop in my q results.', type(other_string), type(queryset_data)) Am I passing the queryset results from the view correctly or are class generator values not meant to be used this way? The reason why I am using iterator(): I need a lightning-fast, cache-less query, every delay hurts my app. By using iterator(), there is no repeated query or caching as stated in documentation https://docs.djangoproject.com/en/4.1/ref/models/querysets/#django.db.models.query.QuerySet.iterator. -
Join two models and group with SUM in Django
I have two model name ProductDetails and InventorySummary. I want to join this two model and wants to group with product name and SUM product quantity. The quantity should be multiplication with product price. My models are given bellow: class ProductDetails(models.Model): id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=100, unique=True) purchase_price = models.DecimalField(max_digits=7, decimal_places=2) dealer_price = models.DecimalField(max_digits=7, decimal_places=2) retail_price = models.DecimalField(max_digits=7, decimal_places=2) remarks = models.CharField(max_length=255, blank=True) def __str__(self): return self.product_name class InventorySummary(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(default=date.today) product_name = models.ForeignKey(ProductDetails, on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return str(self.product_name) My views are given bellow: def stockPrice(request): stock = InventorySummary.objects.select_related('product_name'). values('product_name').annotate(quantity=Sum('quantity')) return render(request, 'inventory_price.html', {'stock': stock}) -
django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured
django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'alumni_portal.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Guys can help me to solve this error django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Pattern for develping an extensible application with immutable deployment environment
This is the problem at hand: I'm developing a system that has as one of its core requirements extensibility: there should be the ability to develop plug-ins that extend the core functionalities. The application will provide some core API and developers will be able to write packages and extensions that add features. One thing I'm having issues designing is the following: let's say a plug-in is represented as a folder with a certain structure; how should the plug-in be installed onto the main application? Traditionally, many web apps used to be extensible by means of uploading a plug-in's code to a specific folder inside of the application, with some mechanism for the main application to discover new plug-ins. The way I plan on deploying the application I'm developing is by means of containers: either by writing a Dockerfile for it, or by using Dokku. Both of those ways involve working with a repository and deploying to immutable environments: this makes the idea of adding code to a folder problematic because that code would be versioned and would change the repository, which is not what I want because adding a plug-in shouldn't be something that alters the codebase in my opinion. … -
register redirect home python django
Can anyone explain why my code does not redirect me to home.html after successful registration? I'm creating custom login and registration forms. Let me know if there is more code you need to see. ``` from django.shortcuts import render, redirect from django.views.generic import TemplateView, CreateView from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.contrib import messages from .forms import JoinForm class HomeView(TemplateView): template_name = "home.html" class JoinView(TemplateView): template_name = "registration/join.html" def join(request): if request.method == "POST": form = JoinForm(request.POST or None) if form.is_vaild(): form.save() return render(request, 'home') else: return render(request, 'join') class LoginView(TemplateView): template_name = "login.html" ``` -
Group send a channel layer from outside consumer class
I have a process that when it gets a message it sends a command to a celery process. From there I would want to send back a message from the celery worker back to the backend telling it "Im done now you can continue". So can I send a group message to a channel layer from outside -
How to log INFO logs in settings.py
I'm trying to log some info messages specifically in django settings.py. I'm following the first example in the django documentation that shows a simple configuration. The only thing I changed was having the log show INFO level messages. When I run python manage.py runserver, the log statement is never shown. The logs are only shown for WARNING level or above (more critical). Here is my configuration that is located in settings.py import logging ... LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, '': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True }, } ... def do_something(): logger.info('Doing Something') do_something() Note I'm trying to log statements only in my settings.py file as of right now. -
Unable to fetch user details by an id given in a JSON string | Getting a Type error in Django
I am trying to get a user's details (in a JSON string format) by providing a user id (also in a JSON string format) This is my model's code class Description(models.Model): description = models.CharField(max_length=150) def __str__(self): return self.description class Team(models.Model): team_name = models.CharField(max_length=50) description = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.team_name class User(models.Model): name = models.CharField(max_length=64) username = models.CharField(max_length=64, unique=True) description = models.ForeignKey(Description, null=True, on_delete=models.SET_NULL) team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name}" This is the serializer Code from rest_framework import serializers from users.models import Description, Team, User class DescriptionSerializer(serializers.ModelSerializer): class Meta: model = Description fields = "__all__" class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = "__all__" class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" This is the views code from urllib import response from django.shortcuts import render from django.http import JsonResponse from rest_framework.response import Response from rest_framework.decorators import api_view from users.models import User, Team, Description from .serializers import UserSerializer, TeamSerializer, DescriptionSerializer # describe user @api_view(["GET"]) def describe_user(request): user = User.objects.get(pk=request.data["id"]) serializer = UserSerializer(user) return JsonResponse(serializer, safe=False) Whenever I enter a JSON data in the body of URL eg: {"id":"2"} I get this error [TypeError at /describe/ Object of type UserSerializer …