Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Filter on ManyToManyField
I have two models: class Student(models.Model): first_name = models.CharField() last_name = models.CharField() class Group(models.Model): name = models.CharField() students = models.ManyToManyField(Student) Some data (first_name and last_name concatenated): Group #1 | Blak Coleman Group #1 | Miguel Scott Group #2 | Jordan Barnes Group #2 | Jordan Gustman Group #2 | Jekson Barnes Group #3 | Jordan Smith As you can see theres three students by name Jordan. So I need to return groups which in students queryset has only students by name Jordan. I tried this: groups = Group.objects.filter(students__first_name='Jordan') But group.first().students.all() contains all the students not only Jordan. Expected result: Group #2 | Jordan Barnes Group #2 | Jordan Gustman Group #3 | Jordan Smith How could I do this? -
ManyToMany field to same model without allowing the same object
I am using Django with a model that has a ManyToMany field to the same model. class Job(models.Model): name = models.CharField(_('Name'),max_length=80, blank=True, default="") related_jobs = models.ManyToManyField('self') this works fine. I can create Job objects and add jobs to related_jobs. The problem is that I can associate the same object to himself like this: job1 = Job.objects.create(name='Java') job2 = Job.objects.create(name='Python') job1.related_jobs.add(job2) job1.related_jobs.add(job1) #I don't want this to be possible Is there anyway to restrict this on the models? -
django-rest-framework days-of-week representation in model
I want to create a schedule model to schedule media on days of the week class Schedule(models.Model): name = models.CharField(max_length=100) start_date = models.DateTimeField() end_date = models.DateTimeField() week_days = ??? date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) status = models.BooleanField(default=True) def __str__(self): return self.name but the problem is with week_days it can have multiple days how do I design the week_days field in the Django rest framework? -
How to handle namespace API versioning with DRF-YASG
In my project we want to have multiple versions of same api so as to support backward compatibility. Right now we are using drf-yasg's swagger url at /api/doc/ While our apis are /api/vehicle/$ /api/warehouse/ And then each of the app vehicle and ware house have their own endpoints.. Now we want to do versioning as /api/v1/doc /api/v2/doc /api/v1/vehicle /api/v2/vehicle /api/v1/warehouse Goal is that /v1/doc should show v1 of both vehicle and ware house while/v2/doc should show only v2 of vehicle since only vehicle app has some apis with v2.... How to achieve this I tried adding default version v1 initially in drf settings. But that resulted in no listing being shown in swagger view -
Order queryset by the number of foreign key instances in a Django field
I am trying to return the objects relating to a through table which counts the number of reactions on a blog post. I have an Article model, Sentiment model and Reactions model. The sentiment is simply a 1 or 2, 1 representing like and 2 for dislike. On the frontend users can react to an article and their reactions are stored in a Reactions table. Reactions model class Reaction(models.Model): user_id = models.ForeignKey(User, related_name='user_id', on_delete=models.CASCADE) article_id = models.ForeignKey(Article, related_name='article_id', on_delete=models.CASCADE) sentiment = models.ForeignKey(Sentiment, related_name='sentiment', on_delete=models.CASCADE) I'd like to find the 2 most liked articles so I have written a view to handle the GET request views.py class MostPopularView(generics.RetrieveAPIView): queryset = Reaction.objects.annotate(num_likes = Count('sentiment_id')).order_by('num_likes') serializer_class = MostPopularSerializer and a serializer to transform the data serializers.py class MostPopularSerializer(serializers.Serializer): class Meta: fields = ( 'id', 'title', ) model = Article As the code stands now, I'm getting a response <QuerySet [<Reaction: d745e09b-5685-4592-ab43-766f47c73bef San Francisco Bay 1>, <Reaction: d745e09b-5685-4592-ab43-766f47c73bef The Golden Gate Bridge 1>, <Reaction: dd512e6d-5015-4a70-ac42-3afcb1747050 San Francisco Bay 1>, <Reaction: dd512e6d-5015-4a70-ac42-3afcb1747050 The Golden Gate Bridge 2>]> Showing San Francisco Bay has 2 likes and The Golden Gate Bridge has 1 like and 1 dislike. I've tried multiple methods to get the correct response including … -
Safest way to send base64 encoded Image in a post api request
I have a post request where I am sending a base64 encoded image. I wanted to know is there any encryption method that I can use to encrypt this base64 string. In frontend I am using Javascript and for backend Django is being used. So far I have not been able to find any resource or anything that can point me right direction. Any help will be appreciated. -
Django form is not saving when I have action = to desired url
If I use action="" in my django form, the form works properly but sends the user to the wrong page. I want the user to go back to the macro/ page upon form submission, but when I add that url to action (like action="{% url 'macro' %}", it goes to the page but the form doesn't save. Any suggestion on how to handle this? Code below: (Option 1) macro_update.html -> the form here works properly, but takes the user to the wrong page <ul> <form action="" method="post"> {% csrf_token %} {{ macro_form.as_ul }} <input type="submit" value="Submit"> </form> </ul> (Option 2) macro_update.html -> the user is redirected to the right page upon submission, but the form data doesn't update/save <ul> <form action="{% url 'macro' %}" method="post"> {% csrf_token %} {{ macro_form.as_ul }} <input type="submit" value="Submit"> </form> </ul> views.py @login_required(login_url='login') def macroUpdate(request): if request.method == "POST": macro_form = MacroForm(request.POST, instance=request.user.profile) if macro_form.is_valid(): macro_form.save() messages.success(request,('Your macros were successfully updated!')) else: messages.error(request,('Unable to complete request')) return redirect("profile") macro_form = MacroForm(instance=request.user.profile) context = {"user":request.user, "macro_form":macro_form } return render(request, 'macro_update.html', context) urls.py urlpatterns = [ path('', views.loginPage, name='login'), path('register/', views.registerPage, name='register'), path('profile/', views.profilePage, name='profile'), path('profile/update/', views.profileUpdate, name='profile-update'), path('logout/', views.logoutUser, name='logout-user'), path('macro/', views.macroPage, name='macro'), path('macro/update/', views.macroUpdate, name='macro-update'), … -
populating form with data from session; django
I'm wondering how to fill my form with data that i have stored in my session. my model: models.py class Order(models.Model): order_by = ForeignKey(User, on_delete=DO_NOTHING) order_status = ForeignKey(OrderStatus, on_delete=DO_NOTHING) created = DateTimeField(default=datetime.now) address_street = CharField(max_length=256) address_postal_code = CharField(max_length=18) address_city = CharField(max_length=128) shipping = ForeignKey(ShippingMethod, on_delete=DO_NOTHING) payment = DecimalField(max_digits=12, decimal_places=2, null=False) payment_method = ForeignKey(PaymentMethod, on_delete=DO_NOTHING) def __str__(self): return self.id I have a view that stores my choices in 'cart' class AddProductToCartView(View): def get(self, request, pk): cart = request.session.get("cart") if cart: for item in cart: if item["id"] == pk: item["quantity"] += 1 break else: cart.append({"id": pk, "quantity": 1}) request.session["cart"] = cart else: request.session["cart"] = [{"id": pk, "quantity": 1}] return redirect("store:cart_view") class CartView(View): def get(self, request): in_cart = [] overall_price = 0 overall_tax = 0 if "cart" in request.session: overall_price = 0 for item in request.session["cart"]: product = Product.objects.select_related("category").get(id=item["id"]) total_price = product.price * item["quantity"] tax = (total_price * product.tax) in_cart.append({ "product": product, "quantity": item["quantity"], "total_price": total_price, "tax": tax }) overall_price += total_price overall_tax += tax return render( request, template_name="cart/cart_view.html", context={ "products": in_cart if len(in_cart) > 0 else None, "overall_price": overall_price, "overall_tax": overall_tax } ) and I want to populate my form with data (some of it not everything is in my 'cart' so … -
How do I solve this input problem? (DJANGO)
I'm trying to do an autocomplete with django. In the HTML, I'm using a <select> tag to get the IDs and connect to the API for the data, anyway, that's not the focus. The truth is that this part of the select doesn't work inside the modal it should, just outside. Could anyone help me with suggestions? I tried to put it outside the modal and it worked, but I need it to work inside the modal. The code below shows where it should work. <div class="row"> <div class="col"> <strong style="font-weight: 500;" class="d-block mb-1">Pessoas a serem adicionadas</strong> <select class='form-control' id="id_pessoas" name="pessoas" required="required" data-ajax--cache="true" data-ajax--delay="250" data-ajax--type="GET" data-ajax--url='{% url "api-list-pessoa" %}' data-theme="bootstrap4" data-allow-clear="true" data-maximum-selection-length="7" data-minimum-input-length="3" data-language="pt-BR" data-placeholder="Selecione uma pessoa"> </select> </div> -
How to import custom modules in Django
I have a module created with the name metrics.py . I want to use this module in my views.py file.The command i used to import is "import metrics" in views.py file. both views.py and metrics.py are in the same folder. i am getting this error "ModuleNotFoundError: No module named 'metrics'" How to use the custom module i created in views.py -
Django JSONField is not able to encode smileys properly
I plan to store a dict in a Django JSONField. One key of this dict is a comment a user can enter. And users like a lot to add some smileys in their comments... The problem is that some smileys, are saved properly in DB. The database is MySQL 8.0.31, Django version is 4.0.8 : JSONField is supported for this environment as reported in documentation. The database default encoding is utf8mb4 and collation utf8mb4_general_ci. With that model : class TestJSONField(models.Model): data = models.JSONField() Here is the test case : comment=b'smiley : \xf0\x9f\x98\x8a'.decode() t=TestJSONField(pk=1, data={'comment':comment}) t.save() r=TestJSONField.objects.get(pk=1) print('BEFORE :', comment) print('AFTER :', r.data['comment'], '(str)') print('AFTER :', r.data['comment'].encode(), '(utf-8 encoded bytes)') which gives : BEFORE : smiley : 😊 AFTER : smiley : ? (str) AFTER : b'smiley : ?' (utf-8 encoded bytes) As you can see the smiley is not stored correctly. This smiley is 4 bytes encoded, this may be the source of the problem because with 2-bytes encoded chars I do not have any problem. With a TextField and using json dumps()/loads() I do not have any problem. Do you have an idea how to have 4 bytes encoded smileys to be saved in a JSONField ? -
logging with cookiecutter-django inside docker not displaying on console
I can't get logging to display. Am I doing something wrong? Other logging that is generated by cookiecutter-django works fine, but when I try to implement logging myself for debugging I am not able to get any display settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "console": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "verbose", }, "file": { "level": "INFO", "class": "logging.FileHandler", "formatter": "verbose", "filename": "debug.log", }, }, "root": {"level": "INFO", "handlers": ["console", "file"]}, } view.py: class run(viewsets.ModelViewSet): serializer_class = RunSerializer def list(self, request): return Response("Get") def create(self, request): logger = logging.getLogger("root") logger.info(request.data) logger.info(request.POST) return Response({200}) this logging does not display to console -
How do I change the text/value of "Add [Model-Name]" button in Django Admin?
When we login to Django Admin Interface as a superuser, we see the list of models on the left sidebar. When we click on any model name, we go to the list display page of that model which have 'Add [Model-Name]" button on uuper right corner. How do I change the text/value of that button? In my case, I have User Model, and I want to change the "Add User" text on list display page of User Model to "Invite User". How do I accomplish that? I have encircled the button with red in the screenshot attached. Django Admin Interface Screenshot I have tried different solutions told in this stackoverflow question and in this django documentation. But I am unable to achieve. I tried to override change_form.html by changing {% blocktranslate with name=opts.verbose_name %}Add {{ name }}{% endblocktranslate %} to {% blocktranslate with name=opts.verbose_name %}Invite {{ name }}{% endblocktranslate %}. I put the overriden file change_form.html in pricingmeister/accounts/templates/admin/. But i could not see the change. The hierarchy of my Django Project and folders is below: Django Project Hierarchy Screenshot Below is my settings.py (truncated some code to show only relevant part of code . . . INSTALLED_APPS = [ # … -
List View is not working but get context data is
I have a ListView but when I call it only the get_context_data method works (the news and category model, not the product) when I try to display the information of the models in the templates. view: class HomeView(ListView): model = Product context_object_name='products' template_name = 'main/home.html' paginate_by = 25 def get_context_data(self, **kwargs): categories = Category.objects.all() news = News.objects.all() context = { 'categories' : categories, 'news' : news, } context = super().get_context_data(**kwargs) return context There is also this piece of code: context = super().get_context_data(**kwargs) If it's written before: categories = Category.objects.all() The Product model is show but not the others. base.html <body> ... {% include "base/categories.html" %} {% block content %}{% endblock %} </body> home.html {% extends 'main/base.html' %} {% block content %} <div> ... <div> {% for product in products %} {% if product.featured == True %} <div> <div> <a href="">{{ product.author }}</a> <small>{{ product.date_posted|date:"F d, Y" }}</small> </div> <p>Some text..</p> </div> {% endif %} {% endfor %} </div> </div> {% endblock content %} categories.html <div> ... <div> {% for category in categories %} <p>{{ category.name }}</p> {% endfor %} </div> <div> {% for new in news %} <p>{{ new.title }}</p> {% endfor %} </div> </div> -
How to delete 200,000 records with DJango?
Situation: I have Model have a relation 1-1, sample: class User(models.Model): user_namme = models.CharField(max_length=40) type = models.CharField(max_length=255) created_at = models.DatetimeField() ... class Book(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) And I have a around 200,000 records. Languague: Python Framework: Django Database: Postgres Question: How can I delete 200,000 records above with minimal cost? Solution I have tried: user_ids = Users.objects.filter(type='sample', created_date__gte='2022-11-15 08:00', created_date__lt="2022-11-15 08:30").values_list('id',flat=True)[:200000] # Fetch 200,000 user ids. for i, _ in enumerate(user_ids[:: 1000]): with transaction.atomic(): batch_start = i * self.batch_size batch_end = batch_start + self.batch_size _, deleted = Users.objects.filter(id__in=user_ids[batch_start,batch_end] With this solution, my server use arround: 600MB CPU 300MB RAM Take more 15 minutes to finish workload. I wonder do anyone have a better solution? -
How to ignore errors in twilio send sms
I am trying to send sms using python and twilio. I am actually sending 1000-2000 sms. so while sending I get errors like : 30032 - Toll-Free Number Has Not Been Verified 21610 - Attempt to send to unsubscribed recipient so here what I am trying. I have a form inside my dashboard. When I will press send button it will start sending message to every one. when someone blocks my number from there side the whole process get closed and I had to send messages or remove them from my list again and again. Here is views.py class AdminIndex(View): template_name = "AdminPage/index.html" def get(self, request): contents = ContentTemplate.objects.all() numbers = NumberGroup.objects.all() groups = Group.objects.all() args = { "contents": contents, "numbers": numbers, "groups": groups } return render(request, self.template_name, args) def post(self, request): content = request.POST.get("content") number = request.POST.get("number") groups = request.POST.get("group") if request.method == "POST": message = SendMessageModel( content=ContentTemplate.objects.get(id=content), number=NumberGroup.objects.get(id=number), group=Group.objects.get(id=groups) ) message.save() for n in message.group.customers.all(): account_sid = "AC2b0cc7c783ccc1e82f3771636dda5e73" auth_token = "bdb32f3656485e868270f68a1b3024ee" client = Client( account_sid, auth_token ) send_message = client.messages.create( body=message.content.content, from_=f"+{message.number.number}", to=n.phone_number, ) n.is_sent = True print(str(n.phone_number)) n.save() return HttpResponse("All Sent") So, How can I ignore these errors and keep sending messages to the users without interruption? -
Invalid command 'PassengerAppRoot', perhaps misspelled or defined by a module not included in the server configuration -django
I hosted a django website few week ago, it was working well and suddenly i got this error on my website. I am getting this error on my webpage And in webserver error log i am getting: Invalid command 'PassengerAppRoot', perhaps misspelled or defined by a module not included in the server configuration .htaccess file: DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/plantsof/plantsofnepal" PassengerBaseURI "/" PassengerPython "/home/plantsof/virtualenv/plantsofnepal/3.8/bin/python" PassengerAppLogFile "/home/plantsof/plantsofnepal/logs/passenger.log" DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END I tried to remove this configuration and pass in .htaccess. I couldn't figure out why this error happened suddenly. -
How to search inside an uploaded document?
I'm trying to find a way to search inside the uploaded files. If a user uploads a pdf, CSV, word, etc... to the system, the user should be able to search inside the uploaded file with the keywords. Is there a way for that or a library? or maybe should I save the file as a text inside a model and search from that? I will appreciate all kind of reccommendation. -
Django Ninja API framework Pydantic schema for User model ommits fields
Project running Django with Ninja API framework. To serialize native Django's User model I use following Pydantic schema: class UserBase(Schema): """Base user schema for GET method.""" id: int username = str first_name = str last_name = str email = str But, this approach gives me response: { "id": 1 } Where are the rest of fields? Thought this approach gives me a full data response: class UserModel(ModelSchema): class Config: model = User model_fields = ["id", "username", "first_name", "last_name", "email"] Response from ModelSchema: { "id": 1, "username": "aaaa", "first_name": "first", "last_name": "last", "email": "a@aa.aa" } -
Can not import pyarrow, DLL load failed while importing lib
I have been trying to get polars working but pyarrow keeps giving me error with or without polars package, pyarrow==10.0.0 is installed and django version is Django==3.0.5, I can import it in python shell but when I import it within my django app, it throws me this error whenever and wherever it is imported: File "xxx.py", line 1870, in xxx print(pl.read_sql(query, ALCHEMY_SQL)) File "C:\Users\duoqu\miniconda3\envs\test-env\lib\site-packages\polars\io.py", line 1107, in read_sql tbl = cx.read_sql( File "C:\Users\duoqu\miniconda3\envs\test-env\lib\site-packages\connectorx\__init__.py", line 253, in read_sql import pyarrow File "C:\Users\duoqu\miniconda3\envs\test-env\lib\site-packages\pyarrow\__init__.py", line 65, in <module> import pyarrow.lib as _lib ImportError: DLL load failed while importing lib: The specified procedure could not be found. Or like this: File "xxx.py", line 59, in <module> import pyarrow File "C:\Users\duoqu\miniconda3\envs\test-env\lib\site-packages\pyarrow\__init__.py", line 65, in <module> import pyarrow.lib as _lib ImportError: DLL load failed while importing lib: The specified procedure could not be found. Importing the module from shell within anaconda environment but just plain python shell: Python 3.8.15 (default, Nov 4 2022, 15:16:59) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import pyarrow >>> pyarrow.lib <module 'pyarrow.lib' from 'C:\\Users\\duoqu\\miniconda3\\envs\\test-env\\lib\\site-packages\\pyarrow\\lib.cp38-win_amd64.pyd'> >>> Also it is recognized by pylance: What could be the problem? I am … -
Error resolution django.core.exceptions.ImproperlyConfigured:
Ran into this error when trying makemigrations: django.core.exceptions.ImproperlyConfigured: DEFAULT_AUTO_FIELD refers to the module 'django.db.dashboard_models.BigAutoField' that could not be imported. the code in all train apps is identical, only the name changes: from django.apps import AppConfig class ToolsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'tools' Maybe someone can tell me how to fix it, I will be grateful -
execute a code after return/response has been sent in django
I have gone through the answer at Execute code in Django after response has been sent to the client but I am having difficulty in sending html request. The web page is not loading. It is just only showing the string of the url i am requesting e.g. url/template.html This is what I have done and it keeps on sending a json response instead of an html class ResponseAfter(Response): def __init__(self, data, then_callback, **kwargs): super().__init__(data, **kwargs) self.then_callback = then_callback def close(self): super().close() self.then_callback() def followingFunction(): #this is the function that would be executed afterward page_result= return ResponseAfter((request,'index.html'), followingFunction, content_type ="text/html") Please how can I get the function to send the report update I have seen my mistake. I added render to the return statement and it worked fine. -
Issue with django crontabs there not working
hello guys i trying to use django_crontab on my django project and there not working does anyone know something about this im using Linux centos 8. I want to schedule a task to add some data to my database. Can someone help me The steps that i have take is: pip install django-crontab add to the installed apps build my cron function ` from django.core.management.base import BaseCommand from backups.models import Backups from devices.models import Devices from datetime import datetime from jnpr.junos import Device from jnpr.junos.exception import ConnectError from lxml import etree from django.http import HttpResponse from django.core.files import File class Command(BaseCommand): def handle(self, *args, **kwargs): devices = Devices.objects.all() for x in devices: devid = Devices.objects.get(pk=x.id) ip = x.ip_address username = x.username password = x.password print(devid, ip, username, password) dev1 = Device(host= ip ,user= username, passwd= password) try: dev1.open() stype = "sucsess" dataset = dev1.rpc.get_config(options={'format':'set'}) datatext = dev1.rpc.get_config(options={'format':'text'}) result = (etree.tostring(dataset, encoding='unicode')) file_name = f'{ip}_{datetime.now().date()}.txt' print(file_name) with open("media/"f'{file_name}','w') as f: f.write(etree.tostring(dataset, encoding='unicode')) f.write(etree.tostring(datatext, encoding='unicode')) backup = Backups(device_id=devid, host=ip, savetype=stype, time=datetime.now(), backuptext=file_name) print(backup) backup.save() except ConnectError as err: print ("Cannot connect to device: {0}".format(err)) print("----- Faild ----------") stype = ("Cannot connect to device: {0}".format(err)) backup = Backups(device_id=devid, host=ip, savetype=stype, time=datetime.now()) backup.save() ` … -
Django REST Framework - How to get current user in serializer
I have TransactionSerializer: class TransactionSerializer(serializers.ModelSerializer): user = UserHider(read_only=True) category_choices = tuple(UserCategories.objects.filter(user=**???**).values_list('category_name', flat=True)) category = serializers.ChoiceField(choices=category_choices) def create(self, validated_data): user = self.context['request'].user payment_amount = self.validated_data['payment_amount'] category = self.validated_data['category'] organization = self.validated_data['organization'] description = self.validated_data['description'] return Transaction.objects.create(user=user, payment_amount=payment_amount, category=category, organization=organization, description=description) class Meta: model = Transaction fields = ('user', 'payment_amount', 'date', 'time', 'category', 'organization', 'description') This totally does the job, however I need that instead of "???" the current user was substituted, or rather his ID, but I don't quite understand what basic ModelSerializer method I can use so as not to damage anything, but at the same time get the current user as a variable in order to substitute it later in the filtering place (in this case, categories are filtered if I put some specific user ID which is already registered, then on the DRF form, when creating an object, I get a drop-down list with categories specific only to my user)? I have already tried to do this through the get_user() method, and also tried to create a variable inherited from another serializer, which defines just the user ID, but I received various kinds of errors. -
Is it possible in Django?? If yes how?
I want another model to check if boolean == True then take the value and add to mine. Assuming I have 2 models class Balance (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Amount = models.FloatField(max_length=30) class Deposit (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Deposit_Amount = models.FloatField(max_length=30) Approved = models.BooleanField(default=False) Have tried it in my views but it seems views.py only trigger when an action is push from the user. def Deposits(request): if request.method == 'POST': Input_Amount = request.POST['Input_Amount'] user = request.user available = Balance.objects.get(user=request.user) Deposit_Request = Deposit.objects.create(Deposit_Amount=Input_Amount, user=user) Deposit_Request.save messages.warning(request, 'Request sent, please wait for confirmation') if Deposit_Request.Approved == True: sum = available.Amount + float(Input_Amount) New_balance = Balance.objects.update(Amount=sum, user=user) else: return redirect('deposit') else: return render(request, 'deposit.html') It always return and else statement because the default is False when that action was taken. Am a newbies on django