Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can we use class as view in django?
view.py class myapp(): def index(self): return redirect(someusrl) def productview(self): return redirect(someusrl) urls.py path('', myapp.index, name="home"), path('product', myapp.productview, name="Product_page") like this way thanks in advance :) -
django + chart.js: page language switch button mess up the charts. What?
I am having a super strange issue in my django app that renders graphs with chart js. I used i18n to handle the translation but after spending hours trying to fix my charts, I found out that when language is english the chart work well but when another language is selected, then it either dont work or show messed up values. I don't even know what code to include since I can't figure out how lanaguage and the chart.js are related. Has someone had the same issue before? Or any clue how this could come from? -
ModelForm is not being saved, database fields are empty
i made ModelForm for booking. When i pass the data to the form, no errors are being shown and i think it is being executed successfully. But when i check the database nothing is being saved. here is my code. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): choice_field = ("site 1", "site 1"), ("site 2", "site 2"), ("site 3", "site 3") visitdate = models.DateTimeField(default=timezone.now) visittime = models.TimeField(default=timezone.now) reason = models.TextField() poc = models.CharField(max_length=50) site = models.CharField(max_length=6, choices=choice_field) slug = models.SlugField(unique_for_date=timezone.now) form.py class booking(forms.ModelForm): choice_field = ("site 1", "site 1"), ("site 2", "site 2"), ("site 3", "site 3") visitdate = forms.DateTimeField(required=True) visittime = forms.TimeField(required=True) reason = forms.CharField(widget=forms.Textarea, required=True) poc = forms.CharField(max_length=50) site = forms.MultipleChoiceField(choices=choice_field, widget=forms.NullBooleanSelect) class Meta: model = Post fields = ("visitdate", "visittime", "reason", "poc", "site",) views.py @login_required def dashboard(request): lu = request.user form = booking() if request.method == "POST": form = booking(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return render(request, 'account/dashboard.html', {'lu':lu, 'booking': form}) dashboard.html <form method="POST"> {%csrf_token%} <div class="ff"> <div align='center'> <select class="selector" {{booking.site}}</select> </div> <br> <div align='center'> <input type="date" class="datetime" placeholder="Date" {{booking.visitdate}} <input type="time" class="datetime" placeholder="Time" {{booking.visittime}} </div> <br> <input type="text" class="credentials" placeholder="Point of Contact" {{booking.poc}} … -
format method does not assign values to a string when importing as global variable
I defined some variables inside a file named queries.py and import them inside another file named views.py. The problem is python format does not assign values of each variable to the corresponding placeholder. Consider following lines of code : queries.py main_where_query = ''' where users.deleted_account is null and length(users.phone_number) > 2 and length(users.phone_number) < 20 and users.phone_number not like '+98888888%' ''' messages_where_query = """{0} and messages.date>'{1}' and messages.date<'{2}' """ views.py from .queries import * def get_activity(request): global main_where_query global messages_where_query messages_where_query.format(main_where_query, str(start_date), str(end_date)) .... and the output is : select count(messages.message_id) from messages join users on users.id = messages.sender {0} and messages.date>'{1}' and messages.date<'{2}' and messages.media_type = 0 As you can see all the placeholders are untouched like {0} {1} {2}.I'm sure that those variables are not empty and imported correctly. -
Django rest framework filter not working. Always giving full queryset or data on any filrer query
I making a filter API but no matter what filter I apply it doesn't give me any result. class filter_dataset(ListCreateAPIView): filter_class = ProductFilter serializer_class = AdjustDatasetSerializers filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('revenue', 'spend', 'OS', 'date') def get_queryset(self): dataset = Dataset.objects.all() return dataset def get(self, request): dataset = self.get_queryset() serializer = self.serializer_class(dataset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) models: from django.db import models class Dataset(models.Model): date = models.DateTimeField(max_length=255,auto_now_add=True) channel = models.CharField(max_length=255,null=True, blank=True) OS = models.CharField(max_length=255,null=True, blank=True) impressions = models.CharField(max_length=255,null=True, blank=True) clicks = models.CharField(max_length=255,null=True, blank=True) installs = models.CharField(max_length=255,null=True, blank=True) spend = models.CharField(max_length=255,null=True, blank=True) revenue = models.CharField(max_length=255,null=True, blank=True) Filter class: class ProductFilter(filters.FilterSet): revenue = filters.NumberFilter(field_name="revenue") spend = filters.NumberFilter(field_name="spend") OS = filters.CharFilter(field_name='OS', lookup_expr='OS__exact') date = filters.DateFromToRangeFilter(field_name='date') class Meta: model = Dataset fields = ['revenue', 'spend', 'OS', 'date'] On django rest framework filter fields are showing but no matter what you enter in field this is not giving any results. All was all the data is shown. I'm stuck on this, any help would be needful. -
Class XXX missing "Meta.model" attribute
I Trying get list of objects using DRF, But Getting Error like "missing "Meta.model attribute" Serialzers.py from rest_framework import serializers from .models import Car class CarSerializer(serializers.ModelSerializer): class Meta: model: Car fields=['brand_name','model_name','car_color'] Views.py Code Below: from app2.serializers import CarSerializer from rest_framework import generics class BrandList(generics.ListCreateAPIView): queryset = Brand.objects.all() serializer_class = CarSerializer URLS.py: from app2.views import ,BrandList path("BrandList/", BrandList.as_view(), name="BrandList"), Please someone get out from this -
In what order does celery process tasks when it is configured to use multiple queues?
If I run celery so that it consumes from multiple queues, what order will it process tasks? Given the following startup: celery worker -A app --concurrency=4 --pool=prefork -Ofair --queues=default,lowpriority,highpriority If 1000 tasks get added to the default queue, then 1000 tasks are added to the lowpriority queue, then 1000 tasks are added to the highpriority, in what order are those tasks processed? I think they will be processed in an approximate arrival order: 1000 from default, then 1000 from lowpriority, then 1000 from highpriority. What I would like to happen is a round robin processing style: 1 from default, 1 from lowpriority, 1 from highpriority ... I am aware of Task Priorities but would prefer to avoid them at this stage, because that is a larger migration that requires more planning. Can I get celery to process tasks from multiple queues in a round-robin style? -
Django ORM group by calculation should return data if the foreign have no related data too
This is my models: class Purchase(models.Model): amount = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) entry_for = models.ForeignKey( User, on_delete=models.CASCADE, related_name='ledger_entry_for', ) For example, i have 400+ users but only 50 users have purchased multiple time So i want total purchase amount user by user. so this is my query is below: purchase_user_wise = Purchase.objects.values( 'entry_for' ).annotate( total_purchase=Sum('amount') ) Above query works nice and I return total amount user by user but the problem is: it only return those users calculation who have purchased at least one time or more than one time. and this query not returning all 400 users data. I want, if any of the users don't have any purchase entry, it should return 0 and rest of the calculation should be works that way. Can anyone help me how can i do it? -
What is the most efficient way to create a lobby django
I am trying to create a lobby that would be accessible by a link game/gameID. What i have is just a simple field in my db playerNumber = models.IntegerField(default =0). When user is connected i increment playerNumber by 1. When the player number is 2 i just render error page. But when user closes game page by some mistake, someone else can join instead of him. How would i make this page IP specific or somehow reserve the page for only 2 users and make them able to come back if they left. -
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 %}