Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to enable/disable buttons in HTML jscript
I am trying to enable buttons on a web page using a js funtion for a django project. I am new this so please be cool :-) <input onclick="change(id)" type="button" value="Modify" id="11" class="btn btn-info"></input> <div class="btn-group" role="group" aria-label="Basic example"> <button type="button" class="btn btn-secondary" disabled="false" id="edit_11">Edit</button> <button type="button" class="btn btn-secondary" disabled="false" id="delete_11">Delete</button> </div> <br></br> <input onclick="change(id)" type="button" value="Modify" id="22" class="btn btn-info">/input> <div class="btn-group" role="group" aria-label="Basic example"> <button type="button" class="btn btn-secondary" disabled="false" id="edit_12">Edit</button> <button type="button" class="btn btn-secondary" disabled="false" id="delete_12">Delete</button> </div> <br></br> <script> function change(id) { var elem = document.getElementById(id); let newID = "edit_".concat(id) if (elem.value=="Undo") { elem.value = "Modify"; choiceEdit = document.getElementsByName(newID) choiceEdit.disabled = false } else { elem.value = "Undo"; choiceEdit = document.getElementsByName(newID) choiceEdit.disabled = true } } </script> What I would like to happen is for the name of the main button change from "Modify" to "Undo", which happens. But I'd also like for the two related Edit and Delete buttons to be enabled so as to press them. Anyone can tell me what I am doing wrong? Thanks! -
Use Django template tags with Alpine.js x-text
I'm using Alpine.js in my Django templates and so far I've been quite happy with the results. However, I would like to use Django template tags for instance floatformat on a value computed by Alpine.js. For now, I am formatting the number directly in Alpine.js and my code look like this: <div x-data="{rawNumber: 1.23456, get formattedNumber() { return Math.round(rawNumber + Number.EPSILON) * 100) / 100 } }"> My formatted number is <span x-text="formatNumber"></span> </div> What I'm looking for is a way to use Django template tags on the value computed by Alpine.js. A very naïve implementation (which of course generates error) would look like this: <div x-data="{rawNumber: 1.23456}"> My formatted number is {{ <span x-text="rawNumber"></span>|floatformat:2 }} </div> -
By using Django and allauth, how can we stop authentication of a user with same email address for two social accounts?
I am new to Django and was trying to implement the below-mentioned scenario which is as such: I have a google account as well as a facebook account with the same email address by using django-allauth. So if I am already logged in using google/facebook account and try to login from facebook/google i.e. the other social account in the same session, I should show that the user has already been logged in with this email ID. My approach is to set email and provider id in the session request and manipulate it in the pre_social_login signal in my social adapter. So far I have defined my middleware as such: middleware.py from django.contrib import messages class SimpleMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if request.path == '/accounts/login/' and request.method == 'GET' and not request.user.is_authenticated: if 'email' not in request.session: request.session['email'] = '' request.session['provider']='' request.session['is_active']='False' response = self.get_response(request) return response my_adapter.py from allauth import account from allauth.socialaccount.adapter import DefaultSocialAccountAdapter class MySocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): if request.session['email']=='' and request.session['provider']=='': request.session['email']=sociallogin.account.extra_data['email'] request.request.session['provider']=sociallogin.account.provider request.session['is_active']=False response = self.get_response(request) elif request.session['email']==sociallogin.account.extra_data['email'] … -
How to check file arrived in javascript and HttpResponse object django
Hi everyone and merry christmas Actually my code is working fine, but i can't figure out how to catch a file arrives message in javascript I'm working widh django 2.1 template: ... <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> ... <input type="file" id="prd" name="prd" required> </div> ... <input id="btn_ini" type="submit" name="submit" value="Init process"> </form> ... <script type="text/javascript"> document.addEventListener('???', function(){ // I wish indicate to the user that the process is runnning and don't close the page. // at the moment the logic is working as spected but I can't achieve how to check in javascript when file arrives. }) </script> </body> </html> #views def add_destination(request): ... if request.method == 'POST': ... return handle_uploaded_file(prd) return render(request, 'add-destination.html') def handle_uploaded_file(f) ... file = # processing file ... with open(file, 'rb') as f: file_data = f.read() response = HttpResponse( file_data, content_type='application/force-dowload') response['Content-Disposition'] = 'attachment; filename="proc_{}"'.format(incoming_file_name) return response return None -
Heroku Django Virtual Environment source code modification
I managed to deploy my django app (with mongodb as database) on heroku. But I need to modify some source code in django package in the virtual environment. How can I access to virtual environment created by heroku from requirements.txt ? Or maybe how can I upload directly the virtual environment to heroku and make sure that my GIT django app is working on it? thank you -
Getting "This Field is Required" line in my output of django template
As you can see in this picture, every field is having "This field is required" line which i do not want to print there. Can someone help? Picture.jpg -
Permission_classes([IsAdminUser]) is not working
My function based view has a permission class IsAdminUser, but any user can get the request, please explain where is mistake. from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, IsAdminUser @api_view(['GET']) @permission_classes([IsAdminUser]) def getUsers(request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) -
Crop mongo document with filter
The project stack is Django + MongoDB (djongo library). I have order table with data structure like this { name:"Help", price:123, products:[ { "_id":"some id", "organization":{ "id":1 } }, { "_id":"some id2", "organization":{ "id":2 } } ] } How can I get list order which has item in 'products' set where organization id field is equal 1? When I will get this list how can I delete products set items where organization id field isn't equal 1? So I should get something like this (Price field shouldn't be too) { name:"Help", products:[ { "_id":"some id", "organization":{ "id":1 } } ] } -
TypeError: Field 'facebook_reactions' expected a number but got <class 'rest_framework.fields.IntegerField'>
I am facing an issue when testing my EventViewSet. I get the following error TypeError: Field 'facebook_reactions' expected a number but got <class 'rest_framework.fields.IntegerField'>. This is the test I ran: class EventViewSetTest(BaseTestCase): def test_event_created(self): event_data = { "url": "www.example.com", "tweet_text": "Event successful", "facebook_reactions": 2, } response = self.client.post("/api/events/", event_data) self.assertEqual(status.HTTP_201_CREATED,response.status_code) Here is my views.py: class EventViewSet(ModelViewSet): queryset = Event.objects.all() def get_serializer_class(self): if self.action == "create": return serializers.EventCreateSerializer return serializers.EventSerializer def perform_create(self, serializer): Event.objects.create( url=Link.objects.get_or_create(url=serializer.url)[0], tweet_text=serializer.tweet_text, facebook_reactions=serializer.facebook_reactions, ) Here is my serializers.py: class EventCreateSerializer(serializers.Serializer): url = serializers.URLField tweet_text = serializers.CharField facebook_reactions = serializers.IntegerField class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ["url", "tweet_text", "facebook_reactions"] Help would be much appreciated. Thank you! -
Error: django.core.exceptions.ImproperlyConfigured: NewsCreateVive is missing a QuerySet
I'm just trying to add the simplest form to my website. I'm making an example from a book I get an error: Internal Server Error: /newsboard/add/ Traceback (most recent call last): File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\edit.py", line 170, in get return super().get(request, *args, **kwargs) File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\edit.py", line 135, in get return self.render_to_response(self.get_context_data()) File "C:\Users\Pavel\Desktop\DjangoWEBIRonBull\IRonBULL\newsboard\views.py", line 14, in get_context_data context = super().get_context_data(**kwargs) File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\edit.py", line 68, in get_context_data kwargs['form'] = self.get_form() File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\edit.py", line 34, in get_form form_class = self.get_form_class() File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\edit.py", line 95, in get_form_class model = self.get_queryset().model File "C:\Users\Pavel\AppData\Roaming\Python\Python310\site-packages\django\views\generic\detail.py", line 69, in get_queryset raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: NewsCreateVive is missing a QuerySet. Define NewsCreateVive.model, NewsCreateVive.queryset, or override NewsCr eateVive.get_queryset(). [27/Dec/2021 19:54:41] "GET /newsboard/add/ HTTP/1.1" 500 98314 At the same time, this is not related to the solutions that I saw when I was looking for an answer to my question. (problem with the file urls.py and using the name of its class inherited from CreateVive) My code: urls.py: from django.urls import path from … -
Add a custom query-function to django admin
I created a custom function. I added to the Django admin panel for a certain model. Now, it can be used and applied to the desired queryset of elements that are stored in this model. I have, let's say, a problem. This model contains a huge quantity of data. I need a queryset only for a certain quantity of those that have a particular field that is not Null (Hence,it contains data). I would like to know if it is possible to create a function for the admin panel that allows for checking all the fields that respect some conditions. In my example, those that have that field that is not Null. I could do the job by simply using either a script or opening the shell. But I would like to try something new. If you have any idea, Thank you! -
'QuerySet' object has no attribute '_committed'
Wondering why I'm having a hard time to make this sharing function view work without keep hitting this error 'QuerySet' object has no attribute '_committed' somehow when i try to save shared object without adding the groupimage model everything seem to work perfectly fine until i add the image form and groupimage model then things starts to fall part, How do i make this to work? what are the possible best solution to saving share object with separate models in my case Post and GroupImage ? I have made a deep search on stack for a solution but somehow all seem not to fit a solution for my case! Would appreciate help and overviews thank you Here is my view that handle shared Post def share_post(request, pk): original_post = Post.objects.prefetch_related('groupimage_set').get(pk=pk) original_img = GroupImage.objects.filter(post=original_post) group = Group.objects.get(groups=original_post.group.id) form = ShareForm(request.POST, request.FILES) if form.is_valid(): new_post = Post( shared_body = request.POST.get('description'), description = original_post.description, username = original_post.username, date_posted = original_post.date_posted, group = original_post.group, video = original_post.video, shared_on = datetime.now(), shared_user = request.user) new_post.save() form = GroupImageForm(request.POST, request.FILES) if form.is_valid(): new_image = GroupImage( post = original_post, group = group, image = original_img, ) new_image.save() return redirect('group:main',original_post.group.pk) else: form = ShareForm(request.POST, request.FILES) ctx = {'form':form, … -
python-django forms and models
i need to create a user registration form using django and also need to save datas (fist_name,last_name,username,password1,password2) in auth_user and age,idproof in UserProfile model ,how can i do that using a single django form in views. -
why site url isnt stable
upstream main_site { server 127.0.0.1:8000; } server { server_name domain.com; access_log off; error_log /var/log/nginx/main_site_error.log; location / { proxy_pass http://main_site; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot client_max_body_size 50M; } server { if ($host = domain.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name domain.com; listen 80; return 404; # managed by Certbot client_max_body_size 50M; } I used this configuration for the Negnix on server, but when I want to enter the site with Url (domain.com), sometimes it brings the default of GoDady site and sometimes it brings the site itself. I also used Docker-Compose to run the application. when i use my own ip:port its correct and somtimes got this message This site can’t be reached domain.com unexpectedly closed the connection. Your client does not have permission to get URL / from this server. What do you think I did wrong? -
how to check if a property exists in a foreign key model?
I have a model named Product class Product(models.Model): order = models.ForeignKey(Order, on_delete = models.CASCADE) quantity = models.ForeignKey(Quantity, on_delete = models.CASCADE) In both ForeignKey-s I have the same property named 'number'. I want to check if that property exists in Product model or in its ForeignKey-s models. What I am trying to do is: hasattr(Product, 'number') -
Build model saved 1kb file
Hello Programmers Hope you are doing well. Thanks in advance Problem: When I build my project, # build models for project with id project_id def build_id(project_id): # get directory path to store models in path = fetch_model_path(project_id, True) # train model model, scaler_in, scaler_out = train_project_models(project_id) # ensure model was trained if model is None: return False # store models store_model(f'{path}/model.pkl', model) store_model(f'{path}/scaler_in.pkl', scaler_in) store_model(f'{path}/scaler_out.pkl', scaler_out) # clear current loaded model from memory keras_clear() return True project build successfully but saved 1 kb file. If there is already file exist having some size the model decrease the file file_size to 1kb fetch the models path for project with id project_id def fetch_model_path(project_id, make_dirs=False): # get directory path for project_id path = JaProjectManagement.objects.all().get( id=project_id).url # do necessary transformations path = path if path.find('://') == -1 else path.split('://')[1] path = str(project_id) + '_' + path.replace('.', '_').replace('/', '') path = os.path.join(MODEL_PATH, path) # make directories if asked if make_dirs: os.makedirs(path, exist_ok=True) return path Store model # dump model to path def store_model(path, model): with open(path, 'wb') as f: model_file = File(f) pickle.dump(path, model_file) -
command from compose not executed in entrypoint.sh
I have a Dockerfile for my python django project and then I have a docker-compose that I use to build and deploy my application. Currently, the compose file just have django app, nginx, and db server. The ENTRYPOINT arg in my app's Dockerfile is the entrypoint.sh script which runs some migrations and at the end I have the exec "$@" line which should be executing the Command passed via the docker-compose. But it seems that the command from the Dockerfile does not get executed or crashes. I can see from the output of docker ps -a --no-trunc that the command is indeed being passed as an arg to the ENTRYPOINT. I did try to move the command from the compose file to the entrypoint.sh, and the application starts just fine. But when it is being passed from the compose file, nothing happens. I also tried to echo "$@" in order to check what was being received, but that's empty as well. Here is my app's service in compose: version: '3' services: django_app: container_name: django_app build: context: . dockerfile: Dockerfile image: django_app:latest command: gunicorn app.wsgi:application --preload --bind 0.0.0.0:8000 --workers=4 -t 300 expose: - 8000 depends_on: - db env_file: - ./.env This … -
Not able to Login once user has been created in Django admin
I am able to create the user with permissions and groups. But I am not able to login with the created user in django admin.Creation of the user and permissions -
Why error handler is triggered when i'm trying send django file response?
I upload video file on my django server and saving it in my FileSystemStorage. After I get some frames of this video using python library(PIL) and saving them in fss too. Next i want to display those images on page, so i'm sending(as response) frames_number, fps, filename. def loop(request): if request.method == 'POST': # save video file in vile storage file = request.FILES['file'] fss = FileSystemStorage() fss.save(file.name, file) # set up class, for work with video vt = VideoTools(file.name) # save frames in media storage frames, fps = vt.get_frames() # return frames_number and fps return JsonResponse({ 'frames': frames, 'fps': fps, 'filename': file.name, }) return render(request, 'main/loop.html') In my frontend I count how many frames I need and make the corresponding number of POST requests, each of which give my one frame, but while receiving frame my error handler is trigged. Why? success: function(response) { let fps = response['fps'] let frames = response['frames'] let filename = response['filename'] let frames_needed = Math.round(frames / fps + 1) for(let i=0; i<=frames_needed; i+fps) { // making request let img = get_each_frame(0, filename) img.done(function(response) { console.log(response, 'get_frame_response') }) // getting this handler triggered img.fail(function(error) { console.log(error, 'get_frame_error') }) } }, function get_each_frame(frame_number, filename) { let request … -
How can I check if a foreign key has an attribute on its model?
I have a model named Product class Product(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) I am at Product views.py, how can I check if an attribute exist in the 'Order' model? What I'm trying to do is this -> hasattr(Product, "order__name") -
how to covert utc time fiekd into json?
I want to convert the following object into json but i'm unabe to do that because i'm getting the following error TypeError: can not serialize 'datetime.datetime' object on "create_time":notification_object.create_time.. i'm send back to server the following object by converting into json.. notification = { "id": notification_object.id, "sender": notification_object.sender, "receiver": notification_object.receiver, "message": notification_object.message, "create_time":notification_object.create_time, } I have tried to convert time into string but that is returning me 2021-12-27 10:11:46.395138+00:00 this time format. But i want 2021-12-27T10:16:20.611423Z time format. -
The 'image' attribute has no file associated with it in django
productscreate.html <form method="post"> {% csrf_token %} <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="value: title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image"></td> <br> </tr> <tr> <td><button type="submit" id="submit" data-bind="submit: mySubmit">Submit</button></td> </tr> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <script> var formData1 = new FormData(); $(document).on('click', '#submit',function(e){ e.preventDefault() var viewModel = { title:ko.observable(),description:ko.observable(), mySubmit : function(formElement) { var formData = { 'title' : viewModel.title() , 'description' : viewModel.description(), }; formData1.append('image', $('#image')[0].files[0]) $.ajax({ type: "POST", url: '{% url "productscreate" %}', data: formData,formData1, cache: false, processData: false, enctype: 'multipart/form-data', contentType: false, success: function (){ window.location = '{% url "productslist" %}'; }, error: function(xhr, errmsg, err) { console.log(xhr.status + ":" + xhr.responseText) } }); } }; ko.applyBindings(viewModel); </script> views.py class ProductsList(ListView): model = products context_object_name = 'products' template_name = "productslist.html" class ProductsCreate(CreateView): model = products fields = ['title','description','image'] template_name = "productscreate.html" success_url=reverse_lazy('productslist') class ProductsDetailView(DetailView): template_name = "productsdetail.html" queryset = products.objects.all() context_object_name = 'products' model = products models.py class products(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=200) image = models.FileField(blank=True,null=True) def __str__(self): return self.title productsdetail.html <form> Title:- {{products.title }} <br><br> Description:- {{ products.description}}<br><br> Image :- <img src="{{products.image.url}}" alt="image"><br><br> <img src="/static/images/book.jpg"> <button><a href="/edit/{{ products.id}}">Edit</a></button> </form> Image is not displaying … -
How to select distinct coloumn values from mysql database in django?
I need to retrieve distinct value from query set and display it on a div. Here is my model.py: class Persons(models.Model): id = models.IntegerField(primary_key=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) address = models.CharField(max_length=100) dob = models.CharField(max_length=100) salary = models.IntegerField doj = models.DateField() class Meta: db_table = "test" Here is my view.py: def calender(request): years={} persons = Persons.objects.all() for person in persons: if person.doj.year not in years: years[person.firstname]=person.doj.year return render(request, "home.html", years) Here is my html : <div> {% for item in Persons %} <div class="numbers">{{ item.doj }}</div> {% endfor %} </div> My code is not working. Any help will be highly appreciated. Thank You! -
Django query as string array from checkboxes form
I would like to get multiple inputs from a checkboxes form something and then filter it out from my database. That would be something similar to: http://127.0.0.1:8000/data/?class_type=[class_C,class_M] However what I am receiving from the query is: http://127.0.0.1:8000/data/?class_type=class_C&class_type=class_M This is how it is coded, in .html: Data class <br> <div class="form-check"> <input class="form-check-input" type="checkbox" value="class_C" id="class_C" name="class_type"> <label class="form-check-label" for="class_C"> C </label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="class_M" id="class_M" name="class_type"> <label class="form-check-label" for="class_M"> M </label> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="class_X" id="class_X" name="class_type"> <label class="form-check-label" for="class_X"> X </label> </div> In views.py: data_class = request.GET.get('class_type') [...] if data_class == "class_C": database = database.filter(class_l__contains = "C") elif data_class == "class_M": database = database.filter(class_l__contains = "M") elif data_class == "class_X": database = database.filter(class_l__contains = "X") Any help is pretty appreciated! Thank you! -
How create a link in templates with relational table in django app
I have question : my classes on models.py `class Actes(models.Model): acte_id = models.AutoField(primary_key=True) title = models.TextField() contenue = models.TextField() vector_column =SearchVectorField(null=True) # new field fullpath = models.CharField(max_length=255) date_atce_add = models.DateField(null=True, blank=True) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) type_acte = models.ManyToManyField(Type_acte, help_text='Select a genre for this acte') pdf = models.ForeignKey('PdfModel', on_delete=models.SET_NULL, null=True)` class PdfModel(models.Model): pdf_field = models.CharField(max_length=255) title_pdf = models.CharField(max_length=255) def __str__(self): return ', '.join(['pdf_field' + str(self.pdf_field), 'title_pdf=' + self.title_pdf]) def filename(self): return os.path.basename(self.file.name) def __str__(self): """String for representing the Model object.""" return f'{self.pdf_field}, {self.title_pdf}' class Meta: ordering = ['title_pdf'] my views on views.py class Dlpdf(View): model = Actes, PdfModel context_object_name ="dlpdf_context" template_name = "search_result.html" def Link_Title (request): if Actes.title : TextField == PdfModel.title_pdf return PdfModel.pdf_field title pdf , and title on actes have a same name in db (for example : title is 'moon' on actes title and 'moon" (title_pdf) in pdfmodel my template search_result.html i try this but i d'ont how to write it. <!-- <li>{{ quote.headline | safe }} - <b>By <i>{{ quote.name }}</i></b></li> --> <span class=""> <li class="list-group-item list-group-item-action list-group-item-secondary"><p class="">{{ actes.contenue | safe |striptags |truncatewords:200 | wordwrap:40 }}</p> {% with Actes PdfModel %} {%for pdf_field in dlpdf_context %} - nom du document <i>{{ actes.title }}</i> </li>ici le …