Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Register user with email verification
I'm working on DRF project. I use email as a unique username in my own user model and using jwt as authentication. I made everything but cannot implement email verification when create user model. I was thinking of making token of user and use it to make user activate after first logged in. So I tried to override every single methods in generics.createAPIView and django.contrib.auth.tokens.PasswordResetTokenGenerator. And now it seems like impossible. I coulnd't find any information who made it with DRF. I want to do email verification before user model is actually written in database, and if it succeed, then write in database. I'm using vue as front-end so what I want is [ vue(register page) --> drf(check if it's validate) --> send mail to request.data['email'] --> click the link in email and finish registration --> drf(finish register and write in database) ] Is there any possible way to make it with override on methods of CreateAPIView? -
Use Django Rest Framework Tokens to authorise someone [closed]
I can't think of a more descriptive title, but what I mean is, when I am writing a Python script that scrapes from the API, how can I authorise myself in the Python file as if I was a real user wanting to utilise the API? So if I were to be using the requests library, how would I add authorisation to it, so I could access the API? -
Django | prefetch_related() exclude parent object without child/children object/s
Taken from Django's documentation, suppose that you have the following models: from django.db import models class Topping(models.Model): name = models.CharField(max_length=30) class Pizza(models.Model): name = models.CharField(max_length=50) toppings = models.ManyToManyField(Topping) def __str__(self): return "%s (%s)" % ( self.name, ", ".join(topping.name for topping in self.toppings.all()), ) Running the code below will return all Pizza objects and its related Toppings object/s. Pizza.objects.all().prefetch_related('toppings') Question, what if you would like to look for all Pizza's with specific Topping/s. Will filter on prefetch_related work like the code below? Won't it return all Pizza objects even without the Toppings specified? If so, will it be possible to return only those Pizza's with the filtered Toppings? toppings_q = Q(name='Pepperoni') & Q(name='Ham') & Q(name='Bacon') Pizza.objects.all().prefetch_related( Prefetch( 'toppings', queryset = Toppings.objects.filter(toppings_q) ) ) Thank you. -
How to get user and associated group permissions in Django Rest Framework?
I want to serialize the user and associated group permissions and make them available via an API endpoint. However, I can only retrieve the permissions that are directly assigned to the user, not those that come from the parent group. API Call containg user and group permissions: "user": { "id": 35, "username": "HII", "email": "asdsa@test.de", "user_permissions": [ 9, // Example User Permission Currently Retrieved 11, // Example User Permission Currently Retrieved 6, // Example Group Permission Currently Not Retrieved 8 // Example Group Permission Currently Not Retrieved ] } User API View # Get User API class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user User Serializer # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: user_permissions = serializers.SerializerMethodField('get_user_permissions') model = User fields = ('id', 'username', 'email', 'user_permissions') def get_user_permissions(user): if user.is_superuser: return Permission.objects.all() return user.user_permissions.all() | Permission.objects.filter(group__user=user) The standard django user model is used. How is it possible to retrieve the group permissions associated with a user. I am happy about every hint. -
Django app with real-time script output console
I have a Django app which executes a script. Now I want to display the out put of the script in real-time. I have some questions regarding the implementation of the same. I suppose I can use channels to push each line as they get generated into the front end and display them. But if another user opens the same page he will only be seeing latest lines and not the initial lines pushed. I can use a generator function to simulate kind of a tailf on the filename to get the lines. But where would this code reside and how to trigger it when someone visits the log pages(there would be multiple jobs running at the same time) What would be the best and simple way to achieve this. -
systemd service for Gunicorn for Django
I am using a vps with ubuntu 18.04 and I have created below systemd service for Gunicorn for my Django application with postgres as database : [Unit] Description=Gunicorn After=network.target [Service] Type=simple User=django ExecStart=/bin/bash /home/django/bin/start-server.sh Restart=on-failure [Install] WantedBy=multi-user.target but after enabling gunicorn I have Server Error (500). And the error says: OperationalError at / FATAL: Peer authentication failed for user "root" what I have to do to make it right? -
The view formApp.views.formRegister didn't return an HttpResponse object
Views.py from django.shortcuts import render from . models import Registerform # Create your views here. def formRegister(request): if request.method == 'POST': if request.POST.get('firstN') and request.POST.get('lastN') and request.POST.get('Email') and request.POST.get('pass'): Registerform = Post() Registerform.firstName = request.POST.get('firstN') Registerform.lastName = request.POST.get('lastN') Registerform.email = request.POST.get('Email') Registerform.password = request.POST.get('pass') Registerform.save() return render(request, 'formApp/formreg.html', context_instance=RequestContext(request)) Error Screenshort As you can see in the above error image, my code is not functioning properly. I have added my models.py and views.py code. Please help me to resolve the issue. -
django rest JSON API results as list by key
I have a very basic API made with Django Rest Framework with an output as follows: [ { "name": "John", "city": "chicago", "age": "22" }, { "name": "Gary", "city": "florida", "age": "35" }, { "name": "Selena", "city": "vegas", "age": "18" } ] I want to convert it to the following format to simplify the usage of its data in charts. { "name": ["John", "Gary", "Selena"] "city": ["chicago", "vegas", "florida"] "age": ["22", "35", "18"] } Is there a simple way this can be done in Javascript (and Python just for curiosity)? Can this be proactively solved by adjusting the Serializer or the ViewSet in DRF? -
Django form.cleaned_data.get('field') has no attribute str
I search but didnt find any solution views.py code: def register(request): form = RegisterForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') newUser = User(username = username) newUser.set_password(password) newUser.save() login(request, newUser ) messages.success(request, 'Registering Succeed') return redirect('index') else: return render(request, "register.html", {'form':form}) forms.py code: class RegisterForm(forms.Form): username = forms.CharField(max_length=20, min_length=6, required=True, label="Username") password = forms.CharField(max_length=18, min_length=6, widget=forms.PasswordInput, label="Password", required=True) confirm = forms.CharField(max_length=18, min_length=6, widget=forms.PasswordInput, label="Password Confirmaation", required=True) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') confirm = self.cleaned_data.get('confirm') if password != confirm: raise forms.ValidationError("Passwords are not same") else: return I get an error that 'str' object has not attribute 'get' -
Rendering images in templates in Django
When I render images on my webpage in Django, some images render stretched and some very compressed. Even if I style the <img> it does not apply well to all of the images. Is there any specific way in Django, that we can render images beautifully on the webpage ? -
Show django admin.TabularInline as a formset of the main model form
This is my Django Admin page I want to transfer this look to a form on my website. What i have managed currently is the formset without the "add/delete another order item" button My current ordering view -
AJAX success not JSON serializable
I am implementing AJAX in my Django project. Users can navigate through their favorite items in their account. I have two models, Product for the products details, SavedProduct with username and product_id (foreign key from Product). At first users land into their account from a link, then they sould navigate from page to page with AJAX. So far whenever I hit one of the navigation button a list of dictionaries is created in my view. But I can't pass it back to AJAX, I get a TypeError: Object of type Page is not JSON serializable. What I want is my list of dictionnaires to reach AJAX so it can change my DOM. My views.py: def account(request): user_id = request.user sub_list = SavedProduct.objects.filter(username=user_id) paginator = Paginator(sub_list, 5) page_number = request.GET.get('page') saved_list = paginator.get_page(page_number) context = { 'paginate': True, 'saved_list': saved_list, } if request.method=='POST': user_id = request.user sub_list = SavedProduct.objects.filter(username=user_id) results = [] for fav in sub_list: products_json = {'or_name':0, 'sub_name':0, 'or_brand':0, 'sub_brand':0} products_json['sub_name']=(fav.sub_product.real_name) products_json['sub_brand']=(fav.sub_product.real_brand) products_json['or_name']=(fav.original_product.real_name) products_json['or_brand']=(fav.original_product.real_brand) results.append(products_json) paginator = Paginator(results, 5) page_number = request.POST.get('page') saved_list = paginator.get_page(page_number) data = json.dumps(saved_list) return JsonResponse(data) return render(request, 'account/account.html', context) My AJAX: $(".nav_button_2").on("click", function(event) { event.preventDefault(); var page = $(this).val(); console.log (page); var url = … -
how to make add() with through_defaults different for each object m2m Django?
I have a question about Django add(*objs, bulk=True, through_defaults=None) with new through_defaults argument. https://docs.djangoproject.com/en/3.0/ref/models/relations/#django.db.models.fields.related.RelatedManager.add I have a intermediate model that is used as through model in many-to-many relationship. Relations are recursive and symmetrical (model points to itself). class GroupingModel(models.Model): """ Intermediate model for Many-to-Many recursive relationship between series. """ from_series = models.ForeignKey( 'TvSeriesModel', on_delete=models.CASCADE, related_name='group', ) to_series = models.ForeignKey( 'TvSeriesModel', on_delete=models.CASCADE, related_name='group_to', ) reason_for_interrelationship = models.TextField( verbose_name='Reason for relationship to an another series.' ) For example I have 4 primary model 'TvSeriesModel' instances : obj1, obj2, obj3 and obj4. Now I want to add m2m relationship between obj1 and obj2, obj3 and obj4 via our intermediate model ‘GroupingModel’ where I want to specify reason for this relations in field ‘ reason_for_interrelationship ’ and this reason should be different for each object. So, I would type : interrelationship related manager from primary model obj1.interrelationship.add( obj2, obj3, obj4, through_defaults ={ ‘reason_for_interrelationship’: ‘???????’ } ) And now I have a problem if I want to specify different reason for each object. Seems like it is not possible or at least not obvious for me how to do it. Problem is that I am able to specify only one common reason for relationship for … -
TypeError: Object of type ndarray is not JSON serializable
I want to serialize list of Data which looks like this [[-0.19137745 -0.08272246 -0.29323375 ... -0.07040742 0.08504822 0.11830507] [-0.21211784 -0.08182242 -0.29623193 ... -0.05424922 0.10875464 0.1036639 ] [-0.21633492 -0.08055094 -0.2975351 ... -0.06488793 0.10478106 0.0810216 ] ... [-0.14636803 -0.08461116 -0.3130865 ... -0.05071553 0.04644154 0.08371831] [-0.17098498 -0.08941076 -0.29189685 ... -0.06070996 0.08538496 0.1129984 ] [-0.19961393 -0.07552703 -0.30188963 ... -0.0616323 0.08856633 0.11165522]] shape is (9, 128) and I m using JsonResponse of Django to send a response. return JsonResponse({'use_id':user_id,'face_location':location,'embeddings':encodings,'message':message}) It is raising error like raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type ndarray is not JSON serializable -
update existing record or create if it doesn't exist django rest
I am using Django Rest Framework connected with MySQL DB. I have created a table "Product Status" #models.py class ProductStatus(models.Model): product_id = models.IntegerField(blank=False, null=False,primary_key=True) status = models.CharField(max_length=16,blank=True,null=False,validators=[alphanumeric]) #serializers.py class ProductStatusSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ProductStatus fields = ('product_id', 'status') and I would like to receive multiple records' POST requests and update records if product_id exists or create a new one if product_id is new. How can I do that? -
Error when uploading image to django server using retrofit and kotlin
I wrote the part where I upload the image using retrofit. enter image description here enter image description here And this is what the django server did. [enter image description here][3] If you do this, the django output shows up like this. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Bad Request: /app_addface/ To be honest, Android studio coding seems wrong, but I don't know how to implement it. Also, I don't know what function you should use to put into the django after receiving it from Android Studion. -
Summing Values in Dictionary Based on Certain Values
:) I'd love it if someone could lend me a hand with this... I have a list of dictionaries that state a date as well as a price. It looks like this: dict = [{'Date':2020-06-01, 'Price': 50}, {'Date':2020-06-01, 'Price': 12}, {'Date':2020-06-02, 'Price': 60}] I'd like to create a new list of dictionaries that sum all the Price values that are on the same date. So the output would look like this: output_dict = [{'Date':2020-06-01, 'Price': 62}, {'Date':2020-06-02, 'Price': 60}] How could I achieve this? Any help would be really appreciated. Thanks in advance! :D PS. Technically, the list of dictionaries is displayed like this: dict = [{'Date':datetime.datetime(2020, 6, 1, 0, 0), 'Price': 50}, {'Date':datetime.datetime(2020, 6, 1, 0, 0), 'Price': 12}, {'Date':datetime.datetime(2020, 6, 2, 0, 0), 'Price': 60}] I don't know if one version better than the other though. -
Django tables2 how to display distinct row
I want to have main table with linking value to table with details. I managed that by displaying detailed table with values form main table linked by foreignkey. The issue it that a have duplicated rows in main table that way. It there a way to display distinct value. I have tried to display data from table Factclaimcases and then replace pk - idfactclaimcases with partnumber from Factclaim but I failed. I would appreciate if somebody could look a it. views.py def claim_cases(request): items = Factclaim.objects.exclude(idfactclaimcase__isnull=True) table = tab_claim_cases(items) return render(request, 'claim_cases.html', {'table': table}) tables.py class tab_claim_cases(tables.Table): partnumber = tables.TemplateColumn('<a href="{% url "case_details" %}?idfactclaimcase={{ record.idfactclaimcase.idfactclaimcase }}">{{ record.partnumber.partnumber }}</a>') class Meta: model = Factclaim template_name = "django_tables2/bootstrap.html" fields = ("partnumber", "idfactclaimcase.thedate.thedate", "idfactclaimcase.description", "idfactclaimcase.manufacturedef") models.py class Factclaim(models.Model): idclaim = models.IntegerField(db_column='IdClaim', primary_key=True) # Field name made lowercase. claimnumber = models.CharField(db_column='ClaimNumber', max_length=50, blank=True, null=True) # Field name made lowercase. refinvoice = models.IntegerField(db_column='RefInvoice') # Field name made lowercase. accnumber = models.ForeignKey(Dimclient, models.DO_NOTHING, db_column='AccNumber') # Field name made lowercase. partnumber = models.ForeignKey(Dimproduct, models.DO_NOTHING, db_column='PartNumber') # Field name made lowercase. dateregistered = models.ForeignKey(Dimdate, models.DO_NOTHING, related_name='registration', db_column='DateRegistered', blank=True, null=True) # Field name made lowercase. dateinstalled = models.ForeignKey(Dimdate, models.DO_NOTHING, related_name='instalation', db_column='DateInstalled', blank=True, null=True) # Field name made lowercase. dateremoved … -
How to use Django For a microservice architecture. ? Is it efficient for an independant microservice?
I'm building few micro-service apps currently for learning purposes. I am happy with the micro nature of express framework and find it to be easier and good fit for independant micro-service environment with their own db. About django, I find it to be a little bigger and its not a micro framework. I'm thinking about how would a django framework fit into the micro-service world. My questions are, 1) Authentication, I tried out jwt based auth among few express apps, with expiry and refresh it seemed to flexible and nicer. Django has its own auth middle-wares and everything already, If I'm using django for independent micro services, Should i be writing custom middle-ware for each Service ? or If i Use django's admin and user management and put it as a service, then i should be still using custom middlewares in other independant django services ? 2) Is it inefficient ? Most of the django's full-stack features will not be used all the time, and needs few customization in each of it. Does it mean django is not a good fit for this ? I like django since it felt very solid and easy to develop apps, Django and Django … -
Profile's href attribute shows empty string on creation Django
After creating a new user, profile of user is created but it doesn't show default image. When I check view page source, src attribute show empty string like src=''. But when I go to profile link where I can update my profile then at that time it automatically load default image and and all the posts created by that user will get that default image. New user created and new post added by user when I click user profile, it automatically load default image and all posts created by that user get the default image. View page source mdoels.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) forms.py class UserRegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] view.py @login_required def profile(request): Profile.objects.get_or_create(user=request.user) if request.method == 'POST': u_form = UserUpdateForm(data=request.POST, instance=request.user) p_form = ProfileUpdateForm(data=request.POST, instance=request.user.profile, files=request.FILES) if u_form.is_valid() and p_form.is_valid(): … -
App not compatible with buildpack while push to heroku
I have tried all the solutions related to this issue. Nothing worked for me. I am using Django and I put Procfile,requirements.txt, runtime.txt file where manage.py is located. As I know this is the root directory of my project. Can anyone plz help me out? git push -f heroku master Enumerating objects: 718, done. Counting objects: 100% (718/718), done. Delta compression using up to 4 threads Compressing objects: 100% (522/522), done. Writing objects: 100% (718/718), 11.44 MiB | 314.00 KiB/s, done. Total 718 (delta 184), reused 682 (delta 172) remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku-community/apt.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to ewallet-food. remote: To https://git.heroku.com/ewallet-food.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/ewallet-food.git' -
Django rest +vue.js excel file download corrupted
Hi Have problem with downloading excel file from serve by url. The file is corrupted etc.. below is my download function vue downloadFile() { axios({ url: this.scenario.file, method: 'GET', headers: {'Accept': 'application/vnd.ms-excel'}, responseType: "arraybuffer" }).then(response => { const url = window.URL.createObjectURL( new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}) ); const link = document.createElement("a"); link.href = url; link.setAttribute('download', `file.xlsx`); this.myresponseObject = response; // this line is just to save - url= window.URL.createObjectURL this.blobUrl=url; // this line is just to save response object fro checking document.body.appendChild(link); link.click(); window.URL.revokeObjectURL(url); link.remove(); }); }, in this code the url of the file which stored in the object scenario is - this.scenario.file = "http://127.0.0.1:8000/media/datafiles/Input_curves_bm7ionE.xlsx" I have saved the "response" to look at it after download attempt: myresponseObject:Object config:Object adapter:ƒ xhrAdapter(config) data:undefined headers:Object maxContentLength:-1 method:"get" responseType:"arraybuffer" timeout:0 transformRequest:Array[1] transformResponse:Array[1] url:"http://127.0.0.1:8000/media/datafiles/Input_curves_bm7ionE.xlsx" validateStatus:ƒ validateStatus(status) xsrfCookieName:"XSRF-TOKEN" xsrfHeaderName:"X-XSRF-TOKEN" data:ArrayBuffer headers:Object content-length:"1345" content-type:"text/html; charset=utf-8" date:"Mon, 08 Jun 2020 10:24:40 GMT" server:"WSGIServer/0.2 CPython/3.7.7" vary:"Cookie" x-content-type-options:"nosniff" x-frame-options:"DENY" request:XMLHttpRequest status:200 statusText:"OK" And url created by window.URL.createObjectUR is: "blob:http://127.0.0.1:8000/8a40ab70-1ce4-42d2-9176-935c10ef1526" Which is different from the original: url:"http://127.0.0.1:8000/media/datafiles/Input_curves_bm7ionE.xlsx" Guess it should be like this. So, excel file downloaded is 2kb and is corrupted, formats or file extension is invalid Spent day on it..... Regards -
(Django) Having trouble wrapping my head around follower/target models in Models.py
I have just started with making a similar site to Pinterest and the site has follower/target system that I have barely any understanding of. So far, my models.py code is below: from django.db import models class User(models.Model): username = models.CharField(max_length=45, null=True) email = models.CharField(max_length=200, null=True) password = models.CharField(max_length=200) nickname = models.CharField(max_length=45, null=True) target = models.ManyToManyField(self, through='Follow') follower = models.ManyToManyField(self, through='Follow') class Meta: db_table = 'users' class Follow(models.Model): follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='targets') target = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followers') class Meta: db_table = 'follows' This code was made with reference to another StackOverflow thread Django models: database design for user and follower However, I am having trouble understanding how using "related_name='targets' in 'follower' and "related_name='followers'" in 'target' where I can't see any 'targets'(plural) or 'followers'(plural) in other areas of models.py Should I get rid of that related_name, since there is no such table called "followers" or "targets"? And if you spot major errors in my code or logic, can you tell me? Thanks! -
How to send javascript variables to django server using django?
I just started learning web development, My objective: To display selected columns of a CSV file in server on the client page So for some context on what I'm trying to do is, There are a few CSV files on my Django server. The client HTML page has a dropdown to select a file from a list of files and something like a filter for what columns to be displayed. I'm trying to get the values of the file and the filters using a button onclick method and send the values as an ajax request to the Django views.py. I will then use those variables to get the file, and the selected columns and use the render() function to render the HTML page dynamically My Questions: first of all, is what I'm doing the best way to handle my requirement? since I'm new to web-dev I don't know all the possible methods of achieving my requirement and I am doing it the only way I can think of. if what I'm doing is right, how do I send an ajax request to the server's views.py I can't seem to find the right code snippet/tutorial on how to send ajax request … -
No module named 'django.contrib.admin.templatetags.admin_static'
my django version is 3.0.5 and django-suit version is 0.2.28 but why does this error happen? the whole error information is as follows: File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\suit\admin.py", line 8, in <module> from suit.widgets import NumberInput, SuitSplitDateTimeWidget File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\suit\widgets.py", line 6, in <module> from django.contrib.admin.templatetags.admin_static import static ModuleNotFoundError: No module named 'django.contrib.admin.templatetags.admin_static'