Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ordering by the column which is connected with foreign key
I have classes like this, Drawing has the one CustomUser class CustomUser(AbstractUser): detail = models.JSONField(default=dict,null=True,blank=True) NAM = models.CharField(max_length=1024,null=True,blank=True,) class Drawing(SafeDeleteModel): detail = models.JSONField(default=dict,null=True, blank=True) update_user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='update_user') Now I wan to get the list of Drawing by sorting Drawing.update_user.NAM then i made code like this, class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer pagination_class = DrawingResultsSetPagination filter_backends = [filters.OrderingFilter] ordering_fields = ['id','update_user.NAM'] ordering = ['-id'] then call with this url http://localhost/api/drawings/?ordering=-update_user.NAM http://localhost/api/drawings/?ordering=update_user.NAM However in vain. How can I call this ordering? -
React django file upload difference in content-length
I'm trying to upload a PDF file from my react client to my django server (both running locally on my laptop), but I'm observing a difference in the size of the file that is sent from my react client and the file received in the request receieved at my server. The file received in the request at the server does not seem to be a valid PDF file either. This seems to be happening for other file types as well. Attaching relevant screenshots and snippets below where I'm trying to upload a PDF file which is ~4.5 MB in size: React client snippet for uploading the file: const formData = new FormData(); formData.append('file', acceptedFiles[0]); // acceptedFiles comes from a form input const uploadFilesResponse = await axios.request({ method: 'POST', url: `/api/documents/upload/${pathToUpload}`, data: formData, headers: { 'Content-Type': 'multipart/form-data', }, }); The network tab indicating the request I've sent and the file in the request payload: Here's the corresponding request received at the server Even the on disk temporary file created by django for the upload highlighted above (/var/folders/tf/7xrq4m4j11dcfkngpz9j3rfm0000gn/T/tmpil4f5hsn.upload.pdf) seems to be an invalid file which is ~8.5 MB in size. The request object shared above is the request object received at my … -
How can I use only my custom models with social-auth-app-django?
How can I store people logged in or registered with social authentication only in the custom user model? By default, whenever I use social auths, they are registered in User social auths in PYTHON SOCIAL AUTH on the Admin page, but I would like to remove this duplication with the custom user model. This does not mean that I want those displays to disappear from the admin page, but rather that I want to optimize the database space. Libraries I use are DRF, socil-auth-django and Djoser. I want to keep only my custom user model. No other user model is needed. -
Is it possible to remove an item type from a lineitem.aggregate when making a different calculation?
The delivery cost should not include % on booking, but should include % of product price if below the set delivery threshold. Both can be added to an order and at checkout only the product should attract a delivery cost, as the booking relates to buying experiences. I am unable to figure this out, so if anyone can help me I would be most grateful. Below is my model code for checkout, which includes the Order Model where the delivery is being calculated, and Order Line Item Model from where the order total is being calculated using line item aggregate. def update_total(self): """ Updates grand total each time a line item is added, takes into account delivery costs """ self.order_total = self.lineitems.aggregate( Sum('lineitem_total'))['lineitem_total__sum'] or 0 if self.order_total < settings.FREE_DELIVERY_THRESHOLD: self.delivery_cost = self.order_total * \ settings.STANDARD_DELIVERY_PERCENTAGE / 100 else: self.delivery_cost = 0 self.grand_total = self.order_total + self.delivery_cost self.save() class OrderLineItem(models.Model): order = models.ForeignKey( Order, null=False, blank=False, on_delete=models.CASCADE, related_name='lineitems') product = models.ForeignKey(Product, null=True, blank=True, on_delete=models.CASCADE) experience = models.ForeignKey(Experiences, null=True, blank=True, on_delete=models.CASCADE) quantity = models.IntegerField(null=False, blank=False, default=0) lineitem_total = models.DecimalField( max_digits=6, decimal_places=2, null=False, blank=False, editable=False ) price = models.DecimalField( max_digits=6, decimal_places=2, null=False, blank=False,) def get_price(self, *args, **kwargs): if self.product and self.experience: return self.product.price … -
Manager's annotations don't show up when traversing ForeignKey
Suppose I have such classes: class UserManager(Manager): def get_queryset(self): return super().get_queryset().annotate( full_name=Concat( F('first_name'), Value(' '), F('last_name'), output_field=CharField() ) ) class User(Model): first_name = CharField(max_length=16) last_name = CharField(max_length=16) objects = UserManager() class Profile(Model): user = ForeignKey(User, CASCADE, related_name='profiles') And I want to include an annotated field in my query: Profile.objects.filter(GreaterThan(F('user__full_name'), Value(24))) But I got a FieldError: Cannot resolve keyword 'full_name' into field. Choices are: first_name, id, last_name, profiles It's clear that I could repeat my annotation in a current query: Profile.objects.filter(GreaterThan(Concat(F("user__first_name"), Value(" "), F("user__last_name"), output_field=CharField(),), Value(24))) But as soon as my annotations will become more complex, my code become mess. Is there any workaround? -
Cookies not being set in browser when making API request from React, but work with Django REST framework
When I use the Django REST framework to send a POST request to the login endpoint, the cookies are added to the response, and I can observe them in the browser. Additionally, I can confirm that I'm receiving the correct data (user ID and password) in both cases. However, when I use my React application to send the same POST request to the login endpoint, the cookies are not being added to the response, and consequently, they aren't stored in the browser. Again, I receive the correct data (user ID and password) in this scenario as well. My django rest code : @api_view(['POST']) def loginUser(request): print("request", request.data) id_Patient = int(request.data.get('id_Patient')) print("id_Patient", id_Patient) password = request.data.get('password') print("password", password) user = Patient.objects.filter(id_Patient=id_Patient).first() if user is None: print("user is None") return JsonResponse({"message": "User not found"}, status=404) if not user.check_password(password): print("not user.check_password(password)") return JsonResponse({"message": "Incorrect password"}, status=400) payload = { 'id_Patient': user.id_Patient, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } secret_key = os.urandom(32).hex() token = jwt.encode(payload, secret_key, algorithm='HS256') response = JsonResponse({"token": token}) response.set_cookie('my_cookie', 'my_value', httponly=True) # Set the cookie return response What Actually Resulted: Surprisingly, the cookies are being set correctly when I test the API request using Django's REST framework, and I'm receiving the … -
How to resolve ImproperlyConfigured: Cannot import 'core'. Check that 'OutilSuivisEffectifs.apps.core.apps.CoreConfig.name' is correct
my work flow: OutilSuivisEffectifs apps core migrations static templates __init__.py admin.py apps.py forms.py models.py tests.py urls.py views.py __initi__.py settings.py urls.py wsgi.py manage.py my Installed apps in OutilSuivisEffectifs/settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'django_countries', 'bootstrap3_datetime', 'captcha', 'OutilSuivisEffectifs.apps.core', 'import_export' ] my OutilSuivisEffectifs/apps/core/apps.py: from django.apps import AppConfig class CoreConfig(AppConfig): name = 'core' the command I am running is Python manage.py makemigrations The error I get execute_from_command_line(sys.argv) File "C:\Users\c69961\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\c69961\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\c69961\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\c69961\Anaconda3\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\c69961\Anaconda3\lib\site-packages\django\apps\config.py", line 246, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'core'. Check that 'OutilSuivisEffectifs.apps.core.apps.CoreConfig.name' is correct.` I tried to change name : from django.apps import AppConfig class CoreConfig(AppConfig): name = 'OutilSuivisEffectifs.apps.core' But same error -
Return HTTP 404 response with no content-type?
Is there a way in Django to return a HTTP 404 response without a content-type? I tried return HttpResponseNotFound() from my view, but that sends a Content-Type: text/html; charset=utf-8 header. -
Wepback.js Module not Found - React & Django
frontend@1.0.0 build webpack --mode production 'React\music_controller\frontend\node_modules.bin' is not recognized as an internal or external command, operable program or batch file. node:internal/modules/cjs/loader:1080 throw err; ^ I am just starting out with react and Django and I'm having this error when I run the command 'npm run dev' . There are my scripts from my package.json file if this helps: "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, I am just starting out with react and Django and I'm having this error when I run the command 'npm run dev' . There are my scripts from my package.json file if this helps: "scripts": { "dev": "webpack --mode development --watch", "build": "webpack --mode production" }, -
Why Django ORM filter lists all the users?
I like to make a filter where user can search based on last_name or a regio(region). I made the query but it filters well only if I using the last_name filter, but the regio gives all the users in the db. I'm used before Sqlite3 and raw queries but now I like to learn ORM with Postgres so I'm not experienced in ORM yet. What am I doing wrong? models.py class Profil(models.Model): def __str__(self): return str(self.user) def generate_uuid(): return uuid.uuid4().hex user = models.OneToOneField(User, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True, auto_now=False) coach_uuid = models.CharField(default=generate_uuid, editable=True, max_length=40) regio = models.ForeignKey('Regiok', blank=True, null=True, on_delete=models.CASCADE) class Regiok(models.Model): regio = models.CharField(max_length=80) def __str__(self): return str(self.regio) views.py def coachok(request): coach = Profil.objects.all() nev = request.GET.get('nev') regio = request.GET.get('regio') if nev != '' and nev is not None or regio != '' and regio is not None: coach = Profil.objects.filter(Q(user__last_name__icontains=nev) | Q(regio_id__regio=regio)).select_related('user', 'regio') context = { 'coach':coach, } return render(request, 'coachregiszter/coachok.html', context) html <div class="container"> <form method="GET"> <div class="bg-light p-2"> <div class="row my-3"> <h4>Szűrők</h4> <div class="col-md-3"> <h6>Név</h6> <input class="form-control" type="search" name="nev"></input> </div> <div class="col-md-3"> <h6>Vármegye</h6> <select class="form-select" name="regio"> <option value="" selected>Bármelyik</option> <option value="Dél-Dunántúl">Dél-Dunántúl</option> <option value="Közép-Dunántúl">Közép-Dunántúl</option> </select> </div> </div> <button type="submit" class="btn btn-outline-dark">Keresés</button> <a href="/coachok"><button type="submit" class="btn btn-outline-info">Szűrők törlése</button></a> </div> … -
Django- Static HTML pages not loading if DB server is down
In my Django web application, there are many static HTML pages and there is no DB interaction required for these HTML pages. The problem is whenever DB server goes down, the whole site goes down. User cannot even see the static HTML pages. Is there any way to resolve this? -
Problem in setting up Shopify RecurringApplicationCharge in Django App
I am following app structure with reference to https://github.com/Shopify/shopify_django_app repository. I am trying to set up billing for my app using shopify.RecurringApplicationCharge. @shop_login_required def buy_plan(request, id): plan = PlanTable.objects.get(id=id) charge = shopify.RecurringApplicationCharge() charge.name = plan.name charge.price = plan.price charge.test = True charge.return_url = reverse('accept') if charge.response_code == 201: confirmation_url = charge['recurring_application_charge']['confirmation_url'] return redirect(confirmation_url) else: return render(request, 'home/billing.html', context) I also tried the following as mentioned in https://github.com/Shopify/shopify_python_api#billing @shop_login_required def buy_plan(request, id): plan = PlanTable.objects.get(id=id) charge = shopify.RecurringApplicationCharge.create({'name' : plan.name,'price' : plan.price, 'test' : True,'return_url' : reverse('accept')}) if charge.response_code == 201: confirmation_url = charge['recurring_application_charge']['confirmation_url'] return redirect(confirmation_url) else: return render(request, 'home/billing.html', context) But both these methods returned the following error:- ForbiddenAccess at /buy_plan/1 Response(code=403, body="b''", headers={'Date': 'Fri, 18 Aug 2023 12:52:49 GMT', 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked', 'Connection': 'close', 'X-Sorting-Hat-PodId': '319', 'X-Sorting-Hat-ShopId': '72702755136', 'Vary': 'Accept-Encoding', 'Referrer-Policy': 'origin-when-cross-origin', 'X-Frame-Options': 'DENY', 'X-ShopId': '72702755136', 'X-ShardId': '319', 'X-Stats-UserId': '', 'X-Stats-ApiClientId': '54612525057', 'X-Stats-ApiPermissionId': '604913992000', 'X-Shopify-API-Version': 'unstable', 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT': '1/40', 'X-Shopify-Shop-Api-Call-Limit': '1/40', 'Strict-Transport-Security': 'max-age=7889238', 'Server-Timing': 'processing;dur=92', 'X-Shopify-Stage': 'production', 'Content-Security-Policy': "default-src 'self' data: blob: 'unsafe-inline' 'unsafe-eval' https://* shopify-pos://*; block-all-mixed-content; child-src 'self' https://* shopify-pos://*; connect-src 'self' wss://* https://*; frame-ancestors 'none'; img-src 'self' data: blob: https:; script-src https://cdn.shopify.com https://cdn.shopifycdn.net https://checkout.shopifycs.com https://api.stripe.com https://mpsnare.iesnare.com https://appcenter.intuit.com https://www.paypal.com https://js.braintreegateway.com https://c.paypal.com https://maps.googleapis.com https://www.google-analytics.com https://v.shopify.com 'self' 'unsafe-inline' 'unsafe-eval'; upgrade-insecure-requests; … -
django layout template tags with async view
I'm trying to access my template page.html from an async view. My question is very similar to the one asked here. Yet, the difference is that page.html extends a layout.html layout. The SynchronousOnlyOperation is triggered by the presence of {{request.user}} I'm using in the layout, not directly in page.html. layout.html <span class="d-flex flex-row dashboard-settings-icon mx-2"> <i class="bi bi-person-circle"></i> <ul> <li> <a class="dropdown-toggle" href="#" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false" > {{request.user}} </a> <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink" > <li> <a class="dropdown-item" href="{% url 'logout_user' %}" ><i class="bi bi-box-arrow-left"></i> Logout</a > </li> </ul> </li> </ul> </span> page.html {% extends 'layouts/layout.html' %} {% block content %} {% load static %} <form action={% url 'account:upload' %} method="post" enctype="multipart/form-data"> {% csrf_token %} # form </form> {% endblock content %} The view async def upload(request): if request.POST: form = ModelFormClass(request.POST, request.FILES) if form.is_valid(): if request.FILES: # File handling results = await process_data() await form.save() return render(request, "pages/account/results.html", {"form":form, "results":results}) else: return render(request, "pages/account/page.html", {"form":form}) return render(request, "pages/account/page.html", {"form":ModelFormClass}) As there's no view for displaying the layout itself, I tried the following in the view responsible of page.html display: async def upload(request): if request.POST: form = ModelFormClass(request.POST, request.FILES) if form.is_valid(): if request.FILES: # File handling results = await process_data() … -
Annonate Data and group it by one Attribute
I have a Templatet that displays all Vulnerabilities grouped by Clients. I use this Query qs = client.objects.prefetch_related(Prefetch('clientvul_set', clientvul.objects.select_related('VID'))) to selcet all related Vulnerabilties to one Client. The clientvul Database also contains a product field. I also want to display how many vulnerabilities are in each product. If I try to prefetch_related first and then annonate the Data I get "attributeerror 'queryset' object has no attribute 'split'". I can count the Data but cannout group it by a Client. Models.py import datetime from django.db import models from django.contrib import admin class client(models.Model): client= models.CharField(max_length=50,primary_key=True) user= models.CharField(max_length=100) vuls = models.ManyToManyField( 'vul', through='clientvul', related_name='client' ) class vul(models.Model): vid=models.IntegerField(primary_key=True) cvelist=models.CharField(max_length=50) serverity=models.CharField(max_length=25) title=models.CharField(max_length=1000) summary=models.CharField(max_length=1000) class clientvul(models.Model): client= models.ForeignKey(client, on_delete=models.CASCADE) vid=models.ForeignKey(vul, on_delete=models.CASCADE) path=models.CharField(max_length=1000) product=models.CharField(max_length=1000) isActive=models.BooleanField(default=True) class Meta: constraints = [ models.UniqueConstraint( fields=['client', 'vid'], name='unique_migration_host_combination' # legt client und VID als Primarykey fest ) ] admin.site.register(client) admin.site.register(vul) admin.site.register(clientvul) view.py def index(request): if not request.user.is_authenticated: return redirect(login_user) else: qs = client.objects.prefetch_related(Prefetch('clientvul_set', clientvul.objects.select_related('vid'))) gProduct=(clientvul.objects .values('Product') .annotate(pcount=Count('Product')) .order_by('-pcount') ) querys={ 'data':qs, 'groupedProduct':gProduct } print(querys) return render(request, 'browseDB.html',querys) template.html {% for row in data %} <div class="card"> <div class="card-body"> <table class="table"> <thead class="table-dark"> <tr> <th scope="col"><h4>hostname</h4></th> <th scope="col"><h4>user</h4></th> <th class="text-right"> <div class="btn-group"> <button class="btn btn-secondary" data-toggle="collapse" data-target="#{{ row.client }}-vul" data-parent="#myGroup"> … -
TemplateDoesNotExist at /blog/createposts/ [No template names provided ]
I am newbie to django. I do not know how to fix this issue. What I have tried: DIR ['templates'] [TEMPLATE_DIR,] TEMPLATE_DIRS = ('os.path.join(BASE_DIR, "templates"),') amazonbackend/ amazonbackend/ settings.py urls.py manage.py Homepage/ migrations templates a.html b.html static Blog/ migrations templates blog_post.html rich_text_editor_component.html static -
Django CSRF failing with .env file for Docker
Hi I'm using Docker to build a Django web application via Docker-Compose and it uses the .env.dev file for the environmental variables. The problem is the CSRF_TRUSTED_ORIGINS variables : If i put variables inside the settings.py => Ok If i put variables inside the env.dev => KO ( AttributeError: 'NoneType' object has no attribute 'split') settings.py # CSRF_TRUSTED_ORIGINS=["https://www.site1.fr", "http://www.site1.fr"] CSRF_TRUSTED_ORIGINS= os.environ.get("DJANGO_CSRF").split(" ") env.dev DJANGO_CSRF=https://www.site1.fr http://www.site1.fr -
Django Migration - User ForeignKey - (errno: 150 "Foreign key constraint is incorrectly formed")
I can't perform a migration for a User foreign key and I've tried everything. This is the model: class Test(TimeStampedModel): key = models.ForeignKey("users.User", on_delete=models.CASCADE) And this is the migration part (settings.AUTH_USER_MODEL is generated by makemigrations): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("xxxxx", "xxxxx"), ] operations = [ migrations.CreateModel( name="Test", fields=[ ( "key", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, ), ), Note that I've tried to set my model variable like this: key = models.ForeignKey(User, on_delete=models.CASCADE) I've also tried to replace settings.AUTH_USER_MODEL by the user class name like: ( "key", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="users.User", ), ), Note also User have been created before the migration, I've checked it with this code: def check_table_exists(apps, schema_editor): if not schema_editor.table_exists('users_user'): raise RuntimeError('users_user must exist!') class Migration(migrations.Migration): dependencies = [...] operations = [ migrations.RunPython(check_table_exists), # Other operations ] Whatever the solution I'm trying I've always the same MySQLdb._exceptions.OperationalError: (1005, 'Can't create table mdc.alerts_alertchanges (errno: 150 "Foreign key constraint is incorrectly formed")') -
How to protect a single database row / Model instance?
We have customers, and Customer objects. One of these, which I was creating with a migration, was Customer( account='INTERNAL' ...) as a placeholder for when we manufacture stuff for internal consumption. Customers come and go, so the objects need to be deletable. But this single row must not be deleted. What is the best way to stop it getting accidentally deleted? I can replace all instances of Customer.objects.get(account='INTERNAL') with get_or_create so it is self-resurrecting, but it feels like storing up trouble for the future if there are ForeignKey references to it and then it gets deleted. (It can't be Models.PROTECT, because other customers can be deleted). Tagged [postgresql], because that's what we use. I suspect there might be a way to use database functionality to do what I want, but I'd appreciate it if the answer showed how to write doing that as a Django migration (if that's possible). I know more about Django than SQL and Postgres extensions. -
Authentication tokens expiring or being deleted after a page refresh
I'm using using Django with Django Rest Framework for my backend API and DJOSER for authentication, along with the **djangorestframework_simplejwt **package for handling JSON Web Tokens (JWT). I have configured the token lifetimes in my settings.py file, but I've encountering issues with authentication tokens expiring or being deleted after a page refresh in my backend. Here is my auth.js file from React: import axios from 'axios'; import { LOGIN_SUCCESS, LOGIN_FAIL, USER_LOADED_SUCCESS, USER_LOADED_FAIL, AUTHENTICATED_SUCCESS, AUTHENTICATED_FAIL, LOGOUT } from './types'; export const checkAuthenticated = () => async (dispatch) => { if (localStorage.getItem('access')) { const config = { headers: { 'Content-type': 'application/json', 'Accept': 'application/json', }, }; const body = JSON.stringify({ token: localStorage.getItem('access') }); try { const res = await axios.post( `${process.env.REACT_APP_API_URL}/auth/jwt/verify/`, body, config ); if (res.data.code !== 'token_not_valid') { dispatch({ type: AUTHENTICATED_SUCCESS, }); } else { dispatch({ type: AUTHENTICATED_FAIL, }); } } catch (err) { dispatch({ type: AUTHENTICATED_FAIL, }); } } else { dispatch({ type: AUTHENTICATED_FAIL, }); } }; export const load_user = () => async (dispatch) => { if (localStorage.getItem('access')) { const config = { headers: { 'Content-type': 'application/json', Authorization: `JWT ${localStorage.getItem('access')}`, Accept: 'application/json', }, }; try { const res = await axios.get( `${process.env.REACT_APP_API_URL}/auth/users/me/`, config ); dispatch({ type: USER_LOADED_SUCCESS, payload: res.data, }); … -
Djano format TextField space every 4 digits (IBAN)
I'm having a TextField and in my form and I'm trying to make a space every 4 digits because I want the IBAN format of 16 digits XXXX-XXXX-XXXX-XXXX. I read about the python package "django-iban" and imported it, but the form formatting didnt work. Is there another way to force the TextField to make a space every 4 digits? -
filter data in table 1 that is not referenced in table 2 through foreign key in python
I have two tables table 1 and table 2, table 2 has a foreign key from table 1 in this case I intend to select all customers from table 1 that are not yet registered in table 2 models.py: class Cliente(models.Model): contador = models.AutoField(primary_key=True) ---------**--------------------- class Factura(models.Model): factura_nr = models.CharField(primary_key=True,max_length=100) contador = models.ForeignKey(Cliente,on_delete=models.CASCADE) estado_factura=models.CharField(max_length=20,default='Aberta',blank=True) views.py facturas_abertas2=Factura.objects.values('contador__contador').filter(data_leitura__month=date.today().month,estado_factura='Aberta') clientes=Cliente.objects.filter(contador=facturas_abertas2).count() -
Reverse for ' signup' not found. ' signup' is not a valid view function or pattern name
I newbie to Django and I do not know how to fix this problem. I have watched many utube videos to fix this issue, but I found not a single solution. Urls.py for project: amazonbackend from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include(('Homepage.urls', 'Homepage'))), path('blog/', include(('blog.urls', 'blog'))), ] urls.py for first app "Homepage" from django.urls import path from Homepage import views urlpatterns = [ path('',views.HomePage,name='Home'), path('signup/',views.SignupPage,name='signup'), path('login/',views.LoginPage,name='login'), path('logout/',views.LogoutPage,name='logout'), ] urls.py for second app "blog" from django.urls import path from blog import views urlpatterns = [ path('',views.BlogHomePage,name='bloghome'), path('createposts/',views.CreatePosts,name='createposts'), path('myposts/',views.MyPosts,name='myposts'), path('comments/', views.PostsComments, name= "comments") ] navbar.html is a template in first app "Homepage" {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Amazon.com Spend less & Smile More</title> <link rel="icon" href="AMZN-e9f942e4.png" /> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/> <script src="https://kit.fontawesome.com/5ac1140461.js" crossorigin="anonymous" ></script> </head> <body> <header> <nav class="nav-bar" id="Navigation"> <div class="nav-box1 box"></div> <div class="nav-box2 box"> <div class="box2-left"> <i class="fa-solid fa-location-dot fa-xl" style="color: #ffffff"></i> </div> <div class="box2-right"> <p class="first-box2">Deliver to</p> <p class="second-box2">india</p> </div> </div> <div class="nav-box3"> <select name="" id="" class="nav-select"> <option value="">All</option> </select> <input type="search" placeholder="Search Amazon" class="nav-input"> <div class="box3-icon"> <i class="fa-solid fa-magnifying-glass fa-xl" style="color: #000000;"></i> </div> … -
How can I schedule a periodic task once in every 3 days in django celery crontab?
Need to schedule a task every 3 days celery scheduler in django. I have found the scheduling of different cases such as to schedule a task on minutely, hourly, daily, on-weekdays basis, but I could not find my requirement in the documentation of celery. Does anyone know about this? -
Run server is VScode for python/django ecommerce a "type error" pops up?
So basically I'm trying to relearn python with this course where you make a ecommerce website using Django/Python. After adding in a Views and Urls.py the next step is to run is to hope that are three urls store,cart,checkout pop up, however in the conf.py this error pops up line 65, in _path raise TypeError( TypeError: kwargs argument must be a dict, but got str. This is the line they are talking about if kwargs is not None and not isinstance(kwargs, dict): raise TypeError( f"kwargs argument must be a dict, but got {kwargs.__class__.__name__}." ) i would love to know what is throwing it i tried deleting the line but that didnt work i can provide the urls and view file one of them has to be causing it i think, any help would be greatly apprecited. Im expecting to run the server on port 8000 and be able to check if the three urls are working and will bring me up a html page, however i cant run this server due to this error, i didnt create the conf.py file so im a bit confused. -
Showing invalid python identifier
For my url path it is showing the following error. URL route 'quizzes/<int:quiz_id/question/<int:question_id>' uses parameter name 'quiz_id/question/<int:question_id' which isn't a valid Python identifier. I tried doing this in my urls.py path('quizzes/<int:quiz_id>/question/<int:question_id>',user_views.quizquestions,name='quizquestions')