Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix Constant Errors When Implementing Google OAuth Sign-in with Django
I decided to put a google sign in method into my Django website, but I have been encountering errors related to the social_auth_app_django library. For example, at first I got a ValueError (Expected 2 got 1) from one of the utils.py in the library code. Note that I am new to adding google sign in to a Django application. Here are my version specifications: Django version 4.2.13 Python version 3.10.5 social_auth_app_django library version 5.4.1 Here is my settings.py (note that the API keys will be hidden for security purposes) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "games.apps.GamesConfig", "account.apps.AccountConfig", "forums.apps.ForumsConfig", "play.apps.PlayConfig", "make_game.apps.MakeGameConfig", "administration.apps.AdministrationConfig", "bootstrap5", "payments.apps.PaymentsConfig", "social_django" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'account.middleware.DeviceDetectionMiddleware', # "django.middleware.debug.DebugMiddleware", 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'superstarstudios.urls' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "my-google-key" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "my-google-secret" SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ "email", ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2' ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates" ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'account.context_processors.device_type', "social_django.context_processors.backends", 'social_django.context_processors.login_redirect' ], }, }, ] LOGIN_REDIRECT_URL = "/games" LOGOUT_REDIRECT_URL = "/" SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'account.pipeline.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) Here is the function where the main ValueError is … -
Django: subclass, separate class or entirely separate classes
I'm building a forum app in Django as a learning project. I'm unsure of how to approach the creation of Post objects. I want users to be able to post threads (i.e. new topic), I want users to be able to post replies to those threads as well as replying to other replies. I want to include features like reactions to posts, and replies. I'd appreciate some feedback on the different approaches I'm considering: My thinking is that, since the two types of posts are so similar, they should inherit common fields/methods from a parent class. I'm unsure how Django would represent that in the DB tbh. Intially this was an abstract class class Post(models.Model): post_body = models.TextField(max_length=2000) publish_date = models.DateTimeField("date posted") author = models.ForeignKey(User, on_delete=models.CASCADE) class ThreadPost(Post): post_title = models.Charfield(200) is_solved = models.BooleanField("is_issue_solved", default=False) class ReplyPost(Post): is_solution = models.BooleanField("is_this_the_solution", default=False) thread_post = models.ForeignKey(ThreadPost, on_delete=models.CASCADE) Later I started using this, based on a stackoverflow response. However, I'm finding it a bit clunky to work with, as I often have to filter by whether a post is a thread or a reply, and have to find the thread which a post replies to. In that case, just having seperate classes seems … -
Protecting publicly accessable endpoints in Django and React
I have an endpoint urls.py from django.urls import path from . import views app_name = 'Main' urlpatterns = [ path("helloKitty/", views.helloKitty, name='helloKitty'), ] views.py def helloKitty(request): hello = pd.read_csv('static/data/helloKitty_data.csv') hello = hello.to_json(orient='records') return HttpResponse(hello) It's currently accessible by anyone at /helloKitty and it needs to be prevented. I use React on the front-end to access this endpoint and retrieve the data import React from "react"; import { create } from 'zustand'; import axios from 'axios'; const kittyStore = create((set) => ({ kitten: [], fetchKitty: async () => { const response = await axios.get('/helloKitty'); const hello = response.data.map((h) => { return { name: h.name, age: h.age, } }); set({ kitten }) }, })); export default kittyStore; The endpoints /helloKitty needs to be protected from being publicly accessible, and just the React app can view and fetch the data. -
Django REST 404 sending params in the url
Good day, I'm having problems with django/ django rest apí Back: url(r'^' + baseurl + etl + eph + 'salud_folder_xls/listar/<str:accion>/', etlEPHSaludXLSListar), url(r'^' + baseurl + etl + eph + 'salud_folder_xls/descargar/(?P<nombre_archivo>.+\\.xls)', etlEPHDescargarSaludFolderXLS), Front: const response = await axios({ url: '/etl/v1/eph/salud_folder_xls/listar/', method: 'GET', }); When I try salud_folder_xls/listar/ works fine but when I add accion, axios returns always ERROR 404 Any idea? -
Voucher Appears on Both Debit and Credit Sides in Sundry Creditors Ledger in Logistic Accounting Software
I am currently working on existing logistic company's accounting software.the sundry creditors ledger data function returning a single voucher entry twice: once on the debit side and once on the credit side. This behavior seems incorrect as the voucher should only be listed once.its only happening journal Vouchar entry for eg: - as you can see the 100 rs transaction effects on both dr and cr side its journal Vouchar entry rest of the vouchar types working perfectly def get_sundry_creditors_coa_response(coa, start_date, end_date, user): invoices = Invoices.objects.filter(date__range=[ start_date, end_date], invoice_type='Purchase', company__users__email=user.email).order_by('date') respone = [] res_obj = {} for invoice in invoices: cost_entrys = CostEntry.objects.filter( invoice__id=invoice.id, is_included=True) for cost_entry in cost_entrys: res_obj = { "account": invoice.client_name.name if invoice.client_name else "", "date": invoice.date, "currency": invoice.currency_sar, "invoice_number": invoice.invoice_number, "vat_percent": 0, "fcy_amount": 0, "vat_amount": 0, "amount": 0, "dr_amount": 0, "cr_amount": 0, "net_amount": 0, "type": "Invoice", "voucher": "", "party_account": invoice.party_account.name if invoice.party_account else "", "job_no": invoice.job.job_number if invoice.job.job_number else "", "narrations": invoice.narration if invoice.narration else "", "branch": invoice.branch if invoice.branch else "", "language_name": coa.language_name if coa.language_name else "" } fcy_amount = float( cost_entry.fcy_amount if cost_entry.fcy_amount else 0.0) amount = float(cost_entry.amount if cost_entry.amount else 0.0) vat_percent = float( cost_entry.tax_group_code if cost_entry.tax_group_code else 0.0) vat_amount = float((vat_percent * … -
How to override queryset for newly added fieldset in Django Admin Panel
I have added "permissions" fieldset in my User model on Admin Panel, but when I try to add a User it takes a lot of queries due to permissions (500) in my case, I am not able to optimize the code because get_queryset is not executing while adding an object. I want to know how can I fetch all related permissions in add user form, so it should fetch all select related permissions to optimize the admin panel interface. -
Get values from request
I am trying to write values from a request.POST to a string format. By default, these always start with "epochs-NUMBER-". Therefore, I should draw a For loop so that a new line is created for each number. The complete request looks like that. But I only need the 'epochs-NUMBER-' values csrfmiddlewaretoken=hJmSuP3O6GmtwBeJhfqb99LaCVOKxgngGNIEqoqhQQR7tQELUVGHeXRXxfnRE1Ah&base-TOTAL_FORMS=1&base-INITIAL_FORMS=0&base-MIN_NUM_FORMS=0&base-MAX_NUM_FORMS=1000&base-0-time=25.06.2024+13%3A36%3A00&base-0-show_differences=on&base-0-show_null=1&source=Manual&epochs-TOTAL_FORMS=3&epochs-INITIAL_FORMS=3&epochs-MIN_NUM_FORMS=0&epochs-MAX_NUM_FORMS=1000&unit_selector=m&unit_selector=m&unit_selector=m&unit_selector=m&epochs-0-target_name=250.01.G&epochs-0-easting=55555&epochs-0-northing=5555&epochs-0-height=555&epochs-0-azimuth=&epochs-0-zenithangle=&epochs-0-slope_dist=&epochs-1-target_name=170.01.G&epochs-1-easting=44646&epochs-1-northing=6554&epochs-1-height=544&epochs-1-azimuth=&epochs-1-zenithangle=&epochs-1-slope_dist=&epochs-2-target_name=150.01.G&epochs-2-easting=78979878&epochs-2-northing=4645&epochs-2-height=455&epochs-2-azimuth=&epochs-2-zenithangle=&epochs-2-slope_dist= The request looks like that: def nmea_string(self, request, target_name): my_dict = {} keys = [] values = [] target_raw_string = ("PTER," + self.short_name + "_TRG," + target_name + "," + self.time.strftime("%Y-%m-%d %H:%M:%S") + "," + str(self.status_target)) for key, value in request.POST.items(): keys.append(key) values.append(value) for i in range(len(keys)): my_dict.update({keys[i]: values[i]}) for k, v in my_dict.items(): if k.startswith('epochs-0-'): if v == '': v = '-9999.999900' if k.startswith('epochs-0-target_name'): target_raw_string += "," + v else: target_raw_string += "," + v + ",0.000000" tg_checksum = self.get_checksum(target_raw_string) tg_nmea_string = "$" + target_raw_string + "*" + tg_checksum + "\n" nmea_string += tg_nmea_string return nmea_string The end result should look a bit like this: $PTER,TS_TRG,TP-008,2024-04-22 23:00:00,129,675666.252000,0.000000,252132.398000,0.000000,412.137000,0.000000,-9999.999900,0.000000,-9999.999900,0.000000,-9999.999900,0.000000*1F $PTER,TS_TRG,TP-009,2024-04-22 23:00:00,129,675704.440000,0.000000,252162.055000,0.000000,412.341000,0.000000,-9999.999900,0.000000,-9999.999900,0.000000,-9999.999900,0.000000*1A -
Error Decoding JSON Access Token for Daraja API When Hosting Web Service on Render
i am trying to deploy my api on render as a webservice... i have the same code in my local machine as in my git repo from which i building the service to deploy . on the deployed site hosted on render, when i send a post request to daraja api (an mpesa mobile payment natively fom kenya) i get an internal server error with this as the message JSONDecodeError at / Expecting value: line 1 column 1 (char 0) Request Method: POST Request URL: http://rycha-pay.onrender.com/ Django Version: 5.0.6 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Exception Location: /opt/render/project/src/.venv/lib/python3.11/site-packages/requests/models.py, line 978, in json Raised during: mpesa_client.views.pay Python Executable: /opt/render/project/src/.venv/bin/python Python Version: 3.11.9 Python Path: ['/opt/render/project/src/django_mpesa_payments', '/usr/local/lib/python311.zip', '/usr/local/lib/python3.11', '/usr/local/lib/python3.11/lib-dynload', '/opt/render/project/src/.venv/lib/python3.11/site-packages'] Server time: Tue, 25 Jun 2024 10:18:40 +0000 ... on the other hand hand the api works perfectly fine offline and i can send requests to daraja api from my local machine and get valid response as shown in this response body ...*{"MerchantRequestID": "f1e2-4b95-a71d-b30d3cdbb7a7541949", "CheckoutRequestID": "ws_CO_25062024132114897799004096", "ResponseCode": "0", "ResponseDescription": "Success. Request accepted for processing", "CustomerMessage": "Success. Request accepted for processing"}.... *this is the section of code that is being flagged `# Configure logging logger = … -
Is there any way to download files or folders from the public share URL of OneDrive belonging to other users (external resources)?
I have a requirement to download files from the public URL of any OneDrive file or folder belonging to another user using the Django framework. I have written the code, but it gives me an error when accessing the file_id. I am trying to access the file info from below code, but it is now working I have also give the and use msal library for the same #permission "Sites.Read.All", "Sites.ReadWrite.All", "Files.ReadWrite.All", "Files.Read.All" #code where the problem occurs file_info = get_drive_item_id(access_token, encoded_share_url) #code class DownloadView(APIView): def post(self, request): def encode_share_url(share_url): encoded_url = base64.urlsafe_b64encode(share_url.encode()).decode().rstrip("=") return f'u!{encoded_url}' def get_drive_item_id(access_token, share_url): url = f"https://graph.microsoft.com/v1.0/shares/{share_url}/driveItem" headers = { 'Authorization': f'Bearer {access_token}' } response = requests.get(url, headers=headers) response.raise_for_status() return response.json() def resolve_shortened_url(short_url): response = requests.head(short_url, allow_redirects=True) return response.url AUTHORITY = "https://login.microsoftonline.co`your text`m/tenant-id/" CLIENT_ID = "client_id" CLIENT_SECRET = "client_secret" SCOPES = ["https://graph.microsoft.com/.default"] link = request.data.get("link") # Initialize MSAL client application app = ConfidentialClientApplication(CLIENT_ID, authority=AUTHORITY, client_credential=CLIENT_SECRET ) result = app.acquire_token_for_client(scopes=SCOPES) if "access_token" in result: access_token = result['access_token'] headers = {"Authorization": f"Bearer {result['access_token']}"} encoded_share_url = encode_share_url(link) file_info = get_drive_item_id(access_token, encoded_share_url) # Resolve the shortened URL resolved_url = resolve_shortened_url(link) # Parse the file ID from the resolved URL parsed_url = urlparse(resolved_url) query_params = parse_qs(parsed_url.query) # Use the file ID … -
Why /static/ not showing up for /admin in Django project?
So I ahve been trying a bunch of things. settings look good to me but maybe I am missing something, need help. I use: PostegreySQL, Reddis, Celery beat, nginx, gunicorn. the problem: maybe its permission issue, maybe directories, I cannot figure it out. enter image description here [error] 280897#280897: *40433 open() "/app/crm_market/collected_static/grappelli/js/grappelli.min.js" failed (2: No such file or directory), client: 31.128.32.152, server: my_domen.com, request: "GET /static/grappelli/js/grappelli.min.js HTTP/1.1", host: "my_domen.com", referrer: "https://my_domen.com/admin/login/?next=/admin/" (venv) root@fuvscqxzga://root/CRM-WB# docker compose exec web ls -l /app/crm_market/collected_static/ total 12 drwxr-xr-x 6 www-data www-data 4096 Jun 25 09:15 admin drwxr-xr-x 4 www-data www-data 4096 Jun 25 09:15 debug_toolbar drwxr-xr-x 9 www-data www-data 4096 Jun 25 09:15 grappelli project structure: enter image description here settings.py: STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "collected_static") /etc/nginx/sites-enabled/default server { server_name my_domen.com; location /static/ { alias /app/crm_market/collected_static/; } location /admin/ { proxy_pass http://127.0.0.1:8000; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; listen 443 ssl; Dockerfile FROM python:3.9-slim WORKDIR /app/crm_market COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 CMD ["gunicorn", "--bind", "0.0.0.0:8000", "CRM-WB.wsgi:application"] docker-compose.yml services: db: image: postgres:latest … -
Django printing out a JSON file [closed]
I want to print out the json data in HTML file row by row, by just the specific data. But it print all of the data. Print just specific information, not whole document like it happens now. `def show(request): response = requests.get( 'https://api.twelvedata.com/stocks?country=pl').json() return render(request, 'index.html', {'response': response})` ` {% for k,v in response.items %} {{k.section}} :{{v}} {% endfor %}` -
django-import-export: Customizable storage not working with minio
Following the documentation, I'm trying to configure the library to store temporary import files from the admin page into a MinIO bucket. This is my STORAGES configuration: IMPORT_EXPORT_TMP_STORAGE_CLASS = "import_export.tmp_storages.MediaStorage" STORAGES = { "default": { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, "import_export": { "BACKEND": "storages.backends.s3.S3Storage", "OPTIONS": { "bucket_name": os.getenv("PORTAL_S3_BUCKET_NAME"), "region_name": os.getenv("PORTAL_S3_REGION_NAME"), "access_key": os.getenv("PORTAL_S3_ACCESS_KEY"), "secret_key": os.getenv("PORTAL_S3_SECRET_KEY"), }, }, } I suppose that when I import a file from the admin page and reach the confirmation step, I should be able to see the file I'm trying to upload in the bucket, but that's not happening. Nothing is being uploaded. When not setting anything relative to storage and using the default host server storage, I can see the files in the host machine once I'm in the confirmation step, so I assume I should be able to see the file in the bucket as well once it's configured. I've also tried to debug the library, but I am not able to see any information regarding the connection to the bucket. The problem has nothing to do with the MinIO configuration. I've tried retrieving and uploading files to the bucket using Postman with the keys I use in the STORAGES dict … -
How to Override CSS and JS in Folium Map Implementation
All I want is to override the CSS of my Folium map. When I override the styles in my template, they do not reflect on my Folium map. However, when I edit the CSS in the browser's developer tools, it works. I edited the CDN of my Folium map (leaflet.css). Note that I did not manually add the leaflet CDN to my header; Folium automatically includes it. Views.py - Creating a Customized Folium Map from django.views import View import folium def create_map(): f = folium.Figure(width='100%', height='100%') m = folium.Map( location=[14.0000, 122.0000], tiles='https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}{r}.png', attr='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>', zoom_start=6, zoom_control=False, scrollWheelZoom=True, doubleClickZoom=False, ) f.add_child(m) return m Rendering the Map in Django Template class RegionalMalnutritionView(View): template_name = "gis_app/malnutrition_view/regional_pages.html" def get(self, request, *args, **kwargs): context = {} # Assuming 'coodinate_locations' is your GeoJSON data source serializer = RegionalLevelGeoJSONSerializer(coodinate_locations, many=True) geo_data = { 'type': 'FeatureCollection', 'features': serializer.data } folium_map = create_map() for feature in geo_data['features']: html_popup = generate_html_popup_malnutrition(feature) folium.GeoJson( geo_data, highlight_function=highlight_function, style_function=style_function, popup=folium.Popup(html=html_popup, max_width=500), tooltip=folium.features.GeoJsonTooltip( fields=['name'], aliases=['Region Name: '], labels=True, localize=True, sticky=False, style=""" background-color: #F0EFEF; border-radius: 3px; box-shadow: 3px; padding: 20px; """ ), name='Regional Levels', ).add_to(folium_map) context['folium_map'] = folium_map._repr_html_() return render(request, self.template_name, context) templates <div class="map-container">{{ folium_map|safe }} </div> "I want to … -
django_get_or_create doesn't let me create instances
I'm using ModelFactory through SubFactory and there was django_get_or_create Meta field with ('code') inside. I put my 2 new added to model fields to this field django_get_or_create and it literally stopped making countries with 'RU' code and didint fill my array? There's an issue with this field or im doing something really wrong? I did try to search for similar problem but didn't find anything [ class ModelFactory(DjangoModelFactory): code = "RU" predefined_amounts_one_time = [500, 1000, 3000] predefined_amounts_recurring = [500, 1000, 3000] class Meta: model = Model django_get_or_create = ("predefined_amounts_one_time", "predefined_amounts_recurring", "code")] 1 this is what i get multiple times in tests when i try to print those fields: Turkey [] Turkey is an aliase to TR -
How to Quickly Calculate Days Since Latest Uncovered Sales
I have a large set of data for a company's sales and payments received. How can I quickly find the latest sale that cannot be covered by the total payments for each customer? Eg. Suppose the data table looks like this Date Customer ID Type Amount 2024-01-01 1 SALE 100 2024-01-08 1 PAYMENT 50 2024-01-15 1 SALE 100 2024-01-22 1 PAYMENT 100 2024-01-02 2 SALE 200 2024-01-09 2 SALE 200 2024-01-16 2 PAYMENT 150 For Customer 1, it would be 2024-01-15, since total payment amount is 150, so the first sale gets covered; And for customer 2, it would be 2024-01-02, since the only payment cannot cover its first sale. So far I use a window function to compute the cumulative sales and total payments. Then use this generated table to compute the latest uncovered sale, and other statistics. with cumsum_entry as ( select id, date, customer_id, type, amount, sum(amount) filter (where type='PAYMENT') over win_customer - sum(amount) filter (where type='SALE') over win_cumsum as cover from entry window win_customer as (partition by customer_id), win_cumsum as (partition by customer_id order by date rows between unbounded proceeding and current row) ) select customer_id, sum(amount) filter (where date >= '2024-01-01') as monthly_total, min(date) filter … -
Django django.contrib.auth.urls auth - redirect after login
Using python 3.11.9 and Django 5.0.6. I don't have a login/authentication function in views.py that I can write code of desired redirect in. I am using django.contrib.auth.urls for authentication. How do make Django redirect user after successful authentication? I want the user to be redirected to /test after authentication. urls.py urlpatterns = [ path('accounts/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), url('test', views. Test, name='test'), url('', views.home, name='home'), ] views.py @csrf_protect def home(request): return render(request, 'landing.html') @csrf_protect def test(request): if request.user.is_authenticated: return render(request, 'test.html') else: return redirect('/') -
ValueError: The view cart.views.cart_add didn't return an HttpResponse object
I am sure this may have been addressed. I am having this issue for the past week and cannot get past it. I have tried all possible solutions in every site I could find. I would appreciate some help. Thank you here is my error on the console and code ValueError: The view cart.views.cart_add didn't return an HttpResponse object. It returned None instead. from django.shortcuts import render, get_object_or_404 from .cart import Cart from store.models import Product from django.http import HttpResponse, JsonResponse from django import template from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse def cart_summary(request): cart = Cart(request) return render(request, 'summary.html', {'cart': cart}) def cart_add(request): # Get the Cart cart = Cart(request) # test to POST if request.POST.get('action') == 'post': # get Stuff product_id = int(request.POST.get('product_id')) # lookup product in DB product = get_object_or_404(Product, id=product_id) # save to Session cart.add(product=product) # Return a reponse cart_quantity = cart.__len__() # Return Repesponse # response = JsonResponse({'Product Name ': product.name}) response = HttpResponse({'qty ': cart_quantity}) return response def cart_delete(request): return def cart_update(request): pass I have tried everything under the sun -
function' object has no attribute 'objects'
Exception Type:AttributeErrorException Value:'function' object has no attribute 'objects'Exception Location:C:\Users\abdullohdev\Desktop\Projects\koram\main\views.py, line 110, in contact_us <div class="col-xxl-8 col-xl-9 col-lg-10"> <form method="POST" action="{% url 'contact-us' %}" class="contact-form text-center"> <div class="row"> <div class="col-md-6"> <div class="form-grp"> <input name="name" type="text" required placeholder="Ism va Familiyangiz"> </div> </div> <div class="col-md-6"> <div class="form-grp"> <input name="email" type="email" required placeholder="Elektron pochta manzilingiz"> </div> </div> <div class="form-grp"> {% csrf_token %} <textarea name="message" id="message" required placeholder="Xabar"></textarea> </div> </div> <button type="submit" class="btn">Yuborish</button> </form> </div> My contact page def contact_us(request): if request.method == "POST": email = request.POST.get('email') name = request.POST.get('name') message = request.POST.get('message') e = contact.objects.create(ism=name, email=email, msg=message) e.save() text = 'Xabar\n Email: '+email+'\nIsm: '+name+'\nXabar : '+message url = 'https://api.telegram.org/bot7349223445:AAEm_BVOUyH8pmHryWF_yJzcDko3NyRxe9M/sendMessage?chat_id=500919341' requests.get(url+'&text='+text) return redirect('index') -
How use FOR statement with continue/escape/break in this code Django?
I am developing a template in Django. In this template, I receive a list of bibliographies and a list of already associated bibliographies. I need to write a specific button inside the TD for when the bibliography is already associated. However, since Django does not provide any structure like break or continue in the FOR command, I am completely lost on how to do this. As it stands, it will eventually plot more than one button on the screen. Can someone help me solve this? I have already tried making custom filters, but I couldn't solve the problem. {% for bibliografia in page_obj %} <tr> <td>{{ bibliografia.titulo }}</td> <td>{{ bibliografia.autores }}</td> <td>{{ bibliografia.editora }}</td> <td>{{ bibliografia.ano }}</td> <td> {% if bibliografia.tipo_nome == 'Eletrônico' %} ∞ {% else %} {{ bibliografia.exemplares }} {% endif %} </td> <td>{{ bibliografia.tipo_nome }}</td> <td> {% if bibliografias_ja_associadas|length > 0%} {% for bib_associada in bibliografias_ja_associadas %} {% if bibliografia.id == bib_associada.id %} <button class="btn btn-secondary btnAssociacaoBibliografia" data-id="{{ bib_associada.ementa_bibliografia_id }}" data-bibliografia-id="{{ bibliografia.id }}" data-action="remover">Já associado como {{ bib_associada.categoria_nome }}</button> {% else %} <button class="btn btn-primary btnAssociacaoBibliografia" data-id="{{ bibliografia.id }}" data-bibliografia-id="{{ bibliografia.id }}" data-action="associar">Associar</button> {% endif %} {% endfor %} {% else %} <button class="btn btn-primary btnAssociacaoBibliografia" data-id="{{ … -
How to add a ForeignKey field to be saved in ModelForm Django?
While creating my website, I face the following problem: a user can add an article, and so the article model has a ForeignKey field - author. I created a form for adding it, inheriting from ModelForm, since I think it is more logical that way (as it interacts directly with db). The problem is that I cannot add this field to the Form, as it cannot be filled; it has to be taken from the request itself. author = request.user.pk So how can I make a form save the author id as well? Without it, there's an error: NOT NULL CONSTRAINT FAILED, which is logical as the form doesn't save pk and so it is null; but a FOREIGN KEY cannot be null. The only way is to inherit it from class Form? I don't really want to do it... I was thinking about 'overriding' method save() so that it has one more argument - author id: form.save(author=request.user.pk) This way it would work. But I changed my mind, because if something goes wrong, this will mess up the whole database... The save() method is too global. What's more, there might well be another way to solve my problem, which is … -
Trying to redirect using api
enter image description herehere I am trying to use a api to redirect to another url if a particular condition passes.In the first case if profile is already complete then it will redirect to home page if not then it must redirect me to profile completion page.Is there any changes in code I used do to achieve this I tried this code and applied the logic but in postman I'm unable to test this. How to solve this issue -
Find SQLite3 database location in Django project unit tests
I am trying to add more tests for this django project. I am struggling to load SQLite database and debug. A easy way to debug would be accessing the SQLite3 database during testing. How do I find SQLite3 database location in Django project unit tests and see if my endpoints are being tested as I expect? For example, the contest.py has from django.test import Client client = Client() Is there a way of reverse engineer this class and find the sqlite3 storage file? -
Remove model created with choices and the choices too
Sometime ago I created a model with some choices: class MyEnum(StrEnum): CREATE = "create" DELETE = "delete" class ShareHistory(models.Model): action = models.TextField(choices=MyEnum.get_choices()) created_at = models.DateTimeField(auto_now_add=True, auto_created=True) After some time I understood that I don't need that model. So I can just remove the class, run makemigrations, then run migrate and that is all, the table is gone. But I want to remove the choices too (MyEnum). If I do that the next time someone runs the migrations from scratch will receive an error, because the initial migration needs MyEnum. Is there a way to remove that? -
django payment, user balance [closed]
for example, I have a simple website where there is a list of posts, they are of two types: paid and free, paid ones can be purchased by authorized users and then they can read it, free ones can be read by anyone, after registration, all authorized users will have their own balance, there will be a payment system, and each authorized user can deposit at least 5$, after payment, so that the amount he deposited will be credited to his account, how can I implement this and what technologies do I need to use and what should I pay attention to? -
Initializing a Bokeh AjaxDataSource: source callback not receiving parameters on initialization
I have a Bokeh vbar plot in a figure which gets its data from an AjaxDataSource via a JavaScript callback. It works OK after resizing, but initializing the plot fails with a MultiValueDictKeyError, apparently because my callback function is being called without any of the necessary GET parameters being passed to it. (The error is in the line Amin = float(request.GET["Amin"] of the function ajax_data). How do I configure the plot so that it is initialized correctly on first loading? Here is my (anonymised) code: def plot(request): partnerID = int(request.GET['partnerID']) Amin, Amax, Bmax = 0, 50, 0.01 bokeh_html = get_bokeh_html(Amin, Amax, Bmax) c = {"bokeh_html": bokeh_html} c["bokeh_js"] = (f'<script src="https://cdn.bokeh.org/bokeh/' f'release/bokeh-{settings.BOKEH_VERSION}.min.js"' f' type="text/javascript"></script>') return render(request, 'myapp/plot.html', c) def get_bokeh_html(Amin, Amax, Bmax): fig = bp.figure( frame_width=1000, frame_height=800, title="PLOT", tools="box_zoom,wheel_zoom,reset", x_axis_label="Abcissa", y_axis_label="Data axis", ) fig.toolbar.logo = None fig.x_range = Range1d(Amin, Amax) fig.y_range = Range1d(0, Bmax) source = AjaxDataSource( method="GET", data_url=reverse("myapp:ajax_data"), name="ajax_plot_data_source", polling_interval=None, ) r = fig.vbar( x="x", top="top", width=f"width", source=source, ) callback = CustomJS( args=dict(xr=fig.x_range), code=""" $.ajax({ url: 'ajax-data', data: { 'Amin': xr.start, 'Amax': xr.end, 'partnerID': 2 }, success: function (data) { var ds = Bokeh.documents[0].get_model_by_name('ajax_plot_data_source'); ds.data = data; } }); """, ) fig.x_range.js_on_change("start", callback) fig.legend.click_policy = "hide" bokeh_script, bokeh_div = components(fig) …