Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the default zoom level of a map in Geodjango's admin?
I've been looking into GeoDjango recently, I'm struggling to customize the default zoom level of the openstreet map displaying in my admin section. Below is what I have tried but with no effect, please assist. from django.contrib import admin from django.contrib.gis import admin class LocationAdmin(admin.OSMGeoAdmin): default_zoom = 5 -
Django - Redirect uppercase urls to lowercase
In my Django apps, I have many urls including /(?P<project_name>[_\w]+)/. The project_name is defined by users and it is an attribute of the Project model. I've added a validator on the project_name to check if it's lowercase. So new names are all lowercase but some old names include uppercase characters. I would like to change all the names stored to make them lowercase but at the same time, I don't want users to get an error when trying to access to one of the url with the old project name including uppercase characters. As I have many urls and many views, I don't want to update each to manually .lower() the project_name. Is there a way to redirect all urls including /<project_NAME>/ to /<project_name>/? -
How to use Prepend_WWW in DJango
I am facing issues in a project, my site opens with www, but doesn't load if that part is missing. I read about PREPEND_WWW= True (since if user types just domain, redirect to www.domain.com which works) in settings.py on django, but that just doesn't work. I have enabled CommonMiddleware too. Any other thing that can be done to solve?. Please help -
How to change a form dynamically?
I have two models, Company andEmployee. I would like that when the user selected the company, the employee data would be set dynamically in the employee form because both forms will be shown on the same page. So initially on the page I have the form to select the company and immediately after the selection the data of the employees linked to the company appear to the user. I made the forms like this: class CompanyForm(ModelForm): class Meta: model = Company fields = ['nome'] class EmployeeForm(ModelForm): class Meta: model = Employee fields = ['nome'] def __init__(self, *args, **kwargs): super(EmployeeForm, self).__init__(*args, **kwargs) self.fields['nome'].queryset = Employee.objects.filter(company = CompanyForm.cleaned_data.get('nome')) But I get the following error: 'CompanyForm' object has no attribute 'get' Is it possible to change one form immediately when the other is changed (on the same page) without submitting to Django? -
Http request between two containers
I am creating a web service which uses react for the frontend and django REST for the backend. Both are running in separate docker containers. My docker-compose file looks like this. services: db: image: postgres volumes: - ./config/load.sql:/docker-entrypoint-initdb.d/init.sql environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . image: gudmundurorri4/hoss-web command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code stdin_open: true ports: - "8000:8000" depends_on: - db frontend: image: gudmundurorri4/hoss-frontend stdin_open: true ports: - "3000:3000" depends_on: - "web" Both the web and frontend containers work fine. The backend works when I open it in the browser and when I execute a get request to http://web:8000 from within the frontend container I get the correct response. However when I execute a GET request from my react app using the same address (http://web:8000) it always fails with the error net::ERR_NAME_NOT_RESOLVED -
pyttsx3 in Django
This code works on python shell but doesn't work on localhost The main purpose of code is, to make application say 'hi' every second in python from time import sleep import pyttsx3 engine = pyttsx3.init() def say(text): engine.say(text) engine.runAndWait() def runAfter(function): def wrapper(): while True: function() sleep(1) return wrapper @runAfter def sayHi(): arg = 'hi' print(f'say({arg})') say(arg) sayHi() in django @runAfter def sayHi(): arg = 'hi' print(f'say({arg})') say(arg) def test(responce): sayHi() return HttpResponse('<h1>test</h1>') in django it says 'hi' once -
Django give Error 500 for all static files like CSS and Images, when DUGUB is FLASE
I've tried different solutions already posted by users, but they didn't work for me. settings.py of Project BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False ALLOWED_HOSTS = ["*"] STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] STATIC_ROOT=os.path.join(BASE_DIR,'assets') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') All my CSS files are in style folder inside the static folder. And all images are in the media folder. Browser Consol Logs Refused to apply style from 'http://127.0.0.1:8000/static/styles/LandingPage_CSS.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. icons8-user-48.png:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) Doorakart%20icon.png:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) apple.jpg:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) banana.jpg:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) watermelon.jpg:1 . . . Failed to load resource: the server responded with a status of 500 (Internal Server Error) Refused to apply style from 'http://127.0.0.1:8000/static/styles/LandingPage_CSS.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Example of HTML file {% load static … -
Django Form Modification with populated value set
I have a problem with this Lead Form. When the user create a lead, he assigns it to a customer. I got the list of customers from the init that retrieve the user associates and build the customers list for my user and his associate. This works fine during the lead CREATION. Unfortunately, when the user wants to edit the lead, I can see the customer id in the pre-loaded form from the lead instance, but it is not pre-selected on the screen. my class LeadForm class LeadForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(LeadForm, self).__init__(*args, **kwargs) userutils = UserUtilities() associated_users = userutils.get_associated_users_for_customer_module(self.user) self.fields['customer'].queryset = Customer.objects.filter(creator__in=associated_users) team_members = userutils.get_associated_users(self.user) self.fields['assignee'].queryset = team_members customer = forms.ModelChoiceField( queryset=None, label="Customer Email", required=True, widget=forms.Select(attrs={'class': 'form-control select2 select2-container--custom', 'style': 'width:20%'})) and here it is what I obtain instead of the existing customer -
Audio not playing in django template
I am trying to build a audio player with a django backend.The front end is made with javascipt and html5.IT works on its own but the audio wont play with django.Here's my code. My app/models.py:- from django.db import models # Create your models here. class song_thumb(models.Model): artist=models.CharField(max_length=100,null=True) song_title=models.CharField(max_length=100,null=True) album=models.CharField(max_length=100,null=True) song_duration=models.FloatField(null=True) img=models.ImageField(upload_to='pics',null=True) song=models.FileField(upload_to='media',null=True) my views.py:- from django.shortcuts import render from .models import song_thumb # Create your views here. def songs(request): artist1=song_thumb() artist1.artist='Alcest' artist1.song_title='Kodama' artist1.album='Kodama' artist1.song_duration='9.10' artist1.img='kodama.jpg' artist1.song='Kodama.mp3' artist2=song_thumb() artist2.artist='Tash Sultana' artist2.song_title='Jungle' artist2.album='Jungle' artist2.song_duration='5.17' artist2.img='jungle.jpg' artist2.song='Jungle.mp3' artist3=song_thumb() artist3.artist='Animals as leaders' artist3.song_title='Cafo' artist3.album='Cafo' artist3.song_duration='6.56' artist3.img='cafo.jpg' artist3.song='Cafo.mp3' artists=[artist1,artist2,artist3] return render(request, 'home.html', {'artists':artists}) my template:- <div class="data-content"> {% for artist in artists %} <div id="img-1" class="tabcontent"> <div class="blog-content"> <div class="row"> <div class="col-3"> <div class="img"> <img class="img-thumbnail" src="{{baseurl}}/{{artist.img}}" alt=""> </div> </div> </div> <div class="title"> <p> {{artist.artist}} </p><br> <p>{{artist.song_title}}</p><br> <p>{{artist.album}}</p><br> <p>{{artist.song_duration}}</p><br> <audio id="myAudio"> <source src="E:\coding\fyp\music\assests\media\Kodama" type="audio/ogg"> <source src={{artist.song}} type="audio/mpeg"> Your browser does not support the audio element. </audio> <p>Click the buttons to play or pause the audio.</p> <button onclick="playAudio()" type="button">Play Audio</button> <button onclick="pauseAudio()" type="button">Pause Audio</button> <script src="{% static 'assests/js/home.js' %}"></script> </div> <span>Close</span> </div> </div> {% endfor %} </div> I have added media_root and media_url.The MEDIA_ROOT=os.path.join(BASE_DIR,'media') and i've saved the audio files in a folder called media inside … -
chatbot from CLI to GUI in python
Hello as newbie i am trying chatbotai module in python [1]: https://pypi.org/project/chatbotAI/ which gets result in CLI prompt i want it to get in html page like a proper chatbot i tried many things didn't work any solutions? from chatbot import Chat, register_call import wikipedia @register_call("whoIs") def who_is(query,session_id="general"): try: return wikipedia.summary(query) except Exception: for new_query in wikipedia.search(query): try: return wikipedia.summary(new_query) except Exception: pass return "I don't know about "+query first_question="Hi, how are you?" Chat("examples/Example.template").converse(first_question) examples/Example.template {% block %} {% client %}(Do you know about|what is|who is|tell me about) (?P<query>.*){% endclient %} {% response %}{% call whoIs: %query %}{% endresponse %} {% endblock %} -
How to connect User profile view with user posts/twitts view?
I have a problem. How should I connect my profile.html to the user_twitt_list.html? accounts.models User = settings.AUTH_USER_MODEL class ProfileManager(models.Manager): def toggle_follow(self, request_user, username_to_toggle): profile_ = Profile.objects.get(user__username__iexact = username_to_toggle) user = request_user is_following=False if user in profile_.followers.all(): profile_.followers.remove(user) else: profile_.followers.add(user) is_following=True return profile_, is_following class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #user.profile followers = models.ManyToManyField(User, related_name='is_following', blank=True) activated = models.BooleanField(default=False) profile_pic = models.ImageField(default='default.png', upload_to='profile_pics',blank=True) date = models.DateTimeField(auto_now_add=True) objects = ProfileManager() def __str__(self): return self.user.username def post_save_user_receiver(sender, instance, created, *args, **kwargs): if created: profile, is_created = Profile.objects.get_or_create(user = instance) post_save.connect(post_save_user_receiver, sender=User) blog.models User = get_user_model() class Twitt(models.Model): author = models.ForeignKey(User, related_name="twitts", on_delete=models.CASCADE) text = models.TextField(max_length=280) publish_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.text[:10] def get_absolute_url(self): return reverse("test") User all twitts view: class UserTwitt(generic.ListView): model = models.Twitt template_name = 'blog/user_twitt_list.html' def get_queryset(self): twitt_user = get_object_or_404(User, username=self.kwargs.get('username')) return models.Twitt.objects.filter(author=twitt_user).order_by('-publish_date') User profile view: class ProfileDetailView(generic.DetailView): template_name = 'blog/profile.html' def get_object(self): username = self.kwargs.get('username') if username is None: raise Http404 return get_object_or_404(User, username__iexact = username, is_active=True) def get_context_data(self, *args, **kwargs): context = super(ProfileDetailView, self).get_context_data(*args, **kwargs) user = context['user'] is_following = False if user.profile in self.request.user.is_following.all(): is_following = True context['is_following'] = is_following return context Now when I open user_twitt_list.html I can see all twitts, but when I open profile.html … -
django foreign key cannot be null
I am a beginner to django and trying to create a post request on django rest-framework. I have a following model: class ProjectScheme(models.Model): name = models.CharField(max_length=250, blank=False,null=False) parent_scheme_id = models.ForeignKey(ProjectSchemeMaster, on_delete = models.CASCADE) rule = models.TextField(blank=True) def __str__(self): return str(self.name) And a serializer: class SchemeDetailSerializer(serializers.ModelSerializer): class Meta: model = ProjectScheme fields = ('id', 'name', 'parent_scheme_id', 'rule') depth=1 And my view: @api_view(['POST']) @renderer_classes((JSONRenderer,)) def create_project_scheme(request): if request.method == 'POST': data = JSONParser().parse(request) serializer = SchemeDetailSerializer(data=data) comp_logger.info('Call to create_project') if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response({'response':serializer.errors}) return Response({}) With post request body as: { "name": "django-rf" } This gives serializer.is_valid() to true, but in response I get (1048, "Column 'parent_scheme_id_id' cannot be null") I tried adding parent_scheme_id = models.ForeignKey(ProjectSchemeMaster, on_delete = models.CASCADE, blank=False, null=False) but that didn't make any difference. How can I validate the request input so that it shows proper validation message like for name field? -
Returning a user with a list of the groups he belongs to in Django Rest API
I'm writing an API and I want to return a list of users along with the groups each user belongs to. I'm fairly new to Django and I'm stuck. I've tried several ways but the closest I came to finding a solution is when Django returned auth.Group.none while the user is in a Group. authentication/models.py class CustomUser(AbstractUser): role = models.CharField(blank=True, max_length=120) authentication/views.py class CustomUserView(APIView): permission_classes = [IsAuthenticated, IsAdmin, ] serializer_class = CustomUserSerializer def get(self, request, format='json'): queryset = CustomUser.objects.all() serializer = CustomUserSerializer(queryset, many=True) filterset_fields = ['id', 'name', 'email', 'groups'] return Response(serializer.data, status=status.HTTP_200_OK) authentication/serializers.py class CustomUserSerializer(serializers.ModelSerializer): email = serializers.CharField( required=True ) username = serializers.CharField(required=True) password = serializers.CharField(min_length=8, write_only=True) first_name = serializers.CharField() last_name = serializers.CharField() groups = serializers.CharField() role = serializers.CharField() class Meta: model = CustomUser fields = ('id', 'email', 'username', 'first_name', 'last_name', 'password', 'groups', 'role') extra_kwargs = {'password': {'write_only': True}} JSON Output { "id": 4, "email": "", "username": "testuser", "first_name": "", "last_name": "", "groups": "auth.Group.None" } Any input would be appreciated! Thanks in advance. -
Django Translation using BlockTrans tag in template
I have a translation problem in template. This works fine and translating to current active language. {% load i18n %} {% blocktrans %}Your dashboard login otp is.{% endblocktrans %} But when I add context variable in text like: {% load i18n %} {% blocktrans %}Your dashboard login otp is {{otp}}.{% endblocktrans %} Then the translation won't work. I'm rendering the above txt file using get_template render function in Django. My .po file: msgid "Your dashboard login otp is {otp}." msgstr "आपका डैशबोर्ड लॉगिन otp {otp} है।" Any help would be appreciated. -
Give specific permission per user when signing up
I am using allauth for registering users and I would like to give permissions to users automatically after they created a local account or using social login. A good example would be only 1 user to be able to create posts and comments whilst the rest of the users to be able to only create comments. Looking around I have seen that you can create Groups and through those you can give certain permissions, is this the right way to handle this? Or are there some better avenues worth exploring? Many thanks. -
Is there a way to hide a button on every page except Home page of a site in Django?
{% if user.is_authenticated %} {% endif %} Django Girls Blog {% if user.is_anonymous %} LogIn {% endif %} {% if user.is_authenticated %} {% endif %} {% if user.is_authenticated %} {{ user }} LogOut> {% endif %} -
How to properly run Django dev server locally for testing form another device in the network
I'm trying to run a local dev server on Django using the command python manage.py runserver 0.0.0.0:5000 but it takes very long time loading whenever I try to open it, and in the cmd, it shows this error An established connection was aborted by the software in your host machine Note Using Postgresql as a database. Traceback Exception happened during processing of request from ('127.0.0.1', 53334) Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
Django get data from second model filtered by values from the first
I have this little model: class Event(models.Model): # The Category table name that inherits models.Model name = models.TextField(blank=True) #Like a varchar desc = models.TextField(blank=True) #Like a varchar address = models.TextField(blank=True) date = models.DateField(default=timezone.now) reservation_date = models.DateField() event_participant = models.IntegerField(blank=False,default=0) class Reservation(models.Model): # The Category table name that inherits models.Model event_id = models.ForeignKey(Event, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) When I list all my events, I wan to calculate the rest of possible participant. So I tried it at my view: def events_list(request): events = Event.objects.all().order_by('date') #I started here for event in events: obj = Reservation.objects.filter(event_id=event) return render(request, 'events_list.html', {'events': events, 'obj': obj}) But the obj is empty. Or is there a better way to calculate the participant (participant - quantity)? Thanks -
Want to ask about web hosting
I'm currently working on a project. It's a website built with Python Django and Firebase. Expecting 2000+ registered users and around 400/500 concurrent users access to the site at once. What options do I have? I currently has a GCP account with 275USD Trial Credits left. The site will be hosted for around 2-3weeks. and should I use App Engine or Compute Engine to host the site? -
What is the different user type in django
I have a task in django to create a 1.superuser 2. admin user 3.user . The task is to create test for users , superuser will give authority to admin users to check the answer given to user. How can i implement in django? -
Django, is it possible to have a formset factory with two ForeingKey?
How can I set two ForeignKey in a inline formset factory? I have created an inline formset factory utilizing two models: Lavorazione and Costi_materiale. class Lavorazione(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, ) numero_lavorazione=models.IntegerField() class Costi_materiale(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali) numero_lavorazione=models.ForeignKey(Lavorazione) prezzo=models.DecimalField() After I have created the inline formset facotry as the following: CostiMaterialeFormSet = inlineformset_factory( Lavorazione, Costi_materiale, form=CostiMaterialeForm, fields="__all__", exclude=('codice_commessa',), can_delete=True, extra=1 ) But I have in Costi_materiale two ForeignKey, instead in the form the formset recognise only numero_lavorazione and not also codice_commesse. I want that the formset set in the first model the codice commesse and lavorazione fields and subsequently in the inline formset the other fields. -
Not Understood an Aspect of Django
So you see I'm learning the basics of Django from a course on YouTube by Rafeh Qazi. In that course we were making a polls application following the Django at a glace documentation. So on the third video we talked about something called Namespacing URL names. And I didn't quit understand it. Can anyone please tell me about it You See here is how the tree view of my project look like: ## Django Crash Course ## -> ### mysite ### > folder: _pycache_ > __init__.py > asgi.py > settings.py > urls.py > wsgi.py -> ### polls ### > folder: _pycache_ > folder: migrations > folder: templates > folder: polls > index.html > detail.html > __init__.py > admin.py > apps.py > models.py > test.py > urls.py > views.py > .gitignore > db.sqlite > manage.py I may not be able to show you the images of my code I can take you there: follow this link: My Github project -
How to add nested json
class activitySerializere(serializers.ModelSerializer): class Meta: model=ActivityPeriods fields = ['members_id','start_time','end_time'] class membersSerializere(serializers.ModelSerializer): activity = activitySerializere(many=True,read_only=True) class Meta: model=Members fields = ['id','real_name','tz','activity'] depth = 1 -
How to validate local running Json data in javascript?
Firstly, I am doing the quiz app using the Django. And I have retrieved the questions, options from the DB using views.py. Next I need to validate the user given answer and correct answer which is already stored in the DB. On click it need to change the red or green based on the answer. So here I have stucked : Using Django rest framework I have created the API . (127.0.0.1:8000/api/) Actually in every JavaScript quizzes there are taking the temparory variable and storing the questions and validating them . But here I have taken the questions in the DB and already so How to validate the answers my taking that json into the JS file and how to display the file. Can anyone please right the js file for the Model which I will share the code here. Models.py:- from django.db import models # Create your models here. class Quiz(models.Model): slug = models.SlugField(max_length =200) question = models.CharField(max_length=200) option1 = models.CharField(max_length=200) option2 = models.CharField(max_length=200) option3 = models.CharField(max_length=200) option4 = models.CharField(max_length=200) correct_answer = models.CharField(max_length = 200) views.py:- from django.shortcuts import render, redirect, get_object_or_404 from django.http import JsonResponse from django.utils import timezone from .models import Quiz from rest_framework import generics from … -
how can I reduce database hints in Django ORM?
I have some Models: F ---> D ---> C <--- B ---> A class A: - class B: a = ForeignKey c = ForeignKey class C: - class D: c = ForeignKey class F: d = ForeignKey and I'm using this query: querset = B.objects.select_related('c').filter(a=a_instance) to show result in template: {% for b in querset %} {% for d in b.c.d_set.all %} {% for f in d.f_set.all %} {% endfor %} {% endfor %} {% endfor %} how can I reduce database hints? is it ok to use Prefetch like this or am I wrong? querset = B.objects.select_related( 'c' ).prefetch_related( Prefetch('c__d_set__f_set') ).filter( a=a_instance ) django = 2.2 thanks