Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying Django Application on Digital Ocean
I am migrating to digital Ocean for app hosting. I have setup the static file handling to be done by white-noise on my settings.py file, I have run the collectstatic command on my local machine and it works. When the app is being build on digital ocean it encounter's an error. The error stack is as below. -----> $ python manage.py collectstatic --noinput [skakey] [2022-02-23 06:00:36] Traceback (most recent call last): [skakey] [2022-02-23 06:00:36] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 243, in fetch_command [skakey] [2022-02-23 06:00:36] app_name = commands[subcommand] [skakey] [2022-02-23 06:00:36] KeyError: 'collectstatic' [skakey] [2022-02-23 06:00:36] During handling of the above exception, another exception occurred: [skakey] [2022-02-23 06:00:36] Traceback (most recent call last): [skakey] [2022-02-23 06:00:36] File "/workspace/manage.py", line 25, in <module> [skakey] [2022-02-23 06:00:36] main() [skakey] [2022-02-23 06:00:36] File "/workspace/manage.py", line 21, in main [skakey] [2022-02-23 06:00:36] execute_from_command_line(sys.argv) [skakey] [2022-02-23 06:00:36] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line [skakey] [2022-02-23 06:00:36] utility.execute() [skakey] [2022-02-23 06:00:36] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute [skakey] [2022-02-23 06:00:36] self.fetch_command(subcommand).run_from_argv(self.argv) [skakey] [2022-02-23 06:00:36] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 250, in fetch_command [skakey] [2022-02-23 06:00:36] settings.INSTALLED_APPS [skakey] [2022-02-23 06:00:36] File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 84, in __getattr__ [skakey] [2022-02-23 06:00:36] self._setup(name) [skakey] [2022-02-23 06:00:36] File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 71, in _setup [skakey] [2022-02-23 … -
How to get the plane password of Django admin user in pre_save signal when creating user from admin panel?
I need to log Django admin users in 3ed party authentication service. For that I need plane password without hashing. Here I used pre_save signal. That approach works well when I create an API endpoint for registration. But when I create an admin user from Django it always comes with defalut hashed password. Any idea how to get the plane password? -
How to rollback non linear migrations in django?
Suppose I have following migrations in Django. X / \ A B [A and B can represent any number of linear migrations.] \ / Y (merge migration). How can I rollback only B and Y? And keep A as it is. -
Different HTTP request method in a django view class
I had written a view class that has 4 request methods(PUT, POST, DELETE, GET). I want to limit the access via 405 error(Method Not Allowed).2 of my methods do not need any id(The POST and GET) but the others need id. how can I write URLs with different names, for different methods? my view: class CourseAPI(GenericAPIView): permission_classes = [IsAuthenticated] serializer_class = CourseSerializer def get(self, request, *args, **kwargs): def put(self, request, *args, **kwargs): def post(self, request, *args, **kwargs): def delete(self, request, *args, **kwargs): here is my URLs: path( "responsible-person/list/", CourseAPI.as_view(), name="course-list", ), path( "course/<int:pk>/delete/", CourseAPI.as_view(), name="delete-course", ), path( "course/<int:pk>/edit/", CourseAPI.as_view(), name="update-course", ), path( "course/add/", CourseAPI.as_view(), name="add-course", ), is there any way to write like this? path( "course/add/", CourseAPI.post.as_view(), name="add-course", ) -
Django/React/Axios Trying to create an image gallery
I have a web app for an alumni group that manages events, scholarships, etc. I have the models and web pages to display all event details, but I'm struggling to allow a user to upload multiple images for a particular event. Each event has an id and other fields, and the gallery has the image and a foreign key to the event id, so images with event_id 3 all are assigned to the event with id 3, etc. At the moment, I've got all of the other fields to display with my api urls being consumed by axios (pics below). I can successfully upload all images to an event in the django backend. I would like to display those images at the bottom right under Event pictures. I'll deal with modals to enlarge them later. My events details page. import React, { useState, useEffect } from "react"; import { useParams, useNavigate } from "react-router"; import { Link } from "react-router-dom"; import { getEventById, deleteEventById, getGallery, getGalleryById, getGalleryByEventId } from "../../api/apiCalls"; import { Card, CardGroup, Col, Modal, Button } from "react-bootstrap"; import "./Event.css"; const EventDetail = () => { const [event, setEvent] = useState([]); const { id } = useParams(); const … -
Get the current chat history after page refresh
I have created a chatbot that can be added in any website and bot will added on all pages of website. Bot is working fine problem is after page refresh or going another page of website, current chat history is lost. How can I show show current chat after page refresh. I am using django channels for live chat and saving messages in database. When chat start I create a history instance in Histoy model, and then save every message in Conversation model This is model to save the chat. This is chat to customer care type app so messages are saved in question/answer form. class ChatHistory(models.Model): TYPE = ( ('bot_chat', 'bot_chat'), ('user_chat', 'user_chat') ) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='company_chat') customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING, related_name='customer_chat') date_time = models.DateTimeField(auto_now_add=True) chat_type = models.CharField(max_length=10, choices=TYPE) talker = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='user_chat', null=True) saved_status = models.BooleanField(default=False) trained_status = models.BooleanField(default=True) class Meta: ordering = ['-pk'] class Conversation(models.Model): history = models.ForeignKey(ChatHistory, on_delete=models.CASCADE, related_name='chat_history') question = models.TextField(null=True) answer = models.TextField(null=True) time = models.TimeField(auto_now_add=True) -
Nginx configuration with gunicorn
Api is in Django framework and the Web app is in Angular both are different projects. Nginx and gunicorn worked well and upload both projects in the same directory but when I hit my domain it shows Django application default page. I want to show my static html page instead of Django default page. 'server{ listen 443; server_name class.domain.com; root /var/www/html/; index index.html; location /static/ { try_files $uri $uri/ /index.html; } location ~ ^/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } }' -
how to display models.full_clean() ValidationError in django admin?
https://docs.djangoproject.com/en/4.0/ref/models/instances/#validating-objects from django.core.exceptions import ValidationError try: article.full_clean() except ValidationError as e: # Do something based on the errors contained in e.message_dict. # Display them to a user, or handle them programmatically. pass There tell us can Display them to a user, how to display errors in Admin? When I do nothing: When Settings.py Debug = True, it always render a ValidationError at /admin/xxx/xxx/xxx/change/ page. When Settings.py Debug = False, it always render a HTTP 500 page. -
KeyError at /webhook/ 'HTTP_STRIPE_SIGNATURE'
Following is my code for webhook with a Django application @csrf_exempt def webhook(request): webhook_secret = STRIPE_WEBHOOK_SECRET payload = request.body.decode('utf-8') signature = request.META["HTTP_STRIPE_SIGNATURE"] try: event = stripe.Webhook.construct_event( payload=payload, sig_header=signature, secret=webhook_secret) data = event['data'] except Exception as e: return e event_type = event['type'] data_object = data['object'] if event_type == 'invoice.paid': webhook_object = data["object"] stripe_customer_id = webhook_object["customer"] stripe_sub = stripe.Subscription.retrieve(webhook_object["subscription"]) stripe_price_id = stripe_sub["plan"]["id"] current_period_end = stripe_sub["current_period_end"] current_period_end = datetime.datetime.fromtimestamp(current_period_end, tz=None) pricing = Pricing.objects.get(stripe_price_id=stripe_price_id) user = User.objects.get(stripe_customer_id=stripe_customer_id) subscription = Subscription.objects.get(user=user) subscription.status = stripe_sub["status"] subscription.stripe_subscription_id = webhook_object["subscription"] subscription.pricing = pricing subscription.current_period_end = current_period_end subscription.save() if event_type == 'customer.subscription.deleted': webhook_object = data["object"] stripe_customer_id = webhook_object["customer"] stripe_sub = stripe.Subscription.retrieve(webhook_object["id"]) user = User.objects.get(stripe_customer_id=stripe_customer_id) subscription = Subscription.objects.get(user=user) subscription.status = stripe_sub["status"] subscription.save() return HttpResponse() and the url is path('webhook/', webhook, name='webhook') if I check the path https://example.com/webhook/, I am getting the error Exception Type: KeyError at /webhook/ Exception Value: 'HTTP_STRIPE_SIGNATURE' and in strpe account I am getting 500 error -
How to set Python path for django project?
I want to set up an existing project from git. The default python of ubuntu 20.04 is python3.8 and on the project I need to use python3.9. I installed anaconda which has python3.9, the project has a virtual env. when I want to install project dependencies I got this error: > pipenv install Warning: Your Pipfile requires python_version 3.9, but you are using None (/home/mahdi/.local/share/v/W/bin/python). $ pipenv check will surely fail. Pipfile.lock not found, creating… Locking [dev-packages] dependencies… alenvs/Project-UUOFIsQX/bin/python: not found running which python3 resulting this: > which python3 /home/mahdi/anaconda3/bin/python3 -
Calling Django Function from JS Ajax not working
I am trying to call a python function that calculates and converts some number input from a user form. I have an onclick button event to call the following JS function $.ajax({ type: "POST", url:"/calc_ha_range/", dataType: 'json', data: {'ra_deg' : ra_deg, 'dec_deg': dec_deg, 'glon_deg': glon_deg, 'glat_deg': glat_deg}, success: function(data) { jsonData = JSON.parse(data); ha_start.setAttribute('min', jsonData.min); ha_start.setAttribute('max', jsonData.max); ha_end.setAttribute('min', jsonData.min); ha_end.setAttribute('max', jsonData.max); // data.min = minimum val for HA range } }) I then have a django url mapping in the form of path('calc_ha_range/', utils.sensitivity_db.calc_hour_angle_range) which refers to the following python function def calc_hour_angle_range( request ): geo_lat = EarthLocation.from_geodetic(lon="XXXX",lat="XXXX",height=XXXX).lat.value if request.method == "POST": ra_deg, dec_deg, glon_deg, glat_deg = request.POST["ra_deg"], request.POST["dec_deg"], request.POST["glon_deg"], request.POST["glat_deg"] tan_geo_lat = math.tan( geo_lat*(math.pi/180.00) ) tan_dec = math.tan( dec_deg*(math.pi/180.00) ) cos_ha = -tan_dec * tan_geo_lat ha_rad = math.acos( cos_ha ) ha_deg = ha_rad*(180.00/math.pi) ha_h = ha_deg/15.00 output = {'min': -math.fabs(ha_h), 'max': +math.fabs(ha_h)} My issue is when the ajax call takes place in the onClick function I get an error in the console saying 404: mysite.com/calc_ha_range/ not found I have taken over this project from another amateur developer so my understanding of ajax and django is quite fragmented -
Unable to change the time to IST in django
Here is the code from the settings.py from where i change the time LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True this shows me correct time in the :8000/admin but not in the views.py here show you how user.otp_bring_time = datetime.now() this code how i set the time to the user this is how it appears in the photo But when i use it in views it shows me like this user_otp_issued_time =user.otp_bring_time How can i change it to inr -
Django free usage before subscription design question?
I have a Django app using a custom user allauth for a basic user sign up. Inside my application I have the ability to generate a report. However, after the user generates a single report I want to force a subscription using stripe payment processing. For doing something like this will I need a single user type or multiple user types and what is the best way to implement a forced subscription on a basic user model already created or will I have to rip the bandaid off and redesign the user model with a counter for the report usage? -
Temporarily Storing A List of Custom Class Objects in Django
I’m using an api (Spotify) to receive search results(Playlists and their data) and displaying them on my website. I could just directly print out the results to the website in an HTML table, however I need to perform Regex to get values. I created a PlaylistObject class to create where I stored only the attributes from the search that I want to use, as well as my regexs to find an email and username. I do not store this value in the database because it’s temporary and doesn’t need to be saved for long term. The problem I am having is with Pagination. The way I have the program set up, it has to recall the Spotify API function call that’s gets the search and assigns it to my list of PlaylistObjects every single time the page reloads. Because of pagination, it reloads every time the page is changed. The pagination is working and the program functions, however I want to find a way to temporary story my list of Spotify Objects, that way I dont have to recreate it every time I change the page. I don’t want to use a database because it would get filled fast with … -
Hyperlink in Django mail
I am trying to send e-mail in Django ( I am using send_mail) which contain hyperlink to my site(home page) in body? How can I do this? @register.filter def mail(gpd_user_mail): return send_mail( 'GPD System Notification: Please accept GPD', # smth like this: 'http://localhost:54332/home/', 'xm04wz1@bosch.com', [gpd_user_mail,], fail_silently=False, ) -
How to Use Viewsets and Serializers in pytest==7.0.1 Parametrize in Testing djangorestframework==3.13.1 get_serializer() and get_permission()?
I am using a Django Project Template from here. I am testing my serializers and permission in every viewset my app has. I want to use parametrize from pytest to reduce the lines I need to write tests to each serializers and viewset. I have 10 serializers and viewset that I need to test which has a pattern as shown bellow. test_drf_viewsets.py @pytest.mark.parametrize( ("app_url", "app_viewset", "serializer"), [ ( "api:mv-signup-list", viewset.UserSignUpMaterializedViewSet, serializers.UserSignUpMaterializedViewSerializer, ), ( "api:mv-total-list", viewset.TotalMaterializedViewSet, serializers.TotalMaterializedViewSerializer, ), ], ) def test_get_serializer( self, admin_user: User, app_url: str, app_viewset, serializer, rf: RequestFactory, ): viewsets = app_viewset request = rf.get(reverse(app_url)) request.user = admin_user viewsets.request = Request(request) viewsets.format_kwarg = None assert isinstance(viewsets.get_serializer(), serializer) However, when I run the code above, it shows this error TypeError: GenericAPIView.get_serializer() missing 1 required positional argument: 'self' The code presented above is omitted for brevity. -
How to use a ManyToMany field in django with a through model, displaying it and saving it?
I am doing a basic system in Django for a Spa that requires me to have an inventory, massages that use different quantities of product in the inventory, and then a service which will be a combination of multiple massages. So the user of the spa, which is the staff, will be able to create a service, select which massages make that service, and that will instantly trigger the subtraction of that product from the inventory. I used a many to many relation to relate the massages and the items, with a through model to save the amount used as well. My question is, what would be the best way to display this in a form so the staff can add new massages in a way where they can choose many items and their respective quantity that the massage will use? And how can i save all of this afterwards into the DB? I'm using PostgreSQL. This is how my models look right now: class Producto(models.Model): nombre = models.CharField(max_length=200, blank=False) línea = models.CharField(max_length=200, blank=False) proveedor = models.CharField(max_length=200, blank=False) costo_mxn = models.DecimalField(blank=False, max_digits=10, decimal_places=2) unidad_de_medición_choices = [ ("g", "g"), ("mL", "mL"), ("oz", "oz"), ] unidad_de_medición = models.CharField(max_length=20, choices=unidad_de_medición_choices,null=True, blank=True) cantidad_actual = … -
Count objects under some condition using Django templates
I would like to count items under a certain condition. For example (invented view): ... context['example'] = test return render(request, 'index.html', context) .... example has the following values: col1 col2 12 34 99 42 99 42 I know how to count all the values within example, I could so something like this: {{ example.count }} and that would return 3 My question is: how can I count all the items under a certain condition? For example, is there any built-in option to do something like count where example.col2==42 and the result should be 2 -
How to send variables from one views to another?
in my html template I have a variable {{ student.mail}} from context in view Nr.1. In this template I also have button <a class="btn btn-warning" href="{% url 'send_and_home' mail=student.mail %}" role="button">Save and Send</a>. How to send this student.mail to the view Nr.2. The first view returns home page without any . My second page also returns the same home page, but also inside have an additional function to send mail. I don't understand how to implement something like this? Could you help me? my urls: path('home/', views.home, name="home"), my 1st view: @login_required(login_url='login') def home(request): # smth context = ... return render(request, 'app/home.html', context) my 2nd view: @login_required(login_url='login') def send_and_home(request, mail): # article, text, to for mail() depends on mail var from my template mail() context = the same as a view Nr.1 return render(request, 'app/home.html', context) def mail(request, article, text, to): return send_mail( article, 'text', '........', [to,], fail_silently=False, ) -
Join django unrelated models
I have 3 models and I'd like to join them and query in just one query. However, 2 of them do not have foreign keys to each other so I can't use the select_related() option. Could I please request your help? Thanks Here is the model schema: class UserGroup(models.Model): group_name = models.CharField(max_length=80) user_id = models.CharField(max_length=20) class StrategyUserGroupRel(models.Model): strategy = models.ForeignKey(Strategy, on_delete=models.PROTECT) user_group = models.ForeignKey(UserGroup, on_delete=models.PROTECT, to_field='group_name') class SignalStrategyRel(models.Model): signal = models.ForeignKey(Signal, on_delete=PROTECT) strategy = models.ForeignKey(Strategy, on_delete=PROTECT) My entry point would be "user_id" First, I want to get all "group_name" linked to that "user_id". Then, I want the "strategy" which the "group_name" is linked to (can be multiple strategies) Finally, I want the "signal" which the "strategy" is linked to (can be multiple signals) In SQL, it would be like this: select * from strategy_user_group_rel sugr inner join user_group ug on sugr.user_group = ug.group_name inner join signal_strategy_rel ssr on ssr.strategy_id = sugr.strategy_id where ug.user_id = "test_user" -
i want to directly input in django admin dropdown box
This situation is like as above pic. i want to direct input in dropdown i mean, I want to make it possible to input directly, including choosing a dropdown. enter image description here # models.py class AccountBook(TimeStampedModel): branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=False) accountclassification = models.ForeignKey(AccountClassification, on_delete=models.CASCADE, null=True) accountcategory = ChainedForeignKey( "AccountCategory", chained_field="accountclassification", chained_model_field="accountclassification", show_all=False, auto_choose=True, null=True ) ... # admin.py @admin.register(AccountBook) class AccountBookAdmin(admin.ModelAdmin): list_display = ( "accountclassification", "accountcategory", "account_amount", "account_reference", "account_manager", "account_recoder" ) date_hierarchy = 'created_time' class Media: js = ( 'smart-selects/admin/js/chainedfk.js', 'smart-selects/admin/js/chainedm2m.js', ) -
dj-rest-auth - Disable sign up with social account but allow login
what I want to do is have users register using a standard registration page and then have them link their facebook account once in the application which will then allow them to sign in using the "Sign in with facebook" button. So if the users doesn't have an account the Sign in button shouldn't work. however at the moment if a user clicks the FB sign in button A blank account gets created. is there a way to only allow social sign in and not registration ? I've tried setting SOCIALACCOUNT_AUTO_SIGNUP = False but it doesn't seem to work -
Memory issues when sending many files in a row using Requests
In my local folder, I have around 100 css, js and svg files that I'm trying to send via REST api to a Django application. File sizes range from 50KB to 2MB. I'm using requests the following way to send the files one by one, in a loop. requests.post(url, files={"file": open('app.js', 'rb')} Some files get sent and others don't. Every time I re-try, some files that got sent the first time fail, and some that failed the first time succeed. Which file fails and which succeeds is totally random. Logs show a very strange behavior. It seems that the contents of the file that I'm sending, end up in request line and header, not request body where they should be. [2022-02-22 16:32:04 -0600] [8] [DEBUG] Invalid request from ip=172.31.0.1: Invalid HTTP request line: 'ghtSidebarTheme();' [2022-02-22 16:13:31 -0600] [8] [DEBUG] Invalid request from ip=172.31.0.1: Invalid HTTP request line: 'ivateDarkSidebarTheme();' [2022-02-22 10:46:25 -0600] [8] [DEBUG] Invalid request from ip=172.31.0.1: Invalid HTTP method: 'isabled,' Pay attention to the first log statement: Invalid HTTP request line: 'ghtSidebarTheme();' ghtSidebarTheme(); is simply truncated from rightSidebarTheme(); which is a function in one of the js files. My intuition is that there are some memory issues but I'm … -
How can you assign multiple string values to an attribute in Django models
class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, related_name="Customer", limit_choices_to={'is_staff': False}) employee = models.ForeignKey( Employee, null=True, blank=True, on_delete=models.SET_NULL) # locations = What should go here? business_name = models.CharField(max_length=200, null=True, blank=True) phone_no = models.CharField(max_length=200, null=True, blank=True) address = models.CharField(max_length=500, null=True, blank=True) website_url = models.URLField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) As you can see here, I have a locations field which. This field is to store at most 5 locations the business is located in. How can I best achieve this? I have read about using a Many2Many field but this would not be desirable as the locations would have to be first created in the Admin and then added to the business. -
Using django-auditlog, how can I display the 'actor_id' for a particular model?
I have created a simple Django application to display individual articles. These articles have a number of fields that users can edit. I am using the package 'django-auditlog' to log changes to these article models. So far, I have simply followed the auditlog installation doc to setup model history tracking (as well as enabling the middleware to allow 'actor_id' to be tracked). I have also added the example code that displays the most recent changes on the individual model pages as such: <!-- History display --> <div class="table-responsive"> <table id="history" class="table table-striped table-bordered"> <thead> <tr> <th>Actor</th> <th>Field</th> <th>From</th> <th>To</th> </tr> </thead> <tbody> <!-- Human readable - change to '.changes_dict.' for proper logs --> {% for key, value in article.history.latest.changes_display_dict.items %} <tr> <td>{{ article.history.latest.author_id }}</td> <td>{{ key }}</td> <td>{{ value.0|default:"None"|striptags|safe }}</td> <td>{{ value.1|default:"None"|striptags|safe }}</td> </tr> {% empty %} <p>No history for this item has been logged yet.</p> {% endfor %} </tbody> </table> </div> As my code may suggest, I am trying to add an additional column to the history table to show who made the changes that are being displayed. Is there an easy way to do this through auditlog, or will I have to create some kind of sql query …