Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why user date joined is shifted
I am creating a website with django and when I try to create a user I see that his date joined is shifted by one hour. For instance if I create a user at 2020-03-02 20:58:56 I see in my database that the date_joined of the user is 2020-03-02 19:58:56 in my settings.py I have USE_TZ set to True: LANGUAGE_CODE = 'en' TIME_ZONE = 'Europe/Paris' USE_TZ = True Why I have this shifted time and how to fix this ? -
Django TypeError: __init__() got an unexpected keyword argument 'attrs'
I'm trying to make a connection form, but I get this error : TypeError: init() got an unexpected keyword argument 'attrs' form : from django import forms class Connection(forms.Form): username_connection = forms.EmailField(label = None, max_length=80, widget=forms.EmailField(attrs={'class': "modal-input-placement-homepage"})) password_connection = forms.PasswordInput(label = None, max_length=80, widget=forms.PasswordInput(attrs={'class': "modal-input-placement-homepage"})) first_name_signin = forms.CharField(label = None, max_length=80, widget=forms.TextInput(attrs={'class': "modal-input-placement-homepage"})) last_name_signin = forms.CharField(label = None, max_length=80, widget=forms.TextInput(attrs={'class': "modal-input-placement-homepage"})) artist_name_signin = forms.CharField(label = None, max_length=80, widget=forms.TextInput(attrs={'class': "modal-input-placement-homepage"})) email_signin = forms.EmailField(label = None, widget = forms.EmailField(attrs={'class': "modal-input-placement-homepage"})) password1_signin = forms.PasswordInput(label = None, max_length=80, widget=forms.PasswordInput(attrs={'class': "modal-input-placement-homepage"})) password2_signin = forms.PasswordInput(label = None, max_length=80, widget=forms.PasswordInput(attrs={'class': "modal-input-placement-homepage"})) -
Python 'NoneType' TypeError when trying to access dictionary data
I'm using Spotify's API through Spotipy, and trying to get the name of a track. I've used the API with Javascript a fair amount, and had no issues trying to do essentially this same thing, and I've come up against a wall here. Basically, I get the tracks of a given playlist using this endpoint: https://developer.spotify.com/documentation/web-api/reference/playlists/get-playlists-tracks/, and I am trying to extract the names of the tracks. This will output the 'track object' of a given track: playlist_items = spotify.playlist_tracks(playlist_nameid[playlist])['items'] for item in playlist_items: track_object = item['track'] Here's a picture of the output of the above code I know I'm overwriting the track_object, I've just stripped it down for testing. If I try track_object = item['track']['name'] I get the error TypeError at /radio/login 'NoneType' object is not subscriptable To make sure item['track'] is a subscriptable object, I tried type(item['track']), and the output was {}. I'm quite confused at this point, because the error seems to be telling me the dictionary object is of type 'none'. Any help would be greatly appreciated. -
Django 3 models.Q - app_lable gets displayed inside html
since I upgraded to Django 3.x I have a strage behaviour. Imaging the following field at your models.py content_type = models.ForeignKey(ContentType, limit_choices_to=filter_choice, on_delete=models.CASCADE, null=True, blank=True) which refers to: filter_choice = models.Q(app_label='App', model='model_x') | models.Q(app_label='App', model='model_y') If I now display the content_type field on my html templates it look like this: "App| Model Y" which looks quite stupid, same goes for Django admin. Is this a Bug? I'm asking because on Django 2.2.7 (Latest version of 2.x) I dont had this behaviour and only model_x and model_y have been displayed as expected. Would be awesome if only model_x and model_y getting displayd without there app lables. Is there any solution for this, maybe a new option that comes with django 3.x? Thanks in advance :) -
how to create client account id from another user type
hi I trying to implement multiple user type in django , I have one-to-one relation between the account model and the client model it's not working the , I don't know how to get the user from the Account user to the Client user I got this error('Client' object has no attribute 'id') any solution, please. models.py : class AccountManager(BaseUserManager): def create_user(self,email,full_name=None,password=None , is_active=True,is_staff=False,is_admin=False): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') if not password: raise ValueError('Users must have an password ') user_object = self.model( email=self.normalize_email(email), full_name=full_name, ) user_object.set_password(password) user_object.staff =is_staff user_object.admin = is_admin user_object.active = is_active user_object.save(using=self._db) return user_object def create_client(self,salary,email,password,full_name=None): user = self.create_user( email, full_name=full_name, password=password, ) user.save(using=self._db) return user def create_staffuser(self, email,e, password,full_name=None): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, full_name =full_name, password=password, is_staff=True ) user.save(using=self._db) return user def create_superuser(self, email, password,full_name=None): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, full_name = full_name, password=password, is_staff = True, is_admin = True, ) user.save(using=self._db) return user class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255,unique=True) full_name = … -
Sending notification to specific users in Django
I am kinda stuck while I am working on a Django project (creating and scheduling a meeting). I need your help! For the project, I want to send notification (likely pop-up one since I am not implementing email when registering) to users that were selected by the meeting creator. They will receive the notification when they first log in. I have looked at messaging frameworks of Django but it seems like they don't have the method that I am looking for. I am also very new to Django so I really need your help! Any suggestions would be appreciated! -
How to multiply user input in Django
i want to create simple view that takes user input(a number) and renders on other page this number multiplied by 2. my code: views.py def multiply(request): if request.method == 'POST': data = request.POST.get("decimalfield") twice = data * 2 return render(request, 'multiply.html', twice) input.html <form method="POST" action="{% url 'input' %}"> <input type="text" name="decimalfield"> <button type="submit">Upload text</button> </form> My problem is this is not working, now i get error: The view .views.multiply didn't return an HttpResponse object. It returned None instead. My second problem is i don't know how to render that result on second page, not on this same. Should urls look another like mine? urls.py path('input', views.multiply, name='input'), path('multiply', views.multiply, name='multiply'), I am really dejected because this is so simple and i am not able to do it. -
Django-tables2 add html attribute to column
I have an Imagefield in a model, in my table that field is displayed as a link but when you click on it, it directs to a the url and instead I want to do download it. I foud that in html you can add the "download" attribute like this: <a href="/media/pictures/CFE.JPG" download></a> so in my django-tables2: tables.py class PagosDetailTable(tables.Table): imagen = tables.Column( attrs={"td": {"href": "download"}}) class Meta: model = Pagos template_name = "django_tables2/bootstrap-responsive.html" fields = ('carro', 'semana', 'fecha', 'pago', 'imagen') attrs = {"class": "table table-hover table-sm"} but that it overrides the href: <a href="download"></a> is there a way to append the download attribute using the tables.Column? -
Django: How to handle special chars in order_by
I need to order a django queryset by a list of columns. Some of them contain the minus char like IP-A. Now Django complains about invalid argument(s). What is the right way to handle columns with those chars? Renaming the columns is not an option, as the model is fix. -
How enable cors for html files?
I'm using cloudfront to distribute my static files from S3 bucket. I'm using django as my backend. I configurated my cloudfront to get my static files from my S3 bucket. For images and css and js files works well. But for html files is getting this error: Access to XMLHttpRequest at 'https://xxxxxxxx.cloudfront.net/static/partials/main.html?v=e720c74cfb39a5d17a1f5b4d75a496df30620a5c' from origin 'https://www.xxxxxxx.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. But the problem is my others files are download normally, why my html files are getting these erros. I have django-cors-headers==1.1.0 installed in my pip, and i enable all CORS_ORIGIN_ALLOW_ALL = True. But still getting the error. -
Converting base64 to .jpg file, then saving in Django database
def upload_image(request): if request.is_ajax and request.POST: image = request.POST.get('image') image_name = request.POST.get('image_name') imgdata = base64.b64decode(image + '==') extension = image_name.split('.')[1].lower() image_name = '{}_{}_profile_image.{}'.format(request.user.first_name, request.user.last_name, extension) with open(image_name, "wb") as image_file: image_file.write(imgdata) upload = ProfileImage( file=image_file, user = request.user.username ) upload.save() data = { } return JsonResponse(data) I am trying to crop images in Django using Croppie.js. The images are then uploaded to an S3 bucket. I have the cropping working and it is returning the image cropped as a base64 string. I decoded it and write it to a new image file so that it could be then saved in the database. When it it gets to upload.save() I am getting the error. AttributeError: '_io.BufferedWriter' object has no attribute '_committed' I'm not sure what the problem is. This is my first time working with base64 images and im not sure if im missing something when i'm converting back to a file or what is going on. -
How to add metadata(count,next,previous) to Response sent through viewset in Django rest framework
views.py def list(self, request, *args, **kwargs): queryset= User.objects.filter(id=5).values_list('name','designation') queryset=[{'name':i[0],'designation':i[1]} for i in queryset] serializer=getuserserializer(queryset,many=True) return Response(serializer.data) serializer.py class getuserserializer(serializers.Serializer): name=serializers.CharField() designation=serializers.CharField() settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } I have looked through the solutions, which suggested to change settings.py as above. Yet i am getting output like : { "result": [ { "name": "Shubham Kumar", "designation": "SE" } ] } How to convert it to : { "count": 2013, "next": null, "previous": null, "results": [ { "name": "Shubham Kumar", "designation": "SE" } ] } -
Django: Display matplot pie chart based on FilterSet
I have created the following webpage: Goal I want the user to be able to to see his spendings statistics based on the selected year and month. Problem I have difficulties to understand how to filter the database based on the user input. Usually in the html file i would pass the year month filter <form method="get"> {{ filter.form.as_table }} <button type="submit">Search</button> </form> and then display the filtered data by: {% for item in filter.qs %} ... item.*** {% endfor %} However, in this case the plot is already passed by the views.py in jpeg format. So I guess I have to connect the user input to my views.py ? This is my code, I would be grateful for any help. Thank you! models.py CHOICES = ( ('rent', 'Rent'), ('grocery', 'Grocery'), ('shopping', 'Shopping'), ('gym', 'Gym'), ('phone', 'Phone'), ('freetime', 'Freetime'), ('other', 'Other') ) class UserDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="new_spending", null=True) ... cost = models.FloatField() date_added = models.DateTimeField() category = models.CharField(max_length=25, choices=CHOICES) ... def __str__(self): return self.title filters.py from .models import UserDetails import django_filters class BudgetFilter(django_filters.FilterSet): year_added = django_filters.NumberFilter(field_name='date_added', lookup_expr='year', label='Select Year [yyyy]') month_added = django_filters.NumberFilter(field_name='date_added', lookup_expr='month', label='Select Month [mm]') class Meta: model = UserDetails fields = ['year_added', 'month_added'] views.py def … -
DJANGO cmsplugin data
I am trying to confirm if I can read cmsplugin data as html. I meant: 1. I create a plugin as a Grid (Row(s) and Column(s)). I want to get that data as html. I would like to build dynamics html templates based on the Grid system instead of keep adding static files to build the html template. -
Handle 500 internal error in Django Rest Framework
I am new to Django rest. Now what my understanding is that in case of a 500 internal error, django will send a html page with message server error 500, if debug=False in settings.py. But what i want is to send a custom json object with error code , status etc in that exception message instead of that html page. Please suggest me how to proceed with that custom exception handling. -
Using Multiple Form in Single Page (dynamically) in Django Template but The Form is not Validating
I have a View that allows the User to entre Enter Category and Subcategory. The Form will take the user to another which I have three forms and the form will load from the selected Value in Category. Now, I have three forms on my Page but one can only Load. The issue now is that the form is not showing a valid error after posting. Moreso, on print the is.valid(), I am getting False but I got the error message on printing the error. models.py @login_required def AdCategory(request): template_name = 'adcategory.html' #form = AdCategoryForm() form = ProcessItemForm() if request.method == 'POST': form = ProcessItemForm(request.POST) if form.is_valid(): request.session['category'] = request.POST['category'] request.session['subcategory'] = request.POST['subcategory'] return redirect(addItem) return render(request, template_name, {'form': form}) @login_required def addItem(request): template_name = 'additem.html' form1 = ForSaleForm() form2 = VehiclesForm() form3 = JobsForm() category = request.session.get('category') subcategory = request.session.get('subcategory') context = {'form1': form1, 'form2': form2, 'form3': form3, 'category': category, 'subcategory': subcategory} if request.method == 'POST' and category == '1': #if 'job' in request.POST and category == '1' and form3.is_valid(): form3 = JobsForm(request.POST or None, request.FILES) print(form3.is_valid()) print(form3.errors) if form3.is_valid(): if CustomUser.objects.filter(email=request.user).filter(first_name=''): messages.warning(request, 'Update Your Profile Before Submitting Ad!') return redirect('profile') else: if Profile.objects.filter(user=request.user).filter(approval=True).exists(): p = form3.save(commit=False) p.user = … -
How do I achieve this API structure with the given model serializer?
Model class UnitLog(models.Model): unit = models.ForeignKey(Unit, on_delete=models.CASCADE) user = models.ForeignKey(User, to_field="username", on_delete=models.CASCADE) time_in = models.DateTimeField(auto_now_add=True) time_out = models.DateTimeField(blank=True, null=True) total_time = models.FloatField(default=0.0) # In seconds trainee = models.CharField(max_length=30, blank=True, default="") Model Serializer class UnitLogSerializer(serializers.ModelSerializer): class Meta: model = UnitLog fields = ('unit', 'time_in', 'time_out', 'total_time', 'trainee') Required API format/structure: [ { 'date': 'Jan 20, 2019', 'duty: [ { 'unit': 'time_in': 'time_out': 'trainee': }, ... ] }, ... ] Basically, I want to group the work logs of employees by distinct dates in the outer level and list all logs on that day at the inner level. I can use groupby from itertools, order queryset by time_in__date and create a list of lists of logs performed on distinct dates, with a for loop. But I am clueless about how to serialize a list of lists. How do I start writing the serializer? I can vaguely imagine a nesting structure of the same serializer, but I am not able to figure out the view/viewset and the queryset that gets passed. Any ideas? -
Related products
In my model I have a ManyToManyField to select related products. I'm wondering what would be the best way to bring these into my view and render them in my template. models.py class Product(models.Model): title = models.CharField(max_length=80) category = models.ManyToManyField(ProductCategory) featured_image = models.ImageField(upload_to=image_dir) about_this_product = models.TextField() standard_features = models.TextField(null=True) featured = models.BooleanField(default=False) related_models = models.ManyToManyField("self", blank=True, null=True) model_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Products" def __str__(self): return self.title -
Use A Serializer Class Inside Other One In Django
I want to have a serializers that use two model at once (If it possible) models.py class Club(models.Model): id = models.AutoField(primary_key=True) clubname = models.CharField(max_length=50, blank=True, null=True) location = models.CharField(max_length=50, blank=True, null=True) scores = models.IntegerField(blank=True, null=True) serializers.py class ShowAllClubSerializer(serializers.ModelSerializer): class Meta: model = Club fields class ShowClubPictures(serializers.ModelSerializer): class Meta: model = Clubpictures fields = ['picture'] views.py @api_view(["GET", ]) @permission_classes((IsAuthenticated, )) def show_all_clubs_view(request): if request.method == "GET": clubs = Club.objects.all() if clubs: for club in clubs: pictures = Clubpictures.objects.filter(clubid=club.id) serializer1 = ShowAllClubSerializer(club) serializer2 = ShowClubPictures(pictures[0]) return Response(serializer1.data, status=status.HTTP_200_OK) # return Response(serializer2.data, status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) Now I Have These In serializers1 and serializers2 Separately: { "clubname": "Club Name", "location": "Somewhere", "scores": 5, } { "picture": "/media/images/Screenshot.png" } How can I take something like this in result: { "clubname": "Club Name", "location": "Somewhere", "scores": 5, "picture": "/media/images/Screenshot.png" } -
Oracle Virtual box for production
my client's server is using windows server 2016 , however as windows IIS does not support ASGI and redis functions , most features of my programme will be obsolete and unstable. Therefore i feel like the best solution to this issue would be to use a virtual box to host my programme in a virtual linux environment within the server . Therefore i would like to ask the experienced crowd over here at stackexchange if anyone has done something similar to what im planning to do , or if anyone can forsee issues with this method. -
Cron job with elastic beanstalk and django
I'm working on implementing some cronjobs with my application running on elastic beanstalk but am unsure of how to proceed. My current cron-linux.config file in the .ebextension folder looks like: files: "/etc/cron.d/mycron": mode: "000644" owner: root group: root content: | * * * * * root /usr/bin/python opt/python/current/app/api/cron.py > /dev/null commands: remove_old_cron: command: "rm -f /etc/cron.d/*.bak" I've used eb ssh to make sure that the paths point to the correct location. The problem is that I'm not getting any error messages so it's quite hard to know where the problem is. Any help would be much appreciated! -
Elegant way to translate custom error message django rest framework
I want to build 2 dual languages API. I use a custom exception handler and try catch errors on serializer like this (stripped a lot of boilerplate code). Client will receive the error code and lookup on it own dictionary. I want to know are there better way to do it. class OrgDuplicateName(APIException): status_code = 500 # not 201 default_detail = ErrorCode.OrgDuplicateName.name default_code = ErrorCode.OrgDuplicateName class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = "__all__" def is_valid(self, raise_exception=False): if self._context["request"]._stream.method == "POST": if Organization.objects.filter(name=self.initial_data["name"]).exists(): raise OrgDuplicateName break else: return True -
How to send browser push notifications when the tab or browser is closed in django?
I want to implement push notifications in my project with django. I want to show the notifications even when the browser and the tab are closed, I have seen that this is implemented by Facebook or web telegram. Anyone have any idea how to do it? Thank you all -
sending auth_params in django allauth login
im trying to create facebook login with allauth for two type of users (one buttons for each user). for my understanding i used auth params in the login templets of allauth in order to recognize the buttons that parsed but i'm having some difficultly printing or getting this url or the auto params value. i tried overwrite the LoginView in the allauth/account/view but no luck. allauth login.html {% if socialaccount_providers %} <div class="loginOp"> <div class="loginSection"> <h1>type1?</h1> <button> {% include "socialaccount/snippets/provider_list.html" with process="login" auth_params='type1' %} </button> </div> <div class="loginSection"> <h1>type2?</h1> <button> {% include "socialaccount/snippets/provider_list.html" with process="login" auth_params='type2'%} </button> </div> </div> </div> {% include "socialaccount/snippets/login_extra.html" %} {% endif %} thanks!! -
Easy create view on django
Forgive the question, and I know it may be something simple, but I am not able to find the solution. I have this model. model Product(models.Model): .... I need a view to create it, but I don't know how to get and save form data in an easy way, just do it through django-admin. Can anybody help me?