Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ajax Image submit
I am trying to upload and save an image file using Django and respond the image itself to use in ongoing javascript functions. The problem is that the image doesn't get saved, the request.FILES is empty. When using request.body, I can see that there is not the actual file path, but a C://fakepath. Because I want the uploaded image to use immediately, I do the post using a jquery ajax call. views.py: def image_feedback(request): if request.method == 'POST': image = request.FILES.get('image') ImagesUpload.objects.create( image = image, ) return HttpResponse('success') models.py: class ImagesUpload(models.Model): image = models.ImageField(upload_to=renaming_file) def __str__(self): return str(self.image) form_template.html: <form id="image_form" enctype="multipart/form-data">{% csrf_token %} <button class="btn btn-secondary" onclick="$('#id_image').click()">Import Image</button> {{ form_image.image }} <input id="hidden-submit-img" value="SUBMIT" type="submit" style="visibility:hidden"> </form> jquery ajax call: <script> $(document).ready(function () { // This jquery changes the appearance of the django { form_image } var imgElement = $('#id_image'); imgElement.css('visibility', 'hidden'); // This function triggers the hidden submit, // which triggers the ajax image request imgElement.on({ change: function () { $('#hidden-submit-img').click(); }, }); }); // This jquery is for the ajax post of the image $('#image_form').submit(function (event) { event.preventDefault(); $.ajax({ data: { image: $('#id_image').val(), csrfmiddlewaretoken: '{{ csrf_token }}' }, type: "POST", enctype: 'multipart/form-data', url: "{% url 'website:image-feedback' %}", … -
How to get total data creted in manytomany field
here in this i want to fetch no of Players_Participants added by the user,in this i am getting total no of Players_Participants class MyUser(AbstractBaseUser): user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) def __str__(self): return str(self.user_name) class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE,related_name='host') game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) Players_Participating=models.ManyToManyField(MyUser,related_name='related') def __str__(self): return str(self.Host) class MyUserViewSet(viewsets.ViewSet): def create(self,request): user_name=request.data.get('user_name') user=MyUser() user.user_name=user_name return Response({"response":'delivered'}) class SessionViewSet(viewsets.ViewSet): def create(self, request): Host= request.data.get('Host') Sport = request.data.get('Sport') Players_Participating=request.data.get('Players_Participating') new=Session() new.Host=MyUser.objects.get(user_name=Host) new.Sport=Sport new.Players_Participating=Players_Participating new.save() def list(self,request): users = Session.objects.all() use = [] player_list=[] for user in users: for players in user.Players_Participating.all(): player_list.append(players.user_name) use.append({ 'Host':user.Host.user_name, "Sport":user.Sport, "Players_Participating":player_list, }) return Response({"success":True, "users":use, "pages":paginator.num_pages}) -
Include 0 to a annotate count if not found in django Queryset.?
I don't know how to phrase my question correctly but what I am doing is I am querying a table based on certain id and then getting the count of the unique field in a column and that count I am giving to matplotlib to plot but what problem I am facing is if a certain value is not found the label size mismatches with the count and plot doesn't work. Below is my query: workshop_feedback = WorkshopFeedbackResponse.objects.filter(workshop_conducted=workshop_id) count = workshop_feedback.values('q1').annotate(count=Count('q1')) sizes = [item['count'] for item in count] #converting to list for matplotlib bar char labels = [1,2,3] #option of choices for q1 fig, ax = plt.subplots() ax.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.savefig(os.path.join(settings.BASE_DIR, filename)) #filename is random image filename Which i am creating image of the graph My column name is q1 and it can contain 1,2,3 as an option depending upon what user has filled but suppose if I don't have 1 or either option the count doesn't reflect that. Exception Value: 'label' must be of length 'x' Above is the error I get from if count of certain value is missing. So How to get … -
Django: 'HttpResponseRedirect(reverse())' redirects to the same page
HttpResponseRedirect(reverse('success')) leading to the same page which requested with URL changed. views def dashboard_tools(request): ... if request.method == "POST": ... return render(request, "tools/loading.html", {}) # return redirect('success') # return HttpResponseRedirect(reverse('success')) return render(request, "tools/dash_tools.html", {'data':all_entries}) def success(request): return render(request, "tools/loading.html", {}) urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'$',tools.views.dashboard_tools,name="tools"), url(r'^success/', tools.views.success, name="success"), ] The return render(request, "tools/loading.html", {}) redirects to correct page but return redirect('success') and return HttpResponseRedirect(reverse('success'))fails to do so. The redirect and HttpResponseRedirect redirects to the same page with url http://127.0.0.1:8000/success/ -
'QueryDict' object has no attribute 'user'
I'm currently working on my project in Django, I need the foreign key (designation) to be displayed respective to the current user. It displays perfectly fine just like I wanted, but it throws an error while I submit the form, 'QueryDict' object has no attribute 'user'. forms.py def __init__(self,req,*args,**kwargs): super(EmployeeForm,self).__init__(*args,**kwargs) self.fields['designation'].queryset = req.user.designation.all() views.py form = DesignationForm(request) -
Initial Value of Select2Multiple widget
I am working on a searchinput with additional parameters given through a django autocomplete light Select2Multiple widget. class SearchParameterForm(forms.Form): p = forms.MultipleChoiceField( widget=autocomplete.Select2Multiple(url='search-parameter-autocomplete'), label='Search Parameter', required=False, ) & class SearchParameterAutocomplete(LoginRequiredMixin, autocomplete.Select2ListView): def get_list(self): parameter_list = ['only stocked'] for my_storage in Storage.objects.filter(workgroup=self.request.user.profile.workgroup).all(): for workgroup in my_storage.workgroup.all(): parameter_list.append(workgroup.name) return list(set(parameter_list)) I would like to set the initial value of the Widget depending on some parameters (e.g. self.request.user.profile.workgroup.name) Setting the initial value of the field either directly in the class with some dummy values or in the view did not work. I would also like to store the selected values on page refresh. initial = {"id": "AK2", "text": "AK2"} initial = ['AK1'] initial = 'AK1' Is there a way to do this with django or jquery? ~Fabian -
Redirected to same page after POST method django
I am creating this project in django. I am working on reporting films, where I go to a film-detail view, then hit the report button. A report_form shows up where I justify why I am reporting, and then I click report. Everything works fine, but there is one thing. After reporting I get sent back to a random(?) film-detail view, but I would like to go back to the view for the film I am reporting. But how??? views.py class FilmReportView(LoginRequiredMixin, CreateView): model = Report fields = ['reason'] def form_valid(self, form): form.instance.reporter = self.request.user form.instance.reports_id = self.kwargs['pk'] return super().form_valid(form) def get_success_url(self): return "film/<int:pk>/report" report_form.html {% extends "board/base.html" %} {% load crispy_forms_tags %} {% load materializecss %} {% block content %} <div class="valign-wrapper row login-box"> <div class="col card hoverable s10 pull-s1 m6 pull-m3 l8 pull-l2"> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="card-content"> <span class="card-title">Jusity why you want to report this film?</span> <div class="row"> {{ form|materializecss }} </div> </div> <div class="card-action right-align"> <input type="reset" id="reset" class="btn-flat grey-text waves-effect"> <input type="submit" class="btn green waves-effect waves-light" value="Report"> </div> </form> </div> </div> {% endblock content %} urls.py urlpatterns = [ path("", views.films_view, name="board-home"), path("film/add", FilmAddView.as_view(), name="film-add"), path("film/<int:pk>/", FilmDetailView.as_view(), name="film-detail"), path("film/<int:pk>/report", FilmReportView.as_view(), name="film-report"), ] … -
What extraordinary feature can I add to my web page?
I am making a job portal as a mini-project. I wanted to add an extraordinary feature that is not in most job portal website. I am making it using Django in the backend. -
Password Reset email is only sent the host email only in django 2.x
I've added a functionality to my django application, to send gmail(google mail) to user who forgot their password, But, it only sends email to the user I've added in the settings.py file of my project.Can you resolve this problem to mail to all users who request to reset their password? This is the variables, I added in the settings.py file. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_USER') -
How to define default field value but not on database level?
I want to have default value of text field being calculated for user. Eg. Now year=2020, so User choice would be 2020 and 2021 in dropdown field. But in next year(2021) I want to have 2021 and 2022 values to be only possibile choices. Field is defined like this in models.py: year = models.CharField(default=default_year(), max_length=4, choices=year_choices(), ) where: def default_year(): return str(datetime.now().year) def year_choices(): current_year = datetime.now().year years = [] years.append([str(current_year), str(current_year)]) years.append([str(current_year + 1), str(current_year + 1)]) return tuple(years) So it works for now, but because of migration it will not change in next year, right? Whats causing trouble is migration: migrations.AlterField( model_name='movie', name='year', field=models.CharField(choices=[['2020', '2020'], ['2021', '2021']], default='2020', max_length=4), ), How to avoid appying hardcoded values in migration file, or set calculted values in form in other way? -
How to make Dynamic Carousel in django using Bootstrap 4
I'm trying to make dynamic carousel in django using Bootstrap 4. But still i can't do that. Anyone please help to done it. Thanks. views.py def dept(request, name): dept_detail = department_detail.objects.get(name = name ) depts_detail = departments.objects.get(name = name ) course = depts_detail.course_set.all() carousel = depts_detail.carousel_set.all() context = {'dept': dept_detail, 'courses':course, 'carousel':carousel} return render(request, "Departments/dept.html", context) models.py class carousel(models.Model): Department = models.ForeignKey(departments,on_delete=models.CASCADE, null = True) Image = models.ImageField(upload_to='Carousel', null = True) Img_title = models.CharField(max_length=30, null=True) Img_desc = models.CharField(max_length=500, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.Department.name template <div id="gallery" class="carousel slide carousel-fade" data-ride="carousel" data-aos="fade-up" data-aos-delay="300"> <ul class="carousel-indicators" > <li data-target="#gallery" data-slide-to="0" class="active"></li> <li data-target="#gallery" data-slide-to="1"></li> <li data-target="#gallery" data-slide-to="2"></li> </ul> <div class="carousel-inner"> {% for img in carousel %} <div class="carousel-item active" data-interval="100"> <img src="{{img.Image.url}}" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block rounded position-absolute bg-custom"> <h5>{{img.Img_title}}</h5> <p>{{img.Img_desc}}</p> </div> </div> {% endfor %} </div> -
How to fetch data from manytomany field django
As i have many user. i want to fetch the name of users join a particular session in Players_Participating class MyUser(AbstractBaseUser): user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) def __str__(self): return str(self.user_name) class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE,related_name='host') game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) Players_Participating=models.ManyToManyField(MyUser,related_name='related') def __str__(self): return str(self.Host) -
Need _id from mongodb in django from models where object id is exists
I am using MongoDB in Django. i need to return _id (the object field). in mongdb database for every entry their is a _id was created which is a 32 bit object id. i need that value. _id:ObjectId("5e6b77d580a32dff7bb1ef11") this value of every entry in mongodb. data1=Filter_data.objects.get(user_id=raw_data["user_id"],post_id=raw_data["post_id"]) -
Django - Select MAX of field of related query set
Say if I have models: class User(models.Model): name = ... dob = ... class Event(models.Model): user = models.ForeignKey(User, ...) timestamp = models.DateTimeField() And I want to query all Users and annotate with both Count of events and MAX of Events.timestamp I know for count I can do: Users.objects.all().annotate(event_count=models.Count('event_set')) But how do I do max of a related queryset field? I want it to be a single query, like: SELECT Users.*, MAX(Events.timestamp), COUNT(Events) FROM Users JOIN Events on Users.id = Events.user_id -
Partial search using wildcard in Elastic Search
I want to search on array value in Elastic search using wildcard. { "query": { "wildcard": { "short_message": { "value": "*nne*", "boost": 1.0, "rewrite": "constant_score" } } } } I am search on "short_messages", It's working for me. But I want to search on "messages.message" it's not working. { "query": { "wildcard": { "messages.message": { "value": "*nne*", "boost": 1.0, "rewrite": "constant_score" } } } } And I also want to search for multiple fields in an array. For Example:- fields: ["messages.message","messages.subject", "messages.email_search"] It is possible then to give me the best solutions. Thanks in Advance. -
How to Add Auti fields that user can edit
I am creating an model in this I need a autogenerated field other than id .... An AutoField Seequnce #. Auto increment # 10,20,30, - For sequencial ordering. (Auto Generated -but user can edit ) It need to increment on the basis of 10 also the user can able to edit it ..... It's my rquirement Here is my model : class Abc(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) order = models.AutoField() How to generate it on the basis of 10... Also how can user edit it -
Combination custom filter with many to many
class MyText(models.Model): myId = models.CharField(unique=True,null=False,max_length=20) tags1 = models.ManyToManyField(Tag1) tags2 = models.ManyToManyField(Tag2) I have model which has two many-to-many field. class MyTextFilter(filters.FilterSet): tags1 = filters.ModelMultipleChoiceFilter( field_name='tags1__name', queryset=Tag1.objects.all(), ) tags2 = filters.ModelMultipleChoiceFilter( field_name='tags2__name', queryset=Tag2.objects.all(), ) class Meta: model = MyText fields = ('myId','tags1','tags2') Now I want to make the filter that drop the rows which doesn't have either tags1 nor tags2. How can I make combination custom filter?? -
unhashable type: 'ReturnDict' drf django
I'm trying to add but getting this error: unhashable type: 'ReturnDict' models.py: class SumInsuredEntity(UUIDBase): field_name = CICharField(max_length=255,null=False,blank=False,verbose_name=_("Field Name"), unique=True) is_balance = models.ForeignKey(ValidChoice, to_field="key", db_column="is_balance", related_name="is_balance", null=True, blank=True, verbose_name=_("Is Balance"),default='no', on_delete=models.DO_NOTHING) is_thresold = models.ForeignKey(ValidChoice, to_field="key", db_column="is_thresold", related_name="is_thresold", null=True, blank=True, verbose_name=_("Is Thresold"),default='no', on_delete=models.DO_NOTHING) status = models.SmallIntegerField(_("Status:1 for Active; 0:InActive"), default=1) class Meta: db_table = "tpa_master_sieav" def __str__(self): return str(self.uid) Views.py: @api_view(['POST']) def sumInsuredEntityAdd(request): ''' sumInsuredEntity Create Api ''' data= decode_data(request.data.copy()) serializer_obj = SumInsuredEntitySerializer(data=data) if serializer_obj.is_valid(raise_exception=True): try: sumInsured_save = serializer_obj.save() return CustomeResponse(request=request, comment=SUM_INSURED_ENTITY_ADDED_SUCCESSFULLY,data=json.dumps({serializer_obj.data}, cls=UUIDEncoder), message= SUM_INSURED_ENTITY_ADDED_SUCCESSFULLY, status=status.HTTP_200_OK) except Exception as e: print(e) return CustomeResponse(request=request, log_data=json.dumps(str(e), cls=UUIDEncoder), comment=COULD_NOT_SAVE_SUM_INSURED_ENTITY, message=COULD_NOT_SAVE_SUM_INSURED_ENTITY, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) else: return CustomeResponse(request=request, comment=FIELDS_NOT_VALID, message=FIELDS_NOT_VALID, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) its working good but showing error when trying to dump serializer_obj.data -
How to model this relationship in Django Models
I’m developing a web application that is developing products, the issue is the products available should be activated at three levels. The company should be able to turn individual products on or off. Each organization should be able to turn the individual product (from only the allowed on the previous level) on or off. The administrator can activate the product availability on or off for a specific user. How would you recommend to design this at the level of models? -
Real-time audio streaming from javascrit to python-django
i want to record client's microphone in the browser with javascript and send it in real-time to process the audio stream in python. Is django able to do this in real-time? Thank you! -
What is the difference between django3 and django2 for the admin site
I created two python virtual environments on centos with django2 and django3 installed。 Python 3.7.0 Package Version ---------- ------- Django 2.2.2 pip 20.0.2 pytz 2019.3 setuptools 45.3.0 sqlparse 0.3.1 wheel 0.34.2 Package Version ---------- ------- asgiref 3.2.5 Django 3.0.3 pip 20.0.2 pytz 2019.3 setuptools 45.3.0 sqlparse 0.3.1 wheel 0.34.2 Enter the two virtual environments separately, and create the django project using the command django-admin startproject test_project, and then launch it using the command python manage.py runserver 0.0.0.0:8000. Access to the admin site using a browser, django version 2.2.2 success. version 3.0.3 program exit, I tried to add --noreload after the instruction, access again, the program exit, and terminal print segment error (vomit a nuclear). I tried switching to the virtual environment to launch the same django project, and the same thing happened. Access to the admin site with version 3.0.3 of django failed. After looking at the two settings.py, there seems to be no difference. So I'm a little confused. Is there any additional configuration parameter in settings.py for django3? """ Django settings for newrecord project. Generated by 'django-admin startproject' using Django 3.0.3. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, … -
Email forms do not match in Django Custom-User registration
I'm setting up a custom-user registration form to create an account on my Django project. I feel I'm missing something very simple that keeps me from registering for some reason. My registration form demands 4 fields to be filled before a new user can register. Of these 4 fields, two are just a confirmation of the email address. Here is a copy of my form.py: class UserRegisterForm(forms.ModelForm): username = forms.CharField(label='Username') email = forms.EmailField(label='Email Address') email2 = forms.EmailField(label='Confirm Email') password = forms.CharField(widget=forms.PasswordInput) class Meta: model = CustomUser fields = ['username', 'email', 'email2', 'password'] def clean_email(self): email = self.cleaned_data.get('email') email2 = self.cleaned_data.get('email2') if email != email2: raise forms.ValidationError("Emails do not match") And here is a copy of my view.py: def register_view(request): next = request.GET.get('next') form = UserRegisterForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get('password') user.set_password(password) user.save() new_user = authenticate(username=user.username, password=password) login(request, new_user) if next: return redirect(next) return redirect('/stocks/') Whenever I try to register as a new user, my form validation error is raised as is says that my two emails do not match (I copy-paste them to make sure they are identical). I feel I'm missing something that is right under my nose... Cheers to all of you and … -
Django, how to store and retrieve credit card information in Stripe and use it for later charges?
I am working on an e-commerce website project and I am stuck here. Although I looked at the documentation but it wasn't helpful for me using Django. All I learned was to store customer id in my side and use it for later charges. I don't know how to fetch customer cards from stripe API, whether they exists or not? save it and use for future purchase? Thank you for help and support! -
DRF hyperlinkedmodelserializer cannot find view name
I am converting from ModelSerializer to HyperlinkedModelSerializer, following this document(https://www.django-rest-framework.org/api-guide/relations/) board # board/urls.py app_name = 'board' urlpatterns = [ path('boards/', BoardList.as_view(), name='board-list'), path('boards/<int:pk>', BoardDetail.as_view(), name='board-detail'), path('', api_root), ] urlpatterns = format_suffix_patterns(urlpatterns) # board/views.py @api_view(['GET']) def api_root(request, format=None): return Response({ 'boards': reverse('board:board-list', request=request, format=format) }) class BoardList(generics.ListCreateAPIView): queryset = Board.objects.all() serializer_class = BoardSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] # author = serializers.PrimaryKeyRelatedField( # read_only=True, default=serializers.CurrentUserDefault() # ) author = serializers.HyperlinkedRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) def perform_create(self, serializer): serializer.save(author=self.request.user) class BoardDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Board.objects.all() serializer_class = BoardSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsAuthorOrReadOnly] # board/serializers.py class BoardSerializer(serializers.HyperlinkedModelSerializer): # author = serializers.PrimaryKeyRelatedField( # read_only=True, default=serializers.CurrentUserDefault() # ) author = serializers.HyperlinkedRelatedField( view_name='user-detail', read_only=True, default=serializers.CurrentUserDefault() ) url = serializers.HyperlinkedIdentityField(view_name="board:board-detail") class Meta: model = Board # fields = ('id', 'author', 'title', 'body', 'image', 'created','updated') fields = ('url','id', 'author', 'title', 'body', 'image', 'created','updated') users # users/serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): # boards = serializers.PrimaryKeyRelatedField( # many=True, queryset=Board.objects.all() # ) boards = serializers.HyperlinkedRelatedField( view_name='user-detail', many=True, queryset=Board.objects.all() ) url = serializers.HyperlinkedIdentityField(view_name="users:user-detail") class Meta: model = User # fields = ('id', 'username', 'boards') fields = ('url', 'id', 'username', 'boards') I got this error, ImproperlyConfigured at /boards/ Could not resolve URL for hyperlinked relationship using view name "board-detail". You may have failed to include the related model in … -
Open link in new internal windows django, python
I need create web site with some links to another resources and I would like when visitor click in one of this links the new windows(pop up) is opened in the same page, and then visitor can close this window and open another link ... in python and django its possible?