Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get random number every x second from python to template? Django
Ok so this may sound foolish but I know how we can generate random number in javascript every x seconds, but actually I just want to receive a value from my custom template tag which is frequently updating, but when I do so by calling it repeatedly through my javascript it just gives the same value, so I think template tags just calls the function on start and store the value, however I need to get updated value every time I call my tag. My custom_tags.py - @register.simple_tag def getTest(): verification_code = str(randint(100000, 999999)) return verification_code And in my javascript - window.setInterval(function(){ let temp5 = "{% getTest %}" console.log(temp5) }, 5000); This returns me same number everytime, so is there any fix or workaround for this ? PS I dont want to reload every x seconds so it should be done using custom template tags only. Any help is appreciated -
Django | I'd like to delete a product and all of its related data from the database
I have a shopping cart with some items in it. If I delete a product from the basket, I also want to remove it from the orderitem. I am now unable to delete the orderitems and quantity. class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) subtotal = models.DecimalField(default = 0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default = 0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) class OrderItem(models.Model): Quantity_Choices =( ('one', '1'), ('Two', '2'), ('Three', '3'), ) product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.CharField(max_length=22, choices=Quantity_Choices, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) The code for adding an item to the cart is as follows. def cart_update(request): product_id = request.POST.get('product_id') print(product_id) if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("No product") return render("cart_home") cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) added= False else: cart_obj.products.add(product_obj) added =True request.session['cart_items'] = cart_obj.products.count() if request.is_ajax(): print("ajax request") json_data = { "added":added, "removed": not added, "cartItemCount":cart_obj.products.count() } return JsonResponse(json_data) return redirect("cart_home") orderitem cart -
Django seems to import packages from global installations rather then from my Virtual Environment(venv)
I have created a Virtual Environment using Python's built-in venv. Activated the environment & installed the necessary packages. But cannot import Pandas in the Django project. Later I figured out that Django might be importing packages from the global packages installed before, where pandas was not installed. Do I have to change anything in my Django project settings or in my Virtual Environment? Activated Virtual Environment(venv) Pandas installed in the venv This is when I echo path while venv activated This is when I try to import Pandas -
Django Content-Disposition - Ordering and Sorting
I have created a Django/python web app that saves meter readings entered, into the database. This app also has a button that exports the readings along with the unit number for the model that it's in. It is working up to standard, however, when the file is exported, it is exported in the order that the readings have been entered in. How would I sort the export from smallest to largest, through the Django code? Views.py: import csv def Avonleacsv(request): data =AvonleaClass.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Avonlea_file.csv"' writer = csv.writer(response) writer.writerow(['Unit', 'Number of Units' ]) for avonleaclass in data: writer.writerow([ avonleaclass.unitNumber, avonleaclass.newReading, ]) return response -
Django video analysis on background
I'm trying to build a webpage that analyze real-time video with Django. I succeeded in showing the analyzed results on a specific link(I added a few lines to add image analysis). However, the analysis is started when I open the link and when I close the link, the video analysis will be stopped. Opening multiple links also causes a problem. I need the video analysis to be started when I add a camera object and keep running until the server is closed. Also, analysis from multiple cameras need to be done in parallel. I'm searching for some solutions and bumped into "Celery" and "django-background-apps". Could they be a solution to my problems? Or are there any suggested solutions? Thank you :) from django.views.decorators import gzip from django.http import StreamingHttpResponse import cv2 import threading class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def livefe(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: # This is bad! replace it … -
How to display all chat conversations using Django Channels?
When the conversations page is loaded, it should display a list of all active conversations. When a user send a message in a chat, this should be updated in the conversations list. How is it possible for the user to open a connection to the websocket, fetch the chats and listen for new messages? I use Django channels on the backend and Flutter on the frontend. -
Django - How to properly create a related Object on data Import?
I'm currently writing a Python script that allows me to read all metadata from media files like mp3, mp4 etc. and write it into a Database. The problem is that each "Media" object has x MediaStreams objects and I don't really understand how I can properly run trough all streams (index) and create the relation between my Media and MediaStream class/table. new_object = Media.objects.create(...) should work fine but how to get my streams related to it? See my current state of parsing madness down below: import ntpath import subprocess from shlex import join import json import xmltodict from App.models import Media def meta_single(descriptor): """Takes a single media file as argument from disk or http/https (descriptor="/path/to/file.mp4") and scrapes it for metadata. A utf8 encoded JSON object will be returned""" def get_plist_names(name_dict): return [o["string"] for o in (name_dict if isinstance(name_dict, list) else [name_dict])] def path_leaf(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) scrape_cmd = join(['./ffmpeg_binaries/ffprobe', '-print_format', 'json', '-show_streams', '-show_format', '-loglevel', 'quiet', '-hide_banner', descriptor]) scrapped_assets = subprocess.getoutput(scrape_cmd) clean_result = json.loads(scrapped_assets) #metadata = json.dumps(clean_result, indent=4, ensure_ascii=False, sort_keys=True).encode('utf8').strip().decode() #print(metadata) # General Meta filename_value = None bitrate_value = None duration_value = None size_value = None nb_streams_value = None media_type_value = None title_value = None artist_value … -
How to change title/label menu in django admin
Can i change the title/label menu in django admin? let say i wanna change "POLLS" to "MASTER" and "QUESTIONS" to "ALL QUESTIONS"? -
Django urls.py setup
I'm getting a ModuleNotFoundError: No module named admin from django.urls import include, path from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', include('admin.site.urls')), path('learning_log/', include('learning_logs.urls')), ] -
How to do pagination for chat app messages
I am trying to build a real time chat application. What it needs to do: allow users to send messages to other users inside a 'chat' similar to private chat on apps like whatsapp and messenger. after a user sends a message to a chat the other user needs to receive it instantly by having their chat data updated. What I would like to know is how to handle pagination with this type of problem. If a user scrolls up and tries to get their old chat data (message history) I can do pagination on the database, however, if the other user in the chat sends a message i.e. adds a new message to the database for that chat, this instantly offsets the whole chat history/pagination by one (one for every message sent). This of course would result in duplicate messages. And visa versa, if the other user deletes a message then our chat history pagination will be returning missing results. Of course this only occurs if our user is scrolling for chat history while the other user is posting/deleting message. Currently I am considering doing this by asking for the last of results before or equal to the datetime … -
Create a django form with many to many model and a through parameter where all the choices are required
models.py class OfferingType(models.Model): title = models.CharField(max_length=100, unique=True) description = models.TextField(blank=True) class Registration(models.Model): user = models.ForeignKey(User, on_delete=models.RESTRICT) activity = models.ForeignKey(Activity, on_delete=models.RESTRICT) sessions = models.ManyToManyField(Session, related_name='registrations') offerings = models.ManyToManyField(OfferingType, through='RegistrationOffering', related_name='registration_offering') commentary = models.TextField(blank=True) class Meta: unique_together = ('user', 'activity') class RegistrationOffering(models.Model): offering_type = models.ForeignKey(OfferingType, on_delete=models.RESTRICT) registration = models.ForeignKey(Registration, on_delete=models.RESTRICT) amount = models.DecimalField(max_digits=6, decimal_places=1, default=0.0, validators=[django.core.validators.MinValueValidator(0.0)]) hello, after several hours of research i still haven't been able to find a solution that suits me. I would like to create a form that adapts to the number of types of offerings there are. I would like that when registering a user the form asks him to give an amount of offering for each type of offering. Here is the result I would like to have. But the most similair I could do was an inlineformset but I couldn't modify the multichoice box I hope someone can point me on the right path. Thanks Ge -
How we can return extra parameter with the 'HTTP_REFERER' URL in Django views?
url = request.META.get('HTTP_REFERER') return HttpResponseRedirect(url) This URL is used to redirect to the current page and I want to send a parameter with it. How I can do that? -
Poll is not saving
I am building a PollApp and I am stuck on a Problem. I build a poll add feature for add images in the poll . BUT images are not adding in the Poll. When i select images in field then save it redirect to the same page and saying "This field is required". models.py class ImagePoll(models.Model): owner = models.ForeignKey(User, null=True, on_delete=models.CASCADE) image = models.FileField() description = models.TextField() class ImageChoice(models.Model): image_poll = models.ForeignKey(ImagePoll, on_delete=models.CASCADE) choice_image = models.FileField() views.py def polls_add(request): if request.method == 'POST': form = ImagePollAddForm(request.POST) if form.is_valid(): poll = form.save(commit=False) poll.owner = request.user poll.save() new_choice1 = ImageChoice(poll=poll, image=form.cleaned_data['choice1']).save() new_choice2 = ImageChoice(poll=poll, image=form.cleaned_data['choice2']).save() new_choice3 = ImageChoice(poll=poll, image=form.cleaned_data['choice3']).save() messages.success(request, "Poll & Choices added successfully") return redirect('polls:image_polls') else: form = ImagePollAddForm() context = { 'form': form, } return render(request, 'add_poll.html', context) forms.py class ImagePollAddForm(forms.ModelForm): choice1 = forms.FileField() choice2 = forms.FileField() choice3 = forms.FileField() description = forms.TextInput() class Meta: model = ImagePoll fields = ['description', 'choice1', 'choice2', 'choice3'] add_poll.html <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {% for field in form %} <div class="form-group"> {{ field.errors }} {{ field.label_tag }} {{ field }} <br> </div> {% endfor %} <button type="submit" class="btn btn-primary">Add Poll</button> </form> When i try to upload images in each field then … -
How to create fake `date_created` for testing purposes
Goal create fake date_created for testing purposes . class TestTimeSheets(APITestCase): def test_my_function(self): Model.objects.create(date_created=datetime.timedelta( hours=1), field_target='blood_pressure', field_value='120/80') error TypeError: expected string or bytes-like object # in models date_created = models.DateTimeField(default=datetime.now(), blank=True) # or date_created = models.DateTimeField(auto_now_add=True, null=True) -
How to prevent modal form from being closed on submit button when form.is_valid() == False?
I've got a modal form in my template, the form below is validated (date_of_birthday cannot be less than 18 years ago). Is there any way, to not close the form if not form.is_valid() and display error messages and close the form if form.is_valid()? <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <img onclick="" id="close-icon" src="{% static 'icons/cancel.svg' %}"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in profile_form %} {% if field.name == "date_of_birth" %} <div class="form-group" style="margin: 10px 30px;"> {{field.label}} <div> {{field}} </div> {% for error in field.errors %} <div class="alert alert-danger" role="alert"> {{error}} </div> {% endfor %} </div> {% elif field.name == 'bio' %} <div class="form-group" style="margin: 10px 30px; display: grid;"> {{field.label}} {{field}} {% for error in field.errors %} <div class="alert alert-danger" role="alert"> {{error}} </div> {% endfor %} </div> {% else %} <div class="form-group" style="margin: 10px 30px;"> {{field.label}} {{field}} {% for error in field.errors %} <div class="alert alert-danger" role="alert"> {{error}} </div> {% endfor %} </div> {% endif %} {% endfor %} <button type="button" class="submit-button">Submit</button> </form> </div> </div> </div> View: def post(self, request, user_id): profile_form = UserProfileForm(request.POST, request.FILES) if profile_form.is_valid(): date_of_birth = profile_form.cleaned_data['date_of_birth'] image = profile_form.cleaned_data['image'] background_image = profile_form.cleaned_data['background_image'] bio … -
How to import data from custom template tag to javascript? Django
How to escape js on a custom template tag? In my custom_tags.py I have registered a simple tag which simply takes data from firebase in form of array of dictionary. I want to pass this array directly to my JavaScript but doing so gives me error. my custom_tags.py - @register.simple_tag def getMessageData(): message_data = [] data = database.child('ChatMessages').get() for task in data.each(): message_data.append(task.val()) return dumps(message_data) in my js - messageData = JSON.parse("{% getMessageData %}"); This gives me Uncaught SyntaxError: Unexpected token & in JSON at position 2 at JSON.parse (<anonymous>) at (index):23 error. I tried debugging value by var temp2 = "{% getMessageData %}" so I found its value to be So basically I need some way to use escapejs on my custom template tag.. Its easy to do on values passed through rendering but with {% template_tag_name|escapejs %} gives error as it considers escapejs a part of name. -
Django - Allow custom users edit their profile
I think I've tried all the solutions from Internet to allow custom users to edit their profile but I still can't manage to do it. To illustrate my architecture, I have a profile page on which there is an edit button. This button open a modal form to edit the profile. I think I have to do something with my url (to include pk in it) but I don't understand how : if I use a simple path (without pk) I have this error : Reverse for 'edit_profile_modal' not found. 'edit_profile_modal' is not a valid view function or pattern name and when I try to add pk I have this one : Reverse for 'edit_profile' with no arguments not found. 1 pattern(s) tried: ['accounts/edit_profile/(?P[0-9]+)$'] Here is my code : accounts/url.py urlpatterns = [ ... path('profil/', ProfileView.as_view(), name="profil"), path('edit_profile/',EditProfileView.as_view(),name="edit_profile"),] views.py class EditProfileView(BSModalUpdateView): model = Account template_name = 'accounts:edit_profile' form_class = EditProfileForm success_message = 'Le profil a été modifié avec succès' success_url = reverse_lazy('accounts:profil') profil.html <!--Modal--> <script type="text/javascript"> $(document).ready(function() { $("#edit-profile").modalForm({ formURL: "{% url 'accounts:edit_profile' %}" }); }); </script> <div class="modal fade" tabindex="-1" role="dialog" id="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"> </div> </div> </div> <button id="edit-profile" class="btn btn-primary" type="button" name="button"><a class="nav-link active" href="{% … -
Can't reach AJAX success event
Can't reach AJAX success event with any visible error (error event doesn't trigger either). I'm trying to load data to <div id="list"></div> block. After opening the page there's only 1 message in the console: beforeSend and no information about success or error events. How can I trigger success event and fill this block? views.py: def load_api(request): return render(request, 'bboard/api_rubrics.html') @api_view(['GET']) def get_api_rubrics(request): if request.method == 'GET': rubrics = Rubric.objects.all() serializer = RubricSerializer(rubrics, many=True) return Response(serializer.data) urls.py: urlpatterns = [ path('all_api_rubrics/', load_api), path('all_api_rubrics/api/rubrics/', get_api_rubrics), ] serializers.py: class RubricSerializer(serializers.ModelSerializer): class Meta: model = Rubric fields = ('id', 'name', 'order') models.py: class Rubric(models.Model): name = models.CharField(max_length=20, db_index=True, verbose_name='Name') order = models.IntegerField(default=0, db_index=True) def __str__(self): return self.name class Meta: verbose_name_plural = 'Rubrics' verbose_name = 'Rubric' ordering = ['order', 'name'] api_rubrics.html: {% load static %} <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <title>List of rubrics</title> </head> <body> <div id="list"></div> </body> <script src="{% static 'bboard/rubrics1.js' %}"></script> </html> rubrics1.js: window.onload = function() { $.ajax({ method: 'GET', url: 'api/rubrics', beforeSend: function() { console.log('beforeSend'); }, succsess: function(result) { update_table(result); console.log('after send'); }, error: function() { console.log('error'); } }); } function update_table(data) { console.log('inside update_table'); var list = document.getElementById('list'); var jsonData = JSON.parse(data); var s = '<ul>'; … -
Create a voice call feature for the mobile app
I'm developing a mobile app and I want to create a functionality that it has Voice call feature through internet. How to implement this functionality My tech stack is Frontend - Flutter Backend - Django How can I achieve this? -
how to trigger the delete button when expected
def edit_question(request): req = json.loads(request.body) answers=req["answers"] for answer in answers: try: models.Answer.objects.filter(answer_id=answer["answer_id"]).update( question_id=models.Questions.objects.get(pk=question_no), mark=guided_answer["mark"], ans=guided_answer["ans"], ) except: models.Answer.objects.get_or_create( question_id=models.Questions.objects.get(pk=question_no), mark=guided_answer["mark"], ans=guided_answer["ans"], ) else: (this button is suppose to delete answers) #models.Answer.objects.filter(answer_id=answer["answer_id"]).delete() return success({"res": True}) Problem: I have three types of apis i need to put inside, one is delete, one is update and one is create,the code i have with me creates and updates based off whether there is an existing field or not but now i need to add a delete api inside that basically gets the answer deleted when the button is triggered there are two issues to this the first issue is that the model basically deletes based off what is visible, it should delete the items that are not visible, if the field name of the item has been removed the api should identify it and remove it based off that <MinusCircleOutlined className='dynamic-delete-button' style={{ paddingLeft: '10px', position: 'absolute', top: '0%', right: '-5%', }} onClick={() => remove(field.name)} /> the second issue is that the delete api right now basically interferes with the update and create api on top where if i try to create and update it deletes it I need to know whether i can firstly … -
ModuleNotFoundError: No module named 'froala_editordjango'
I have installed froala_editor for my application and also followed the steps written on official github repo https://github.com/froala/django-froala-editor/, but on running python manage.py runserver (after migration), I am getting this error. what could be the possible cause of the error. Please answer. -
function' object has no attribute 'as_view in Django
Getting the below error while starting Django dev server. It looks like as_view() exist in APIView.But still getting this error. File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "E:\django_maxmilian\monthly_challenges\challenges\urls.py", line 4, in <module> path('test', views.BookView.as_view()) AttributeError: 'function' object has no attribute 'as_view' view.py from . import models from . import serializers from django.views.decorators.csrf import csrf_exempt from rest_framework.response import Response from rest_framework.views import APIView from django.views.generic.edit import CreateView # Create your views here. @csrf_exempt class BookView(APIView): def get(self, request): snippets = models.Book.objects.all() serializer = serializers.BookSerializer(snippets, many=True) return Response(serializer.data) urls.py from django.urls import path from . import views urlpatterns = [ path('test', views.BookView.as_view()) ] -
I have got an assignment, I need help, Django Rest Framework, please keep the answer as simple as possible
Create an app named "orders" in the project "restaurant". Create a model named "MenuItem" to store the item name, price and description. Add few items using the Django Shell or the Admin module. The app "orders" must support the following API end points : -
Django & VSCode: Can't run commands in terminal
I don't know why but I can't run any comands in the vSCode Terminal. For example, when I try python manage.py createsuperuser I get an error that can't find Python. So I do py manage.py createsuperuser and then I get a syntax error saying that manage.py doesn't exist or something like that. Anyone know why this is and how I could fix it? -
How to Generate and use Client ID and Secret in Python
Hello Everyone can anyone help me with a problem I want to generate client id and secret and how will i use it in my code For example like razorpay provided client id and secret and then authenticate it RAZORPAY_KEY_ID = 'rzp_test_bDsdfFGvKkfjksDNw' RAZORPAY_KEY_SECRET = 'C9fV6Z1CghkncHGYHbagBhBo2' So how would i generate a credential like this and use it when some is making an api request with it? Any Help Will be appreciated Thank You