Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
I want to download files using flask from my folder. How to download
@app.route("/download?/path:filename",methods = ['GET', 'POST']) def download(filename): return send_from_directory(filepath, filename =filename, as_attachment = True) This is the function Click on the File to Download : {{post.py_file}} This is the html tag -
Django KeyError at /
Hello Guys Im trying to make a Login page and I want it to be validated, I'm having hard time fixing it. I don't know what's going on. The problem is whenever I try to login with invalid user or not registered user I want it to throw me and error message. So I did this Now it throwing me a Error of django. KeyError at / 'username' Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: KeyError Exception Value: 'username' Exception Location: /home/aakash/Documents/Projects/Imp Projects/Atom-Social-Media/users/forms.py, line 32, in clean_password Python Executable: /home/aakash/Documents/Projects/Imp Projects/Atom-Social-Media/bin/python3 Python Version: 3.9.5 Python Path: ['/home/aakash/Documents/Projects/Imp Projects/Atom-Social-Media', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/home/aakash/Documents/Projects/Imp ' 'Projects/Atom-Social-Media/lib/python3.9/site-packages'] Server time: Tue, 01 Jun 2021 07:08:02 +0000 Traceback Switch to copy-and-paste view /home/aakash/Documents/Projects/Imp Projects/Atom-Social-Media/lib/python3.9/site-packages/django/core/handlers/exception.py, line 47, in inner response = get_response(request) … ▶ Local vars /home/aakash/Documents/Projects/Imp Projects/Atom-Social-Media/lib/python3.9/site-packages/django/core/handlers/base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /home/aakash/Documents/Projects/Imp Projects/Atom-Social-Media/users/views.py, line 11, in register_view if form.is_valid(): Forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.forms import fields from django.forms.widgets import PasswordInput from django.contrib.auth.hashers import check_password User = get_user_model() unallowed_username = ['fuck', 'fuck123', 'bitch', 'yourdad', 'yourmom','suck'] class LoginForm(forms.Form): username= forms.CharField() password = forms.CharField( widget=PasswordInput( … -
django.db.utils.OperationalError: no such table: poll_position
Here It is showing an error while mapping the position table with the candidate if I use ForeignKey relationship then it is also showing an error can anybody tell what is the problem. models.py from django.db import models from django.contrib.auth.models import User class Position(models.Model): title = models.CharField(max_length=50, unique=True) def __str__(self): return self.title class candidate(models.Model): full_name = models.CharField(max_length=50) total_vote = models.IntegerField(default=0, editable=False) position = models.ForeignKey(Position, on_delete=models.CASCADE) def __str__(self): return "{} - {}".format(self.full_name, self.position.title) class Registration(models.Model): fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) dob=models.DateField() user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) def __str__(self): return self.fname error: OperationalError at /admin/poll/candidate/ no such table: poll_position Request Method: GET Request URL: http://127.0.0.1:8000/admin/poll/candidate/ Django Version: 3.2.3 Exception Type: OperationalError Exception Value: no such table: poll_position Exception Location: C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\Anil\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\Anil\\PycharmProjects\\E_Vote\\ovs', 'C:\\Users\\Anil\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Anil\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Anil\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Anil\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Anil\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Tue, 01 Jun 2021 07:10:50 +0000 -
How to enable all lookups for all fields in django-filters library
in django filters you need somtigs like filterset_fields = {'object_id': ['gte', 'lte', 'exact', 'lt']} to enable filtering but what if I want to enable all lookups filtering on all fields. pagination_class = PageNumberPagination filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] search_fields = '__all__' filterset_fields = {'object_id': ['gte', 'lte', 'exact', 'lt']} I tried filterset_fields = 'all' but I got only the 'exact' functionalities. also I have a problem in which when I do url/?id=2 I got the same data, so why __all__ doesn't work on the id? -
Django Teamplate Tabs Not Showing
I have a Django website which you can think of as a blog. In there, I have a route where you can create a new post. There is also a list page and a detail page, where you can see all the posts published, and see the contents of the post respectively. When creating a new post, I have not added CKEditor or any other WYSIWYG editor. But if I have any tabs in the post, it doesn't render. For example, if I write some code in VSCode and paste it in the TextField, even though the tabs render in the TextField, the tabs don't appear in the detail page. For example, if I write this in the TextField: foo = "bar" if foo == "bar": print("baz") This, in the detail page looks like this: foo = "bar" if foo == "bar": print("baz") This is the part of my detail page that renders the above on the screen: <div class="contents"> {{ object.contents | linebreaks }} </div> Could you help? -
How to add extra key-value to QuerySet lists?
I am working with Django,i need to retrieve data from multiple database, which has different database name but with same table column structure. So I use model.using(database).all()to get queryset and merge them into one. I want to add extra databasename to indicate the data's database name, this is my code. model: class Sections(models.Model): apply_id = models.PositiveIntegerField() pathology_id = models.CharField(max_length=128) user_id = models.PositiveIntegerField() updated_at = models.DateTimeField(blank=True, null=True) get_queryset: def get_queryset(self): slideset = [] database_config = ['database1', 'database2', 'database3'] for i, x in database_config: slides = Sections.objects.using(x).all() #### I want to add extra databasename column in every query object. for x1 in slides: x1.databasename = x ###### slideset.append(slides) # merge QuerySet query = functools.reduce(lambda a, b: a|b, slideset) return query.order_by("updated_at").reverse() the one return will be : { "apply_id": 1123, "pathology_id": 1235, "user_id": 1, "updated_at": "202106011430", # add extra databasename. "databasename": "database1". } Because the column can't be modify, so I had to leave Sections model unchange, just add extra key-value to query, can someone help me on that? -
PermissionError: [Errno 1] Operation not permitted: '/app/staticfiles/admin/css/widgets.css'
Someone can help me? I didnt know why this error happends i give permission to django file app in chown -R appuser /app More detail: i use docker-compose build and docker-compose up my project tree: https://i.ibb.co/WKwWFgw/aaa.png my files: Dockerfile: # For more information, please refer to https://aka.ms/vscode-docker-python FROM python:3.9-alpine3.13 EXPOSE 8000 ENV PATH="/scripts:${PATH}" # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 # Install pip requirements COPY requirements.txt . RUN apk add --no-cache jpeg-dev zlib-dev RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers && apk add postgresql-dev gcc python3-dev musl-dev \ && pip install Pillow && apk add gcc musl-dev python3-dev libffi-dev openssl-dev cargo # more pip RUN pip install psycopg2 #end more pip RUN pip install --upgrade pip RUN python -m pip install -r requirements.txt RUN apk del .tmp COPY /app /app WORKDIR /app COPY ./scripts /scripts RUN chmod +x /scripts/* # Creates a non-root user with an explicit UID and adds permission to access the /app folder # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app USER appuser # During debugging, … -
how to convert Django uploadedfile.InMemory into numpy array or Image
#Views.py-- I want to convert uploaded image file into numpy array(cv2.imread) .Please help me ``` def upload(request): if request.method == 'POST' and request.FILES['image_file']: f = request.FILES['image_file'] myfile = str(f.read()) array_np = cv2.imread(myfile)``` -
Get all items with all properties using django multi-table inheritance and django rest framework (Cart Product)
I'm using PostgresSQL as DB, Django as backend and HTML, CSS, Javascript as Frontend. I have refer this question link but doesn't help me. Let me explain the whole scenario about my website. 1. I am building website like, if person brought a house then, a person need all household product, then my website will help him to get all the details of the single product like for ex. Fans (speed, RPM, Power consumption etc.), Side Table (Height, wood used, colour etc.) and more than tons of product. 2. Then my first page look like this. 3. Then the user go to the specific page (if click refrigerator link button -> List of Refrigerator(price, brand, specification)) 4. Then the user choose the specific item then he/she will redirect to the main page with selected item. (ref. image down below.) Now, my problem is that I can't access the details of the child table (reference table or link table)[Using Multi table Inheritance] As you can see on the above image I can't access (Refrigerator or other models) Details. Now my code goes here: models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=200) joined_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name class …