Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting a v alue from app for specific user
I have a Calendar app, which has a Event class for title, description, start_time, end_time, choices fields. I added the choices field with two choices c =[("1", "経理部"), ("2", "管理部")] I also added a a column to User model with this class class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.CharField(max_length=100) I'm able to access this department field with this code to shell >>> from django.contrib.auth.models import User >>> u = User.objects.get(username='marcel4') >>> d = u.employee.department >>> print(d) >>> 経理部 And simply I would like to save a post (Event) in calendar app with '経理部' choice and be able to see that post only with account that has department set to 経理部 (same one) Where should I make a changes? (like if or so) Here are my codes models in calendar class Event(models.Model): c =[("1", "経理部"), ("2", "管理部")] title = models.CharField(max_length=100) description = models.TextField() start_time = models.DateTimeField(default='2019-06-18T16:00') end_time = models.DateTimeField(default='2019-06-18T17:00') choices = models.CharField(max_length=1, choices=c) @property def get_html_url(self): url = reverse('cal:event_edit', args=(self.id,)) return f'<a href="{url}"> {self.title} </a>' views in calendar class CalendarView(LoginRequiredMixin, generic.ListView): model = Event template_name = 'cal/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) d = get_date(self.request.GET.get('month', None)) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = … -
Deployment architecture for a analytics web baszed application that uses django and spark frameworks
I am developing a web based analytics application which will provide model training and testing features via UI. To do this i had used django with scikit learn. Now, I want to do this at big data scale using spark. Using django as the backend framework for handling requests and spark to do the processing and modelling I had setup a django project and setup spark on a cluster of two linux machines along with hdfs. I am assuming that uploading / downloading / streaming of data to that hdfs is already implemented. I write each model as a view in the django project and the implementation of the view has code written using pyspark. I had used pyspark to create a connection to the spark setup on linux cluster. import pandas as pd import numpy as np import os from pyspark import SparkConf, SparkContext from pyspark.sql import SparkSession from pyspark.ml import Pipeline from pyspark.ml.feature import StringIndexer, VectorAssembler, IndexToString from pyspark.ml.classification import DecisionTreeClassifier from pyspark.ml.evaluation import MulticlassClassificationEvaluator def sample_model_code(trainData, trainDataFileType, trainDataDelimiter, testData, testDataFileType, testDataDelimiter, targetIndexTrainData, targetIndexTestData, modelName): # trainData = "D:/training-data.csv" # trainDataFileType = "csv" # trainDataDelimiter = "," # testData = "D:/test-data.csv" # testDataFileType = "csv" # testDataDelimiter = … -
Django : Display user object of logged in user in admin page
I have a set of users in my django application. I want them to be able to only see/change their user object in the admin page. So far, I made a group that restricts all permissions to the user object and then added a object permission using django-guardian, this does indeed do the job but it does not display the user object in the admin page however it does enable the user from accessing his record through code. I essentially am looking for something like user_passes_test for the admin page. -
Error with Django: gunicorn: command not found
Below is the few lines of log obtained from heroku logs while testing a django app I created. The error from the log seems to be "bash: gunicorn: command not found". Please suggest how to stop the error and run the app. 2019-0624T09:36:40.536849+00:00 heroku[web.1]: Starting process with command `gunicorn pages_project.wsgi --log-file -` 2019-06-24T09:36:42.131706+00:00 heroku[web.1]: State changed from starting to crashed 2019-06-24T09:36:42.137706+00:00 heroku[web.1]: State changed from crashed to starting 2019-06-24T09:36:42.051277+00:00 app[web.1]: bash: gunicorn: command not found 2019-06-24T09:36:42.111756+00:00 heroku[web.1]: Process exited with status 127 2019-06-24T09:36:45.000000+00:00 app[api]: Build succeeded 2019-06-24T09:36:48.595597+00:00 heroku[web.1]: Starting process with command `gunicorn pages_project.wsgi --log-file -` 2019-06-24T09:36:51.225166+00:00 heroku[web.1]: State changed from starting to crashed 2019-06-24T09:36:51.204050+00:00 heroku[web.1]: Process exited with status 127 2019-06-24T09:36:51.147676+00:00 app[web.1]: bash: gunicorn: command not found -
Django send excel file to Celery Task. Error InMemoryUploadedFile
I have background process - read excel file and save data from this file. I need to do read file in the background process. But i have error InMemoryUploadedFile. My code def create(self, validated_data): company = '' file_type = '' email = '' file = validated_data['file'] import_data.delay(file=file, company=company, file_type=file_type, email=email) my method looks like @app.task def import_data( file, company, file_type, email): // some code But i have error InMemoryUploadedFile. How i can to send a file to cellery without errors? -
Django fails to import any package : AttributeError: __name__
For some reasons, I had to reinstall Python on my desktop. Since then, my django applications are not working. I can create one, but as soon as I import a package anywhere in the application, I can't run python manage.py runserver I can run another python script, I can start Jupyter Notebooks (and import the exact same packages in them). I also tried to create new projects with the "new" python installed, as soon as I add import pandas (or any other packages except django), I have the error. The error message is quite long, ending with the following lines : File : "C:\Users\myname\AppData\Local\Continuum\anaconda3\lib\site-packages\py\-error.py", line 44, in __getattr__ raise AttributeError(Name) AttributeError: __name__ -
How to create a dynamic filter based on the primary key of ForeignKey in ListView?
I am relatively new to Django but the main problem I am facing right now is to create a ListView that will display uploaded documents based on the primary key of my ForeignKey. I have tried several methods of trying to create the filter and read the online documentation on class-based view but it does not seem to have relevant information on how to use the primary key of my ForeignKey in my filter. These are my models: class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default = 'default0.jpg', upload_to='course_image/') description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.IntegerField(default = 0) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk' : self.pk}) class Lesson(models.Model): title = models.CharField(max_length=100) file = models.FileField(upload_to="lesson/pdf") date_posted = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('lesson_upload', kwargs={'pk': self.pk}) Here is my ListView with the filter that is not working: class LessonListView(ListView): model = Lesson template_name = 'store/uploaded_lesson.html' context_object_name = 'lesson' # def get_queryset(self): # return Lesson.objects.filter(Post__pk=self.Post.pk) def get_queryset(self): self.post__pk = get_object_or_404(post__pk, name=self.kwargs['post__pk']) return Lesson.objects.filter(post__pk=self.post__pk) -
put() missing 1 required positional argument: 'pk'
I am new in Django and I am trying to update record. but when I run put method, An error show like that => put() missing 1 required positional argument: 'pk' Here is my view => from rest_framework.generics import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from .models import Allowance from .serializers import AllowanceSerializer # Create your views here. class AllowanceAPIView(APIView): def get(self,request,pk=None): if pk: allowance=get_object_or_404(Allowance.objects.all(),pk=pk) serializer = AllowanceSerializer(allowance) return Response({serializer.data}) allowance=Allowance.objects.all() serializer = AllowanceSerializer(allowance,many=True) return Response({"allowance":serializer.data}) def put(self,request,pk): save_allowance = get_object_or_404(Allowance.objects.all(),pk=pk) data = request.data.get('allowance') serializer = AllowanceSerializer(instance=save_allowance,data=data,partial=True) if serializer.is_valid(raise_exception = True): allowance_saved=serializer.save() return Response({"sucess": "Allowance '{}' updated successfully".format(allowance_saved.AllowID)}) def delete(self,request,pk): #Get object with this pk allowance = get_object_or_404(Allowance.objects.all(),pk=pk) allowance.delete() return Response({"message":"Allowance with id '{}' has been deleted.".format(pk)},status=204) Here is my url=> from django.conf.urls import url from .views import AllowanceAPIView urlpatterns = [ url(r'^$', AllowanceAPIView.as_view(), name='post-listcreate'), url(r'^(?P<pk>\d+)/$', AllowanceAPIView.as_view(), name='post-listcreate') ] Get method and post method are ok, Just happen in put method and delete not testing yet. Please help. -
How to Migrate to custom user Model from profile Model?
I'm refactoring a code base that uses a Profile model with one to one relation to django User model, I want to create a custom user model and migrate profile and User model data to this new custom model and all the other models that have reference to Profile model should have a reference to CustomUserModel. Note: I need to keep the data I am wondering is there any solution without having to deleting all the migrations for this problem? I have checked these answers: https://www.caktusgroup.com/blog/2019/04/26/how-switch-custom-django-user-model-mid-project/ https://code.djangoproject.com/ticket/25313 But neither of them considering if you have a profile model and you have relations from other models to your profile model. At the end I want to update all relations from Profile model to custom user model and keep the data as it was. -
My django form is not displaying on the html page
I am trying to create an add form to take input from a user and add it to my model, however, the form is not showing on the page, can someone tell me what I am doing wrong? Here is the code for the forms.py, views.py and add.html: forms.py class AddForm(forms.Form): vehicle = forms.CharField(max_length=10) carrier = forms.FloatField() location = forms.ChoiceField(choices=[(1, 'Mathura Installation')]) customer_code = forms.FloatField() zone = forms.ChoiceField(choices=[('NW', 'North West'), ('NCR', 'North Central'), ('SCR', 'South Central'), ('S', 'South'), ('N', 'North'), ('W', 'West'), ('E', 'East') ]) quantity = forms.FloatField() load = forms.FloatField() rtkm = forms.FloatField(label='RTKM') rate = forms.ChoiceField(label='Rate ', widget=forms.RadioSelect, choices=[('avg', 'Average Rate'), ('user', 'User Rate')]) views.py def add(request): addform = forms.AddForm() dict = {'addform': addform} return render(request, 'add.html', dict) html - add.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <head> <meta charset="UTF-8"> <title>Transport Portal - Add Page</title> </head> <body> <div class="header"> <img src="{% static 'images/hpcl_logo.png' %}"> <h1>Transportation Portal</h1> </div> <div class="topnav"> <ul> <li><a href="home.html">Home</a></li> <li><a href="homehp.html">Search</a></li> <li><a class="active" href="add.html">Add</a></li> </ul> </div> <div class="add"> <form method="POST"> {% csrf_token %} {{ addform.as_p }} </form> </div> </body> </html> -
Unicode error while sending audio/mpeg response django rest framework
I am trying to send audio/mpeg response in an API. The API takes some parameter from the user and creates audio on that basis. I am able to convert the output to stream and is able to write to the file. When I open that file, I can hear the correct output. But when I try to send the byte stream as the output in the Response object of django-restframework, I am getting the unicodeDecodeError. I have tried to send the HttpResponse and the audio stream works fine with that. from rest_framework.response import Response from rest_framework.views import APIView class GetTextAudioView(APIView): def post(self, request, *args, **kwargs): text = request.data.get('text') response = polly.synthesize_speech(Text=text, OutputFormat='mp3, VoiceId='Joanna') response = response.get('AudioStream') with open('speech.mp3', "wb") as file: file.write(response.read()) return Response(data=response, content_type='audio/mpeg', status=status.HTTP_200_OK) The point I am not getting is why Django rest framework is trying to parse the response as JSON when clearly the content_type is not application/json. Thanks in advance. -
How to scrap price and product from random E-Commerce site
I want to scrap the product name and its price from any E-commerce site (i.e) Amazon, Flipkart etc.Using Django I want to scrap every E-commerce site, by using single function.Even if a new site is launched example: www.ABC.com, My code should scrap even this site's product name and price. Is there any possibilites?. -
How to upload file from django oscar dashboard?
So, I tried to modify ProductClass from Django Oscar. It works fine if I tried to upload image from Django Rest API, like below: But when I tried to upload image from Django Oscar admin dashboard it always return null. Here is my model: And below is my dashboard/catalogue/forms.py What do I need to modify or extends so that I can upload image using Django Oscar admin dashboard? -
Display an image located in database Django 2.2
I want to get images from database to show on my html page but it is showing Page not found 404 http://127.0.0.1:8000/media/designs/myphoto.jpg def index(request): topImgs = PortfolioImages.objects.filter(feature=2) botImgs = PortfolioImages.objects.filter(feature=3) return render(request, 'ideadunes/index.html', {'topImgs':topImgs, 'botImgs':botImgs}) -
What is purpose of django.setup()?
I am updating website of my previous employee & have some issue with following code. What is purpose of django.setup() line in following code. Is it necessary to put below code in init.py file. from __future__ import absolute_import, unicode_literals import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app_name.settings") django.setup() -
How to customize HTTP_USER_AGENT header with Graphene and React Native?
I found that React Native does not give HTTP_USER_AGENT value to Django Graphene. On Garaphene, I receive the header by: def resolve(cls, root, info, **kwargs): info.context.META['HTTP_USER_AGENT'] It works when I send a query through a browser. However, the HTTP_USER_AGENT only has "okhttp/3.6.0" value when I send a query through my React Native app. So I tried to change the HTTP_USER_AGENT value by setting headers of axios. onSubmit = async () => { if (!this.state.isSubmitting) { this.setState({isSubmitting: true}); await axios({ url: 'http://192.168.0.6:8000/graphql/', method: 'post', headers: { HTTP_USER_AGENT: 'CCC' }, data: { query: ` It does not work. HTTP_USER_AGENT does not change and only shows "okhttp/3.6.0". I tried other custom headers and found that they do not work either. I cannot just set my own custom-named-header. Why is this the case? The only header I was available to change was AUTHORIZATION. Django Graphene received the header value when I set await axios({ url: 'http://192.168.0.6:8000/graphql/', method: 'post', headers: { AUTHORIZATION: 'JWT CCC' }, and the value was availble from info.context.META['HTTP_AUTHORIZATION'] I had no idea what my assumptions were wrong. -
How to launch local API to be accessible globally?
I would like to run RESTFUL API build in Python Django on my machine in a way to be accessible from the Internet. I don't want to host it in the cloud or anywhere else, I would like to keep running it locally I tried to run it locally and it works fine for my device since it in the same network but users from the different network cannot send a request to me. -
Django Haystack Rebuild Necessary?
I have a Web app which uses Elastic search and django Haystack for its search functionality. I also have an add button which adds the value to database. Once I add and search the NEW ITEM immediately, it gives me correct result without doing rebuild_index. I suppose it is because I have added HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor to my settings.py file I have a script running parallel to this django application which changes a field in the same backend database (MongoDb) When I search for the particular changed field, it is not showing that correct result item it is not showing the changed result item instead it shows the old item before updation until I stop my application and do a manage.py rebuild_index and runserver and search it again. It happens only with a seperate script. What do I have to do to make it work in parallel scripts as well? Thanks -
Is it possible to loop a custom model form in django?
Is it possible to create multiple objects for a model in django by looping the same form in a for loop. I am using a custom model form. My template is: {% for query in queryset %} <form method="POST" action="{% url 'academics' %}" style=" padding: 5%"> {% csrf_token %} <input type="text" name="Student" class="form-control" id="id_Student" value="{{query}}"> <input type="text" name="Subject" class="form-control" required id="id_Subject"> <input type="checkbox" name="Presence" id="id_Presence"> <button type="Submit" id="submit">Submit</button> {% endfor %} <button type="Submit" id="submit">Submit</button> </form> My models.py is: class Attendance(models.Model): Student = models.CharField(max_length=100, blank=False) Hour = models.CharField(max_length=1, blank=False) Subject = models.CharField(max_length=8, blank=False) Date = models.DateTimeField(default=timezone.now) Presence = models.BooleanField(default=False, blank=False) def __str__(self): return f'{self.Student}' My views.py is: def academics(request): if request.user.is_staff: form = forms.AttendanceForm() context = { 'form': form, 'queryset': User.objects.filter(profile__Year='SY',profile__Department='CSE') } if request.method == "POST" : form = forms.AttendanceForm(request.POST) if form.is_valid(): student = request.POST.get('Student') hour = request.POST.get('Hour') subject = request.POST.get('Subject') boolean = request.POST.get('Presence') def bool(boolean): if boolean == 'on': return 'True' else: return 'False' form = Attendance(Student=student,Hour=hour,Subject=subject,Presence=bool(boolean)) form.save() return render(request, 'console/academics.html',context) Currently i can create multiple objects, but with the same values of the last form. ie, the object is created with the values of last form. Here i have looped the form so that n number of forms will … -
how can we prefetch the property of model , so that we will not have to request db everytime when the list of objects will be serialized in django
this is my serializer ---> class CurrentUserCalendarSyncSerializer(BaseOccurrenceSerializer): select_related_fields = ('event__group',) organization_name = serpy.StrField(required=False, attr='event.group.organization_name') division_name = serpy.StrField(required=False, attr='event.group.division_name') this is my model---> class OrganizationGroup(MPTTModel, AddressMixin, GeoLocationMixin, Timestampable): @property def organization_name(self) -> Optional[str]: return None if self.is_root_node() else self.get_root().name @property def division_name(self) -> Optional[str]: return None if self.get_ancestors().count() < 2 else self.get_ancestors()[1].name when i am serializing the list of occurrences it hits the db for multiple times and also takes time to get the response, i want to prefetch all these in view where i have created a list of object . -
Missing 'user' argument in a django UpdateView with two forms
I have a view on which there is two forms, one is form updating user password and another form with other informations such as email and username. I have followed tutorials and ended up with this code: views.py: class EditProfileView(PermissionRequiredMixin, generic.UpdateView): permission_required = 'is_staff' template_name = 'profile/edit-profile.html' form_class = UserForm second_form_class = PasswordChangeForm success_url = reverse_lazy('acp:edit-profile') model = User def get_object(self, queryset=None): return self.request.user def get_context_data(self, **kwargs): context = super(EditProfileView, self).get_context_data(**kwargs) if 'form' not in context: context['form'] = self.form_class(self.request.GET) if 'form2' not in context: context['form2'] = self.second_form_class(self.request.GET) return context def post(self, request, *args, **kwargs): self.object = self.get_object() if 'form' in request.POST: form_class = self.get_form_class() form_name = 'form' else: form_class = self.second_form_class form_name = 'form2' form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form) else: return self.render_to_response(self.get_context_data(form=form)) where i have this in my template: <input type="submit" name="form2" class="profile-buttons" value="Alterar senha"> Somehow the code breaks in this line: form = self.get_form(form_class) with the message "TypeError: init() missing 1 required positional argument: 'user'" -
change_view() missing 1 required positional argument: 'object_id' is showing in the superuser page?
In the admin section the elements when clicked on show object_id missing. The comment should be shown. But the error is showing. -
How to read file from python csv in html?
I have a problem that I want to read files from csv and make loop in it instead of writing one by one in html page. How to read and fetch files from csv in html using python code in django. This code is of index.html. <body> <center><h1>Article Writing Sites</h1></center> <div class="row"> <div class="column"> {% with open('file.csv') as open%} </div> <div class="column"> <p>this is next paragraph</p> </div> </div> </body> -
Django will run the function content twice when using render
I am sorry that my English is not good. My problem is that refreshing the page in Google Chrome will cause the function with render to run twice But run it once in the Firefox browser. I don't know if this is a problem with Google Chrome or something else?(I hope to get help, thank you) def add_teacher(request): Teacher.objects.create(username='zhangsan',avatar='https://static-image.xfz.cn/11.jpg',jobtitle='aaa',profile='bbb') print('=====') return render(request,'course/course_index.html') I ran the same content in Google Chrome,And only one data is created in Firefox. but the results are different. Two teachers' data will be created when Google Chrome refreshes the page, and only one will be created in Firefox. Pycharm will also print out twice the content. -
How can I initialize my form Image and Integer fields with model data?
I've managed to initialize a CharField, but how can I do the same with ImageField and IntegerField? My forms.py: class GoodGet(forms.ModelForm): class Meta: model = Good_Get Size = forms.ModelChoiceField(queryset = Good.objects.all()) fields = '__all__' def __init__(self, *args, good_id1=None, **kwargs): super(forms.ModelForm, self).__init__(*args, **kwargs) if good_id1 is not None: obj = Good.objects.filter(id = good_id1) self.fields['Name'].initial = Good.objects.get(id=good_id1) self.fields['Photo'].initial = Good.objects.get(id=good_id1) self.fields['Price'].initial = Good.objects.get(id=good_id1) for good in obj: good_sizes = good.Size.all() self.fields['Size'].queryset = good_sizes So, I need to write these strings correctly: self.fields['Photo'].initial = Good.objects.get(id=good_id1) self.fields['Price'].initial = Good.objects.get(id=good_id1) How?