Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'index' not found. 'index' is not a valid view function or pattern name in django urls
urls.py in app1. from django.contrib import admin from django.urls import path from . import views app_name = 'cricprofile' urlpatterns = [ path('', views.home, name="home"), path('<int:player_id>',views.detail, name="detail") ] views.py in app2. from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request,f'Welcome {username}, Your account created Successfully') return redirect('cricprofile:index.html') else: form = UserCreationForm() return render(request,'users/register.html',{'form':form}) I have created one project with two apps in django. Actual issue is when I try to access html template from one app to another I couldn't redirect. When I tried to redirect I'm getting this error Reverse for 'index' not found. 'index' is not a valid view function or pattern name -
Internal Server Error: /pluscart/, app.models.Cart.MultipleObjectsReturned: get() returned more than one Cart -- it returned 8
views.py from django.db.models import Count from django.shortcuts import render,redirect from django.http import JsonResponse from django.views import View from . models import Product, Cart, Customer from . forms import CustomerRegistrationFrom, CustomerProfileForm from django.contrib import messages from django.db.models import Q def plus_cart(request): if request.method == "GET": prod_id=request.GET['prod_id'] c = Cart.objects.get(Q(product=prod_id) & Q (user=request.user)) c.quantity+=1 c.save() user = request.user cart = Cart.objects.filter(user=user) amount = 0 for p in cart: value = p.quantity * p.product.discounted_price amount = amount + value totalamount = amount + 40 #print(prod_id) data={ 'quantity':c.quantity, 'amount':amount, 'totalamount':totalamount, } return JsonResponse(data) script.js $('.plus-cart').click(function(){ var id=$(this).attr("pid").toString(); var eml = this.parentNode.children[2] console.log("pid =",id) $.ajax({ type:"GET", url:"/pluscart", data:{ prod_id:id }, success:function(data){ console.log("data = ",data); eml.innerHTML = data.quantity document.getElementById("amount").innerText=data.amount document.getElementById("totalamount").innerText=data.totalamount } }) }) Internal Server Error: /pluscart/ Traceback (most recent call last): File "C:\Users\SIRI\OneDrive\Desktop\E-com\env\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\SIRI\OneDrive\Desktop\E-com\ec\app\views.py", line 127, in plus_cart c = Cart.objects.get(Q(product=prod_id) & Q (user=request.user)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\SIRI\OneDrive\Desktop\E-com\env\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\SIRI\OneDrive\Desktop\E-com\env\Lib\site-packages\django\db\models\query.py", line 640, in get raise self.model.MultipleObjectsReturned( app.models.Cart.MultipleObjectsReturned: get() returned more than one Cart -- it returned 8! [07/May/2023 20:18:49] "GET /pluscart/?prod_id=1 HTTP/1.1" 500 77472 Here am try to increase the quantity but it shows error -
Not able to expand a field in drf
I have a story model which has to fields brand and company as a foriegnkey. Now when trying to get story through get request i want to expand the brand and company of that particular story. I am using FlexFieldsModelSerializer and have added the brand and company in the expandable fields but it still does not work. Can someone please help me with it. class Story(AbstractModel): company = models.ForeignKey( 'core.Company', on_delete=models.CASCADE, related_name='company') brand = models.ForeignKey( 'core.Brand', on_delete=models.CASCADE, related_name='brand') viewer = models.CharField(choices=VIEWER_CHOICES.choices,max_length=20,null=True,blank=True) text = models.TextField() type = models.CharField(choices=STORY_TYPES.choices, max_length=50) class Meta: verbose_name = "Story" verbose_name_plural = "Stories" def __repr__(self): return f"{self.__class__.__name__} <{self.company}>" class StorySerializer(FlexFieldsModelSerializer): update_url = CustomURIField(view_name="core:story-detail") class Meta: model = Story fields = '__all__' expandable_fields = { "brand": ('core.BrandSerializer', {"source": "brand"}), "company": ('core.CompanySerializer', {"source": "company"}), "media": ('core.StoryImageSerializer', {"source": "media", 'many': True}), } I am sending get request like this using postman {{ROOT_URL}}/api/v1/core/stories/?expand=company { "id": 54, "update_url": "http://localhost:8000/api/v1/core/stories/54/", "media": [], "created_at": "2023-05-05T09:44:51.475030", "updated_at": "2023-05-05T09:44:51.475043", "viewer": "both", "text": "photo test", "type": "image", "company": 919, "brand": 21 As seen above I am not getting the company expanded. -
Access Denied when connection to mysql in Django
In my newly created django project, I configured MySQL connection instead of default sqlite3. When I ran python manage.py runserver, I receive access denied error: The Django complains wrong user&password, but I think both are correct as I repeatedly login mysql cli console with both. Any tips and suggestion for these access denied appreciated. Following are some backgrounds. The python is 3.9 in ubuntu22.04. The django project is newly created, and I use pymysql instead of mysqlclient for mysql operation. Therefore, I only made two changes: init pymysql Code sample import pymysql pymysql.version_info=(1,4,3,"final",0) pymysql.install_as_MySQLdb() Configure the MySQL connection info I also tried the same in the python console, and shows the user&password should be ok. >>> import pymysql >>> conn = pymysql.connect( ... host='localhost', ... user='test', ... password = "test", ... db='xxx', ... ) >>> conn <pymysql.connections.Connection object at 0x7f065c51ebe0> >>> cur = conn.cursor() >>> cur <pymysql.cursors.Cursor object at 0x7f065ccd0ee0> >>> cur.execute("select @@version") 1 >>> output = cur.fetchall() >>> print(output) (('8.0.32-0ubuntu0.22.04.2',),) >>> conn.close() -
How can I efficiently get related data from a 1 to 1 related table in Django?
I have the following models. (I am including only part of the actual full definition, since the rest isn't relevant to the question.) class Event(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField() title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) class Translation(models.Model): event = models.ForeignKey(Event, related_name="translation_event", on_delete=models.CASCADE, null=True) title = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) I want to create a queryset on the Event table and then join that with the translated data. In other words I want a left outer join between the Event table and the Translation table. If I have a queryset (called queryset) on the Event table, from what I understand from a number of examples I saw as well as the documentation, I should be able to do the following: queryset = queryset.select_related("translation_event") for event_obj in queryset: print(event_obj.title) print(event_obj.translation_event.title) However, when Django gets to the "for event_obj in queryset" line, it throws an exception: django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'translation_event'. (It then gives a list of some valid field names, which are fields in the Event table that have foreign key relationships to other tables.) It almost seems like the select_related allows going from the Event table to other tables, … -
Django How to mock JWT Access Token validation
In my unit test, I have the following code, where I've to generate a new token every time I need to run the test. I want to provide some mock token which also means I need to mock the token validation as well. But I'm not sure how to mock the validation. If I can get any help on this, it would be great. Thanks Settings 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTStatelessUserAuthentication', ], Testcase from apps.common.helpers import get_auth0_access_token class TestDatasetListTestCase(APITestCase): def setUp(self): options = { "url": f"https://{auth0_domain}/oauth/token", "headers": {"cache-control": "no-cache", "content-type": "application/json"}, "json": {"audience": audience, "grant_type": grant_type, "client_id": client_id, "client_secret": client_secret}, } res = requests.post(**options) res_json = res.json() access_token = res_json["access_token"] self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token}") payload = {"label": "new_label"} response = self.client.post(self.url, payload, format="multipart") -
Django richtextupload field error with search
I try to search a field on a model, The field is RichTextUploadingField, so the search is not working in django admin. ANY IDEAS?? I take this error django.core.exceptions.FieldError: Unsupported lookup 'search' for RichTextUploadingField or join on the field not permitted. To solve the bug and find the error -
Chart is not showing on the webpage instead the data from JSON while using Highcharts in Django
So, I am trying to make a candlestick chart using Highcharts in Django , but am not able to show to chart on the webpage, instead a JSON list of the fetched data. I am using the API from iexcloud to fetch the historical data Here is my logic: views.py file: def candlestick_chart_data(request): api_key = 'my_api_key' stock_data = get_historical_data( "AAPL", start="2023-01-01", end="2023-05-05", output_format="pandas", token=api_key) stock_data_array = [{ 'x': date.isoformat(), 'open': row['open'], 'high': row['high'], 'low': row['low'], 'close': row['close'] } for date, row in stock_data.iterrows()] return JsonResponse(stock_data_array, safe=False) my template, i.e., candlestick_chart.html {% extends 'base.html' %} {% block content %} {% block home_css %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highcharts/9.2.1/css/highcharts.css" integrity="sha512-bwK5pU3LlQlAocA38e/L90g86uJUZVvJEnpnT5ZyL0j3frzAKcJbhdTl0z0W4pVfTqBqftbX2y/3D2wLxbt6uQ==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/modules/stock.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> <script src="https://code.highcharts.com/modules/export-data.js"></script> {% endblock %} <div id="container" style="height: 500px; width: 100%;"></div> <script> const dataURL = '{% url "candlestick-chart" %}'; /** * Load new data depending on the selected min and max */ function afterSetExtremes(e) { const { chart } = e.target; chart.showLoading('Loading data from server...'); fetch(`${dataURL}?start=${Math.round(e.min)}&end=${Math.round(e.max)}`) .then(res => res.ok && res.json()) .then(data => { console.log(data) chart.series[0].setData(data); chart.hideLoading(); }).catch(error => console.error(error.message)); } fetch(dataURL) .then(res => res.ok && res.json()) .then(data => { data.forEach((d) => { d.x = new Date(d.x); }); // create the chart Highcharts.stockChart('container', { chart: … -
Unable to open shape_predictor_68_face_landmarks.dat
when i run the command >python manage.py runserver, then I get an error, I don't understand how to solve it, google and similar questions on this topic didn't help. I tried to replace the files in the face_recognition folder, but it also didn't help me. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Пользователь\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File … -
Handle authentication in chrome extension with a Django website
I wanted to know the best way to authenticate users in a chrome extension using a django website, like when the user is logged in in the website, he will be logged in in the extension as well, however I don't want to use Django rest framework, I have a classical Django website, I tried to read cookies form the extension, but I don't know if its a good solution, and I couldn't send the information from the service worker to the content script, I want to know the best way (and modern with manifest v3 and Django 4) to handle this, (I want to implement this to manage Stripe payments). Thank you for your answer. -
Traceback Error : raise self.model.DoesNotExist(__fake__.StartUp.DoeNotExist: StartUp matching query does not exist
This is my models.py file from django.db import models from django.urls import reverse class Tag(models.Model): name = models.CharField(max_length=31, unique=True) slug = models.SlugField(max_length=31, unique=True, help_text = 'A label for URL config') class Meta: ordering = ['name'] def __str__(self): return self.name.title() def get_absolute_url(self): return reverse('organizer_tag_detail', kwargs={'slug': self.slug}) def get_update_url(self): return reverse('organizer_tag_update', kwargs={'slug' : self.slug}) def get_delete_url(self): return reverse('organizer_tag_delete', kwargs={'slug':self.slug}) class StartUp(models.Model): name = models.CharField(max_length=31, db_index=True) slug = models.SlugField(max_length=31,unique=True, help_text='A label for URL config') description = models.TextField() founded_date = models.DateField() contact = models.EmailField('date founded') website = models.URLField() tags = models.ManyToManyField(Tag, blank=True) class Meta: ordering = ['name'] get_latest_by = 'founded_date' def __str__(self): return self.name def get_absolute_url(self): return reverse('organizer_startup_detail', kwargs={'slug':self.slug }) def get_update_url(self): return reverse('organizer_startup_update', kwargs={'slug': self.slug}) def get_delete_url(self): return reverse('organizer_startup_delete', kwargs={'slug': self.slug}) class NewsLink(models.Model): title = models.CharField(max_length=63) slug = models.SlugField(max_length=63) pub_date = models.DateField('date published') link = models.URLField(max_length=255) startup = models.ForeignKey(StartUp, on_delete=models.CASCADE) class Meta: verbose_name ='news article' ordering = ['-pub_date'] get_latest_by = 'pub_date' unique_together = ('slug', 'startup') def __str__(self): return "{} : {}" .format( self.startup, self.title ) def get_absolute_url(self): return self.startup.get_absolute_url() def get_update_url(self): return reverse('organizer_newslink_update', kwargs={'pk':self.pk}) def get_delete_url(self): return reverse('organizer_newslink_delete', kwargs={'pk':self.pk}) ............................................................................................ This is migration file for startup from django.db import migrations from datetime import date STARTUPS = [ { "name" : "Arachnobots", "slug": "arachnobots", … -
The save function of neomodel is not working
I have a neomodel Model: from neomodel import StructuredNode, StringProperty, UniqueIdProperty, db db.set_connection('bolt://neo4j:password@masir_neo4j:7687') class City(StructuredNode): id = UniqueIdProperty() name = StringProperty(index=True, default="city") I've installed labels to the neo4j database by this command which is represented in the neomodel's documentation: neomodel_install_labels manage.py app.models --db bolt://neo4j:password@masir_neo4j:7687 After running this command the City node is added to the neo4j database, then I'm trying to add some data to the database by Python shell, here is the result: But, as you can see there is nothing in the City node. Then I tried to save data by cypher_query and it worked: Why the save function of neomodel isn't working? -
Django Many2Many query to find all `things` in a group of `categories`
Given these Django models: from django.db import models class Thing(models.model): name = models.CharField('Name of the Thing') class Category(models.model): name = models.CharField('Name of the Category') things = models.ManyToManyField(Thing, verbose_name='Things', related_name='categories') I'm really struggling to build a query set that returns all Things in all of a set of Categories. To clarify, let's say we have 5 categories, with IDs 1, 2, 3, 4, 5. I want to find all Things that are in say categories, 2 AND 3. I can find all Things in category 2 OR 3 easily enough. For example this: Thing.objects.filter(categories__in=[2,3]) seems to return just that, Things in category 2 OR 3. And something like: Thing.objects.filter(Q(categories=2)|Q(categories=3)) also, but this: Thing.objects.filter(Q(categories=2)&Q(categories=3)) Returns nothing. I might envisage something like: Thing.objects.filter(categories__contains=[2,3]) but of course that's a dream as contains operates on strings not m2m sets. Is there a standard trick here I'm missing? -
loading initial data from fixtures.json to django test database with pytest
I work on a legacy code that have some initial data for Status model with predefined pk in status_data.json that has been loaded with the command python manage.py loaddata <fixturename>. { "model": "status.Status", "pk":4, "fields": { "item": "Achat", "table": "billing_models", "attribute": "status_billing_models" } } With some models that has foreign key relationship with Status model, the status' pks are STATIC: class BillingModel(Timestemps, SafeDeleteModel): ACHAT = 4 ACTIVATION = 5 name = models.CharField(max_length=200) # ... more fields here # achat or activation cycle_start_at = models.ForeignKey(Status, models.CASCADE) Now i want to write some tests for this legacy code, and i wanna know how to load these initial data in django tests database with pytest so that i can write some tests based on this initial data. -
django admin. create a custom autocomplete field when adding MTM links to admin.TabularInline
I have three django models. class User(models.Model): user_id = models.BigIntegerField(_('user_id'), primary_key=True, blank=False) permission = models.CharField(_('permission'), max_length=30, choices=UserPermissionType.choices) name = models.CharField(_('name'), max_length=255) chat_id = models.BigIntegerField(_('chat_id'), ) def __str__(self): return self.name class Meta: managed = False db_table = 'users' verbose_name = _('User') verbose_name_plural = _('Users') class Store(models.Model): store_id = models.AutoField(_('store_id'), primary_key=True) store_name = models.CharField(_('store_name'), unique=True, max_length=150) users = models.ManyToManyField(User, through='StoreUser') def __str__(self): return self.store_name class Meta: managed = False db_table = 'stores' verbose_name = _('Store') verbose_name_plural = _('Stores') class StoreUser(models.Model): store = models.ForeignKey('Store', models.DO_NOTHING) user = models.ForeignKey('User', models.DO_NOTHING) class Meta: managed = False db_table = 'stores_users' unique_together = (('store', 'user'),) I am trying to make it so that when adding a store to a user on the user's page in the TabularInline field, I would see a drop-down list with lines like f"{store_id}: {store_name}". at the same time, I would like the autocomplete to work on this field I've tried a lot of options. Now I have this variant, but I don't seem to understand at all how AutocompleteSelect works class StoreAutocompleteField(forms.ModelChoiceField): queryset = Store.objects.all() widget = AutocompleteSelect(StoreUser._meta.get_field('store').remote_field, admin.site) def label_from_instance(self, obj): return f"{obj.id}: {obj.name}" class UserStoreInline(admin.TabularInline): model = StoreUser extra = 0 verbose_name = _('Stores for user') def formfield_for_foreignkey(self, db_field, request, … -
on-load Modal blocked by cookiebot
I have a website with an age gate. I've also installed cookiebot to handle the cookies for me. The age gate pops up with a bootstrap modal when you load the page. This worked perfect. Except cookiebot now blocks this from happening and the age-gate does not show up until you reload the page after you accepted (or denied) cookiebot. How can I fix this? I've tried moving the on-load script to the top of my page, about the cookiebot script but that didn't work. Any help would be much appreciated. This is the script I use right now to check for the age-gate and show the model if someone has not verified yet: window.onload = () => { var koekje = Cookies.get('ofage'); if(!koekje){ $('#onload').modal('show'); }; }; -
Django rest framework, JSON parsing
In django have file models.py: class RawTransactionSale(models.Model): summ = models.DecimalField(max_digits=19, decimal_places=2) sign = models.CharField(max_length=12) payments = models.JSONField(blank=False) merchant = models.JSONField(blank=False) class PaymentTable(models.Model): date = models.DateTimeField() PaymentID = models.UUIDField(default=uuid.uuid4, editable=False, blank=False) paymentAmount = models.DecimalField(max_digits=19, decimal_places=2) raw_transaction_sale = models.ForeignKey('RawTransactionSale', on_delete=models.CASCADE, related_name='raw_transaction_sale') class MerchantTable(models.Model): merchantName = models.CharField(max_length=255, blank=False) merchantID = models.UUIDField(default=uuid.uuid4, editable=False, blank=False) payment = models.ForeignKey('PaymentTable', on_delete=models.CASCADE, related_name='merchant') file serializers.py: class PaymentSerializer(serializers.ModelSerializer): class Meta: model = PaymentTable fields = '__all__' class MerchantSerializer(serializers.ModelSerializer): class Meta: model = MerchantTable fields = '__all__' class RawTransactionSaleSerializer(serializers.ModelSerializer): class Meta: model = RawTransactionSale fields = '__all__' file views.py: class RawTransactionSaleViewset(viewsets.ModelViewSet): queryset = RawTransactionSale.objects.all() serializer_class = RawTransactionSaleSerializer def create(self, request, *args, **kwargs): serializer = RawTransactionSaleSerializer(data=request.data) serializer.is_valid(raise_exception=True) validated_data = serializer.validated_data payments_data = validated_data.pop('payments') merchant_data = validated_data.pop('merchant') merchant_serializer = MerchantSerializer(data=merchant_data) merchant_serializer.is_valid(raise_exception=True) merchant = merchant_serializer.save() raw_transaction_sale = RawTransactionSale.objects.create(merchant=merchant, **validated_data) for payment_data in payments_data: payment_data['raw_transaction_sale'] = raw_transaction_sale.id payment_serializer = PaymentSerializer(data=payment_data) payment_serializer.is_valid(raise_exception=True) PaymentTable.objects.create(raw_transaction_sale=raw_transaction_sale, **payment_serializer.validated_data) serializer = self.get_serializer(raw_transaction_sale) return Response(serializer.data, status=status.HTTP_201_CREATED) In API recieve JSON: { "summ": 1860.0, "sign": "123456677531", "SaleMerchID": "ca9f9c0d-c2d0-321d-8b9a-123c3fc5b543", "merchant" : { "merchantName": "SuperShop", "merchantID" : "12345678-1234-abcd-dcab-123abc456def", }, "payments": [ { "date": "2023-04-27T15:50:15.000+0400", "PaymentID": "4dba1234-f19e-1234-a432-ca5d15f9ec21", "paymentAmount": 1860, } ], } I'm try from JSON save payments in separated table PaymentTable, merchant in separated table MerchantTable, link with this transaction PaymentTable and MerchantTable, but … -
Django-allauth social with custom adapter for creating a profile in production
Iam using django-allauth with dj-rest-auth with the apple provider. The strange issue only happens in production. After getting the token from apple for verifying the user, i send it to the django backend. I made a custom adapter which is appended from DefaultSocialAccountAdapter and override the save_user function: class SocialAccountAdapter(DefaultSocialAccountAdapter): def save_user(self, request, sociallogin, form=None): user = super().save_user(request, sociallogin, form) profile = Profile.objects.get_or_create(user=user) url = sociallogin.account.get_avatar_url() avatar = download_file_from_url(url) if url else None if avatar is not None: avatar_obj = UserImageAvatar( file=avatar, creator=user ) with atomic(): avatar_obj.save() image = UserImageAvatar.objects.get(id=avatar_obj.id) user.profile.avatar = image user.profile.save(update_fields=['avatar']) return user setting.py SOCIALACCOUNT_ADAPTER = 'core.adapters.SocialAccountAdapter' for creating a profile after the user is created. Locally it works all just fine. But in production, the user will be created, but without a username and without a profile, maybe the adapter is not be user? Settings are the same as in debug. I am really slowly at the end and would be happy about any little hint or help -
How to reuse class in async Django view
I've made a class with requests inherited from httpx: class URLRequest: """URL request class.""" def __init__(self, client): self.client = httpx.AsyncClient(follow_redirects=True) async def close_session(self): """Close session.""" await self.client.aclose() async def get_url(self, url: str): """Request url with GET method.""" try: response = await self.client.get(url=url) return response except Exception as e: print(e) return httpx.Response(status_code=500) Somewhere in my views.py: async def run(request, url): s = URLRequest() # is that correct to create it here? response = await s.get_url(url) return render(request, "index.html", context=response.text) I want to use one instance of httpx.AsyncClient across many Django views (or maybe there is a better approach) to save hardware resources. So I've made a separate method close_session, but I do not understand where I need to call close_session(). I can make it this way and do not bother about closing it myself: async with httpx.AsyncClient() as client: r = await client.get('https://www.example.com/') But creation a new session instance for every request is a bad idea. -
Django limit queryset
I have three models in simple Django Project. I want to filter Versions by brand while adding in admin page. I've tried in different ways and one of them is iclude in attached code. admin.py file also likes as it shown. Any suggestions ? class Brand(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Version(models.Model): name = models.CharField(max_length=100) manufacturer = models.ForeignKey(Brand, on_delete=models.CASCADE) def __str__(self): return f"{self.name} ({self.manufacturer})" class Car(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) version = models.ForeignKey( Version, on_delete=models.CASCADE, limit_choices_to=Q(manufacturer=OuterRef('manufacturer_id')) ) year = models.PositiveIntegerField() color = models.CharField(max_length=50) mileage = models.PositiveIntegerField() def __str__(self): return f"{self.brand} {self.version} {self.year} {self.color}"``` class CarAdminForm(forms.ModelForm): class Meta: model = Car fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance: self.fields['version'].queryset = self.instance.brand.versions.all() class CarAdmin(admin.ModelAdmin): form = CarAdminForm admin.site.register(Car, CarAdmin) this is how I tried but w/o success. -
How to include {%url%} in js innerHTML?
mainPage.html {% load static %} <!DOCTYPE html> <html lang="en"> <body> <div style="display: flex"> <div id="menu" class="menu"></div> </div> <a class="menu-item" href="{% url 'users' %}">users</a> //this WORKS </body> <script src="{% static 'js/menu.js' %}"></script> </html> menu.js document.getElementById('menu').innerHTML = ` <a class="menu-item" href="{% url 'users' %}">users</a> //this DONT work `; url.py from django.urls import path from . import views urlpatterns = [ path("",views.mainPage), path("users/",views.users,name='users'), ] How to make the url also work in menu.js? it works when I put it in html file. -
How to migrate an edited model after instectdb in Django Rest?
I am completely new to Django Rest. I'm trying to build a small API to learn. In my local database I have a table named "api_task" with the following structure: api_task: { task_id[PK], task_title varchar(15), task_description varchar(150) } I ran the command python manage.py inspectdb api task > models.py to include that table in the Django project. I added a field and made some changes to the model: class ApiTask(models.Model): task_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100, blank=True) description = models.TextField(max_length=250, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: db_table = 'api_task' After that, I created the migration with python manage.py makemigrations api, where "api" is just the application name. When executing the migration it throws an error: jango.db.utils.ProgrammingError: relationship already exists. I was looking through the information on this topic and tried to run the command python manage.py makemigrations api --fake but the model changes are not reflected in the database. I also tried running the command python manage.py migrate api --run-syncdb, but it throws another error: Cannot use run_syncdb with application 'api' as it has migrations. I know Django says you can't change field names or their values to prevent loss of information I think, but that's … -
Trying to add video to webpage and I keep gettting 404 error anyone know how to fix it?
I believe I have tried almost everything. What I am working with -
Djnago views.py need some assistance to visualize my uploaded file to html
I am working on Django project. I created HTML, css and js files for templates where user can choose a file with choose file button. It is control by .js file. My js file looks like this: document.addEventListener('DOMContentLoaded', function() { const uploadBtn = document.querySelector(".upload-btn"); const trainBtn = document.querySelector(".train-btn"); const visualizeBtn = document.querySelector(".visualize-btn"); const fileInput = document.querySelector("#file-input"); const img = document.querySelector(".csv"); let file = null; // To store the uploaded file uploadBtn.addEventListener("click", (event) => { console.log("Upload button clicked"); event.preventDefault(); fileInput.click(); }); fileInput.addEventListener("change", (event) => { file = event.target.files[0]; // Update the uploaded file if (file) { const reader = new FileReader(); reader.onload = (e) => { const fileURL = e.target.result; img.src = fileURL; visualizeBtn.disabled = false; }; reader.readAsDataURL(file); trainBtn.disabled = false; } else { visualizeBtn.disabled = true; trainBtn.disabled = true; } }); visualizeBtn.addEventListener("click", () => { console.log("Visualizing data..."); if (file) { const reader = new FileReader(); reader.onload = (e) => { const fileContent = e.target.result; saveFile(fileContent); }; reader.readAsText(file); } }); function saveFile(fileContent) { const filename = 'data/' + file.name; const link = document.createElement('a'); link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContent)); link.setAttribute('download', filename); document.body.appendChild(link); link.click(); document.body.removeChild(link); } }); I am trying to create a views in views.py file. where I want to visualize data information … -
Django cannot download docx file in ajax
I have a script directs to badownload function for downloading docx file. The result of this function is download docx file but it didn't work. Here is the script. <script> $("#download_draft").click(function(){ $("#download_draft").attr("disabled","disabled"); $("#download_draft").text("Saving Data...."); var json_data={}; $(".input_data").each(function(){ var value=$(this).val(); var parent_html=$(this).parent(); parent_html.html(value); $(this).remove(); }); var jenis_ba = $('#id_jenis_ba').val(); json_data['jenis_ba'] = jenis_ba; var nomor= $('#id_nomor').val(); json_data['nomor'] = nomor; var tanggal = $('#id_tanggal').val(); json_data['tanggal'] = tanggal; var judul = $('#id_judul').val(); json_data['judul'] = judul; var keterangan = $('#keterangan').val(); json_data['keterangan'] = keterangan; var json_tim = []; $("tbody tr").each(function(row, tr){ json_tim[row] = { 'nama_tim' : $(tr).find('td:eq(0) input').val(), 'nip_tim' : $(tr).find('td:eq(1) input').val() } }); json_data['tim'] = json_tim; var string_data=JSON.stringify(json_data); const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; $.ajax({ url:'{{ download_draft }}', headers: {'X-CSRFToken': csrftoken}, type:'GET', dataType: 'json', data:{data:string_data}, success: function(data) { badownload(data); }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); }, complete: function() { $("#download_draft").removeAttr("disabled"); $("#download_draft").text("Download Draft"); } }); function badownload(result){ $.ajax({ url: '../../berita-acara/badownload', headers: {'X-CSRFToken': csrftoken}, type:'POST', dataType: 'json', data:{data:result.result}, success: function(data) { console.log('sukses'); }, error: function(jqXHR, textStatus, errorThrown) { console.log(url); }, }) } }); </script> This is the function. It has to download download.docx file but it didn't work class BeritaAcaraBA(View): def post(self, request): ..... ...... ....... response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=download.docx' document.save(response) return response I …