Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am new to virtual environments and successfully installed virtualenv-win through CMD....aslo created an environment named ( Samim )
After creating the environment I accidently closed cmd. now I want to reopen the ( Samim ) environment but cant find the command to reopen it , please help me. I tried to check if that envionment existed or nor by typing "lsvirtualenv" it returned dir /b /ad "C:\Users\User\Envs" ================================================ Samim So it is present in the system , how can I activate this env ? -
How do I access the files from a ffmpeg_streaming PUT request in Django?
I'm trying to stream video from my webcam using a python package called ffmpeg_streaming and Django2.0. I can see the request being received on the server side but I can't access the actual files in views. This is my views.py @csrf_exempt def stream_video(request): stream = QueryDict(request.body) print("Stream: ", stream) print('Stream:' , stream) data = {'stream': 'streaming...'} """ if hasattr(request, '_post'): del request._post del request._files try: request.method = 'POST' file = request._lost_post_and_files() request.method = 'PUT' except(AttributeError): request.META['REQUEST_METHOD'] = 'POST' request._load_post_and_files() request.META['REQUEST_METHOD'] = 'PUT' request.PUT = request.POST """ file_ob = request.POST print('Files: ', file_ob) files = request.FILES print('Files:' , files) return JsonResponse(data) stream_video.py import ffmpeg_streaming video = ffmpeg_streaming.input('/dev/video0', capture=True) _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) hls = video.hls(Formats.h264(), hls_list_size=10, hls_time=5, method='POST', post_data='File') hls.flags('delete_segments') hls.representations(_480p) hls.output('http://127.0.0.1:8000/stream_video/out.m3u8') How would I go about accessing the files and treating them as uploads? -
How to fix image is not showing in heroku deployed django app
I have a Blog created with Django 3.x. When I run the project on my local server then it works fine. So, I deployed my project to heroku and here is the link bblog-shovon.herokuapp.com/. Then the project was working fine. My project git link https://git.heroku.com/bblog-shovon.gitThen I created a post and then I gave it a thumbnail and finally everything was fine. But, After sometime when i revisit the site then every image were gone. I didn't found them. And when I tried to open the image on another tab then it shows this Error message screenshot. When I am writing this question then I created a new post and after publishing this this posts image is working. But, older image is not working. Then, How can i fix this problem? Please help me!! -
Is there any missing below codes?
from django.shortcuts import render from .models import Destination Create your views here. def index(request): dest1 = Destination.objects.all() return render(request,"index.html",{'dest1':dest1}) Error: from .models import Destination ImportError: cannot import name 'Destination' from 'travellor.models' (C:\Users\Raja Kumar\projects\telusko\travellor\models.py) can anyone help me out ? -
how to format JS object with Lodash
const _ = require('lodash'); org_data = [{ item: 'TESTING123', date: '2020-0610T00:00:00.000Z' },{ item: 'TESTING456', date: '2020-0610T00:00:00.000Z' }] function formating (rows, key='date') { return _.chain(rows).keyBy('item').mapValues(key).value() }; // output { TESTING123: 2020-0610T00:00:00.000Z, TESTING456: 2020-0610T00:00:00.000Z, } //expected output { 'TESTING123' : '2020-0610T00:00:00.000Z', 'TESTING456': '2020-0610T00:00:00.000Z', } Actually data is get by SQL query and item (models.TextField()) and date (models.DateTimeField()) in a django backend It seem that the JS object is broken , I wonder any solution for this case -
Django: How to retrieve the logged in user's details
I am in the process of learning Django. I am trying to create a simple directory web app. I am able to print out all the users details for the main directory page. However, I want to add a feature that when a person logs into the directory app they are brought to their 'profile' page where they will be able to see all their own details e.g. business name, profile pic. I know how to retrieve the default fields e.g. username and email. But cannot seem to retrieve the custom fields that I declared myself. Here is my attempts so far... Models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.DO_NOTHING) #additional classes business_name = models.CharField(max_length=191,blank=True) trade = models.CharField(max_length=191,blank=True) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return self.user.username Views.py: @login_required def profile(request): profile = UserProfileInfo.objects.filter(user=request.user) context = { 'profile': profile } return render(request, 'dir_app/profile.html',context) Profile.html: <div class="container-fluid text-center"> {% for p in profile %} <h3>{{p.business_name}}</h3> {% endfor %} </div> -
How to make None callable?
class ObjectCreateMixin: model_form = None template = None def get(self, request): form = self.model_form() return render(request, self.template, context={'form': form}) self.model_form is not callable How to make None callable? -
Django sitemap for multilanguage website posts filter
I try to seperate my post on lang. in sitemap. but But for example, if there are 3 languages (en,fr,de), each post three added in sitemap. example my_sample_post_english in db language option "en" my_sample_post_french in db language option "fr" my sitemap create like this; <url> <loc>http://127.0.0.1:8000/en/post/vote/my_sample_post_english</loc> <lastmod>2020-05-19</lastmod> <priority>0.5</priority> </url> <url> <loc>http://127.0.0.1:8000/fr/post/vote/my_sample_post_english</loc> <lastmod>2020-05-19</lastmod> <priority>0.5</priority> </url> <url> <loc>http://127.0.0.1:8000/de/post/vote/my_sample_post_english</loc> <lastmod>2020-05-19</lastmod> <priority>0.5</priority> </url> how can i filter post for languages? i want like this; <url> <loc>http://127.0.0.1:8000/en/post/vote/my_sample_post_english</loc> <lastmod>2020-05-19</lastmod> <priority>0.5</priority> </url> <url> <loc>http://127.0.0.1:8000/fr/post/vote/my_sample_post_french</loc> <lastmod>2020-05-19</lastmod> <priority>0.5</priority> </url> <url> <loc>http://127.0.0.1:8000/de/post/vote/my_sample_post_deutsch</loc> <lastmod>2020-05-19</lastmod> <priority>0.5</priority> </url> url.py urlpatterns += i18n_patterns( ... path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ... ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) sitemaps.py class BlogSitemap(Sitemap): priority = 0.5 # this generates urls per language i18n = True def items(self): posts= Post.objects.filter(private=False) for b in posts: if b.language == 'en': b.language = str('en/') + b.language if b.language == 'fr': b.language = str('fr/') + b.language if b.language == 'de': b.language = str('de/') + b.language return posts def lastmod(self, obj): return obj.created_date model.py class Post(models.Model): title = models.CharField(max_length=350,verbose_name="PostTitle") slug = models.SlugField(unique=True, max_length=353, null=True) language = models.CharField(max_length=30, choices=settings.LANGUAGES, default="en") private = models.BooleanField(blank=True, default=False, verbose_name="Private Post") def get_absolute_url(self): return reverse('post:addVote', args=[str(self.slug)]) -
Django to call the correct function
been searching a lot for fixing my issue.. New to django and might be missing a very simple logic here and looking for some help.. I have created a form in html page called thispage.html as below: <form action="{% url 'getvaluefromform' %}" method="POST">{% csrf_token %} <input type="text" name='mytitle' placeholder="enter title"> <input type="submit" value="save"> </form> then I updated views.py with the below code: from django.shortcuts import render def index(request): return render(request,'thispage.html') def getvaluefromform(request): mytitle = request.POST.get('mytitle') print(mytitle) return render(request,'thispage.html') finally my urls.py has this part: from dhango.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), path('getvaluefromform',views.getvaluefromform,name='getvaluefromform') ] Problem: when I use this I am able to get the input vallue however the url is changing to '/getvaluefromform' and when I remove 'getvaluefromform' from the url section and just keep it '' then the code view index gets picked up. Is there a way I can call the second function when button is clicked without moving to the new path. Please advise. P.S - I am deliberately not using a model form because I want to build a raw sql query based on user input and then run the query to get the results/ create a new table on the … -
create multible recored related to parent automaticaly django python
i want to do the following: 1- create one table contain all transactions of my project ==> table name "batch" ==> done 2- when i create new transaction in any model of my project it will create batch then create transaction and refere batch num in the transaction. ==> done ** the following is my problem: 3- i want after save re direct to the same page of creation instead of using url detail from get_absolute_url 4- also i want to complete in the same batch "in php usualy i redirect page to creationURL/Batch_Num then split Batch_number from url in view" here is my view code class Invoice(LoginRequiredMixin, CreateView): template_name = 'Create.html' form_class = InvoiceForm def form_valid(self, form): # Note: Create Batch number for new transaction batch_num, created = H010001.objects.get_or_create( table_name = "Invoice", created_by = self.request.user, updated_by = self.request.user, number_of_documents_created = 0, ) # Note: Create new transaction & assign batch numb form.instance.created_by = self.request.user form.instance.updated_by = self.request.user form.instance.batch_number = batch_num # Note: Increase Creation Document number of batch batch_num.number_of_documents_created += 1 batch_num.save() return super().form_valid(form) and here is my get_absolute_url code in model: def get_absolute_url(self): return reverse("detail", kwargs={ 'pk': self.pk }) -
Django Rest Framework : prefetch_related doesnot work as expected with serializer
I have two models class Book(models.Model): name = models.CharField(max_length=50) author = models.ForeignKey(Author) class Author(models.Model): name = models.CharField(max_length=50) then a prefetch_related queryset is created as follows Author.objects.all().prefetch_related("book_set") Then a serializer is created for the Author and book_set is added to serializer field like this class AuthorSerial(serializers.ModelSerializer): class Meta: model = Author fields = ('name' ,'book_set') But this only return list of book ids as nested serializer and not the rest of data with it such as name like below. { name:'john', book_set:[1,2,3] } Is there any way to solve this to get the data as name:'john', book_set:[{id:1,name:'Book 1'},{id:2,name:'Book 2'},{id:3,name:'Book 3'}] } Also what to do if I have to further filter these prefetch -
Unable to log in to django admin
I know this question has been asked before, but either I don't understand how to apply the solutions provided or they don't work. I think my case may be much simpler. I am a beginner with Django and I'm following first the djangogirls tutorial. I installed Django in a virtual environment that I created with conda. The first time I tried it, I was perfectly able to create a superuser and log in to the account successfully. However, that time I created the project in C:\Users\User\ and it was not very organized since there were a whole lot of files and folders there along with the project. Now, I created a second virtual environment and a new project, which is in F:, another partition of the same drive. I did everything I had done the first time, but when I tried to log in to the admin page, I get a message saying the credentials are incorrect. Actually, I created other two superusers (successfully), but always get the same message. I also created a third virtual environment and project (in the same partition where the OS is not), this time with pip, to follow exactly the same process in the … -
Pass the POST data through the views DRF
My problem is how to pass POST data through the class based views(DRF ApiView). I’m doing a multi step form, and views should have an access to the form data on all steps. The only limitation, I can’t use self.request.session. So summarizing all the information, how can I make my views more restful, that, for example, first step view give all the data to the second step view? If you need code examples, I’ll give it to you. -
The footer of the page is overlapping with the images django
I am trying to do a simple website were the images act like links to another template where you can watch a video, but the footer gets in the way, instead of staying at the bottom of the page it goes up and putting itself behind the pictures.and I am not sure why, I have been looking around but I could not find an clear answer. I am also still learning at the moment, in here you could find teh same questions but with some pictures so you can see what I mean. https://es.stackoverflow.com/questions/362790/the-footer-of-the-page-is-overlapping-with-the-images-django in order to keep the footer in place. I have to add a line of text which if the amount of pictures if odd it kind of stay in the site the html is {% extends "TresAcordesApp/base.html" %} {% load static %} {% block content %} <h1 style="text-align: center;"><p style="color: rgba(0, 95, 0, 0.8);">Temporada Cero</p></h1> <div style="width: 33%; float: left"> <h4 style="margin-left: 2.5cm; color: rgba(0, 95, 0, 0.8); ">Videojuegos</h4> <a href="{% url 'Videojuegos' %}"> <img title="Videojuegos" src="{% static 'TresAcordesApp/img/Videojuegos.jpg' %}" height="250px" width="250px" style="margin-left: 2.5cm;" alt=""> </a> </div> <div style="width: 33%; float: left"> <h6 style="margin-left: 2.5cm; color: rgba(0, 95, 0, 0.8); ">El Día Que Fleko Se Convirtio … -
Django - How do I annotate the count of multiple foreign key fields (within 1 model) to same model
I am trying to annotate the count of two foreign key fields, incorporation_country and acquired_country (both linked to Country model). The fields are within the same model (CustomerInformation). Below is my models.py for reference class Country(models.Model): country_id = models.AutoField(primary_key=True) country = models.CharField(max_length=500) class CustomerInformation(models.Model): customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100) incorporation_country = models.ForeignKey('Country', related_name='customers_incorporation', on_delete=models.CASCADE, null=True, blank=True) acquired_country = models.ForeignKey('Country', related_name='customers_acquired', on_delete=models.CASCADE, null=True, blank=True) What I would want to accomplish is to get CustomerInformation.objects.all() and from there, annotate to get the count of each country for incorporation_country and acquired_country. For example, I would want the output to be something like : [{ 'country': 'Singapore', 'incorporated_count': 5, 'acquired_count': 3 }, { 'country': 'Taiwan', 'incorporated_count': 4, 'acquired_count': 7 }] All help is appreciated, thanks all! -
Django Ajax views.py cannot get the Object ID and returns 404 instead
Hi I am trying to ajaxify my comment function of my blog app in Django. Right now the code works fine except one part: I am not able to transmit the Object ID I want to access to my views.py file. When I hardcode the Object ID everything works fine. views.py file: (When I replace pk=request.POST.get('post_id') with the actual obj ID everything works!) @login_required def comment_create(request): post = get_object_or_404(Post, pk=request.POST.get('post_id')) user = get_object_or_404(User, username=request.user) comment_form = CommentForm() if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.author = user new_comment.save() else: comment_form = CommentForm() if request.is_ajax(): html = render_to_string('feed/comment_section.html', {'post': post}, request=request) return JsonResponse({'form': html}) The comment form in my html: <div> <form class="comment-form" action="{% url 'comment-create' %}" method="POST"> <div class="row"> {{ comment_form.as_p }} {% csrf_token %} <button type="submit" name="post_id" value="{{ post.id }}" class="btn btn-info">Submit</button> </div> </form> </div> My jQuery event handler: $(document).on('submit', '.comment-form', function(event){ event.preventDefault(); console.log($(this).serialize()); $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), dataType: 'json', success: function(response) { $('#comment-section').html(response['form']); console.log($('#comment-section').html(response['form'])); }, error: function(rs, e){ console.log($(rs.responseText)); }, }); }); I tried various things but I do not know how I can make sure the post_id gets handed over to my comment_create() function.. -
Django POST IntegrityError at /add_trade/
I am currently getting into Django Forms which seems to be super cool basically. I tried to set up a quiet simple form to post some data to my database. Later on I will have a form that contains around 20 input fields of different types. Right now my approach raises the following error: IntegrityError at /add_trade/ ERROR: NULL-Value in column »balance« causes Not-Null-Constraint Although I did define all Model fields to blank=True HTML <form action="/add_trade/" method="POST"> {% csrf_token %} <div id="headline"> <div id="input_instrument_wrapper" class="headline_wrapper"> <input type="text" name="instrument" id="instrument_input" placeholder="Insert instrument"> </div> </div> </form> Models.py from django.db import models # Create your models here. class add_trade(models.Model): instrument = models.CharField(max_length=100, blank=False) sector = models.CharField(max_length=100, blank=True) [...] [...] margin_blocked = models.FloatField(max_length=20, blank=True) exposure = models.FloatField(max_length=20, blank=True) class Meta: db_table = 'planned_trades' Forms.py from django import forms from .models import add_trade class TradeForm(forms.ModelForm): class Meta: model = add_trade fields = ('instrument',) Views.py from django.shortcuts import render from .models import add_trade from .forms import TradeForm def add_trade(request): if request.method == 'POST': form = TradeForm(request.POST) # A form bound to the POST data if form.is_valid(): form.save() # saves a new 'add_trade' object to the DB Why is that? I didn't include the balance input field … -
Is it possible to generate 2 different login authenticators django
I am fairly new to django and I am trying to develop a web based game. I want the game to have 2 seperate log ins, one for a user log in and one for a character 'selection', obviously I can't go to the character selection without requiring the login_required decorator, but at the same time I want to make the rest of my website based upon the "character" and therefore I essentially need another login(character)_required, I was wondering if there is simpler way to do this rather than trying to rewrite djangos login functionality. I would appreciate it if I could be pointed in the right direction! -
Return variable from models.py to views.py other files
I made a form you have to fill out when uploading a file. Im using the email from the form to create a folder named after the email and i upload the file inside. In my models.py def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.email, filename) class User(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) pdf = models.FileField(upload_to=user_directory_path) def __str__(self): return self.title Im using user_directory_path to create the user_folder. I now want to do some processing on that data but i need that exact path. I have a separate file that does all the processing user_processing.py or a function inside views.py for example. In that file im importing models.py with from mysite.core.models import user_directory_path Im getting an error. ImportError: cannot import name 'print_filename' from 'mysite.core.Project_x' How do i import a function/ pass a variable from the models.py function into another file? -
Django - create profile for all existing users
i'm using Django 3 , this is my userprofile model from django.db import models from django.contrib.auth.models import User from datetime import datetime from django.db.models.signals import post_save from django.utils.text import slugify from django.db.models import signals # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=1000,blank=True) created_at = models.DateTimeField(default=datetime.now()) slug = models.SlugField(blank=True) img = models.ImageField(upload_to='userimg/',default='userimg/avatar.png') def __str__(self): return "%s" % self.user def save(self, *args, **kwargs): self.slug = slugify(self.user) super(Profile, self).save(*args, **kwargs) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.get(user=instance) post_save.connect(create_user_profile, sender=User) def delete_user(sender, instance=None, **kwargs): try: instance.user except User.DoesNotExist: pass else: instance.user.delete() signals.post_delete.connect(delete_user, sender=Profile) the problem is that the function create_user_profile create profiles only for the new users but doesn't create for the old users , so how can i fix that ? -
Filer Image Compression
How will I compress the images which are getting uploaded through Django-filer in Django cms? I already have the code for image compression but don't where to put in Django cms as I am new to it. -
Django auocomplete lgith shows duplicated forms
I'm using the package Django Autocomplete Light and the strange this it shows 2 of the same form Here is my code : Autocomplete View class ShiftAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Shift.objects.filter(employee__isnull=True) if self.q: qs = qs.filter(branch__name__icontains=self.q) return qs urls.py and here is how I created a URL for it : path('shift_autocomplete/', branches_views.ShiftAutoComplete.as_view(), name='shift_autocomplete'), forms.py here is where I used the autocomplete field in the form class ShiftAssignToEmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ['salary', 'shift'] widgets = { 'shift': autocomplete.ModelSelect2(url='shift_autocomplete') } views.py class ShiftAssignToEmployee(SuccessMessageMixin, UpdateView): model = Employee form_class = ShiftAssignToEmployeeForm template_name = 'back_office/assign_shift_to_employee.html' success_message = _('Shift has been assigned successfully .') And finally the HTML : <form method="post" class="col s12"> {% csrf_token %} <div class="row"> <div class="input-field col s12"> {{ form.shift }} </div> </div> <div class="row"> <div class="input-field col s12"> <i class="material-icons prefix">chrome_reader_mode</i> {{ form.salary }} <label for="id_salary">{% trans 'Salary' %}</label> </div> <button type="submit" class="btn"> <i class="material-icons">send</i> {% trans 'Submit' %}</button> </div> </form> <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> {{ form.media }} so far so good, but the strange thing that in HTML there are 2 forms for the branch, once that looks like a normal SELECT widget with no options at all, and another one that … -
Login required in django
I am developing ecommerce website in django . I have view ( addToCart) I want sure before add to cart if user logged in or not so that i use @login_required('login') before view but when click login it show error (can't access to page ). Note that: normal login is working -
Django - delaying the form submission to prefill some data using javascript
I'm trying to fill in the latitude and longitude of my form with the geocode function which converts an address to latitude and longitude coordinates. I want my form submission to be delayed whilst the geocode function prefills the latitude and longitude fields. I know my geocode works because 'return false' fills the latitude and longitude fields in properly. Here is my delay code below: $('#form').submit(function() { geocode(); console.log('function ran.'); return true; }); Through experimentation by using 'return false', my console.log(Function ran.) prints before the console.log in my geocode function. I've tried using async functions but it still isnt' prefilling the fields quickly enough before form submission. $('#form').submit(async function() { await geocode(); //geocode isn't running fast enough; console.log('function ran.'); return true; }); async function geocode() { console.log("geocode"); } How do I correctly delay the return true function to execute after my geocode function has finished? -
How to pass a permission via Django Rest API?
I would like to create a custom permission that return true / flase depending on whether the user is the author of a story or not and pass this information via the restAPI. So when the author is requesting a story where he is not author the permission returns "false" and i can access these information IsStoryOwner: "False"via my API. Something like this should be the result: "user": { "id": 35, "username": "HII", "user_permissions": [ IsStoryOwner: "False", ] } However i struggle to implement that. I wrote the following permission: class IsStoryOwner(permissions.BasePermission): """ Check if authenticated user is story author """ def has_object_permission(self,request,obj,**kwargs): if request.user.id == story.author: return True return False Than i integrated the permission in my UserAPI class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, IsStoryOwner ] serializer_class = UserSerializer def get_object(self): return self.request.user However the permission is not appearing in my API and the "user_permissions": [] remains empty.