Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can we send notification from specific app while working with FCM notification in django?
I'm developing a website where I have 3 fcm apps. so that i have 3 credentials file of different projects. Now i have initialize three of them. But the problem is. I am unable to configure how to send notification from desire app. as you see below. this is the list of app that i initialize. {'[DEFAULT]': <firebase_admin.App object at 0x7fa5e2ce2350>, 'meidan_userpanel': <firebase_admin.App object at 0x7fa5e2ce05b0>,'meidan_merchant': <firebase_admin.App object at 0x7fa5e3uc05b1>} here is my code. def mobile_push_notes(notification=None,registration_tokens=None,file_name=None): print("file_name == ",file_name) if not file_name: return if not registration_tokens: return if isinstance(registration_tokens, str): registration_tokens=[registration_tokens] try: if not firebase_admin._apps: cred = credentials.Certificate(f'{file_name}.json') if not initializers[file_name] : initializers[file_name] = firebase_admin.initialize_app(cred) except Exception as e: print("Mobile push file not found! or ",str(e)) return None print("initializers ============================",firebase_admin._apps) message_body = remove_html(notification["message"]) if not registration_tokens: return None try: data = notification["data"] except: data="{}" message = messaging.MulticastMessage( data={ 'id':str(notification["id"]), "sender":str(notification["sender"]), "message":str(notification["message"]), "title":str(notification["title"]), "is_merchant_side":str(notification["is_merchant_side"]), "is_userpanel_side":str(notification["is_userpanel_side"]), "category":str(notification["category"]), "resolution_reply":str(notification["resolution_reply"]), "create_time":str(notification["create_time"]), "is_remove":str(notification["is_remove"]), "data":data }, notification=messaging.Notification( title=notification["title"], body=str(message_body) ), android=messaging.AndroidConfig( ttl=datetime.timedelta(days=7), # autoCancel=False, priority='normal', notification=messaging.AndroidNotification( icon='icon.jpg', color='#f45342', ), ), apns=messaging.APNSConfig( payload=messaging.APNSPayload( aps=messaging.Aps(), ), ), tokens=registration_tokens, ) response = messaging.send_multicast(message) here i want to specify my app where i want to send notification. response = messaging.send_multicast(message) -
can i add a static folder wtih files in the static folder and load files
I want to store a admin folder with different static files in static folder in a django project. Basically, i want to load my user part fronted with some of static files and want to load my admin panel with other diffrent static files. how can i do that? i add a folder named admin which contains admins static files. here the snippet how can i load user static files and admins static files from admin folder? -
How to correctly implement password reset in django
am getting the following error when i try to to make migrations for my app Traceback (most recent call last): File "/home/edward/Desktop/Lynia-remittance-platform-/remittance_platform/manage.py", line 22, in <module> main() File "/home/edward/Desktop/Lynia-remittance-platform-/remittance_platform/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/management/base.py", line 453, in execute self.check() File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: ^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/urls/resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ^^^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/urls/resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", … -
DJANGO MODEL FORM INITIAL VALUE
Please I need help with setting initial value for my model form. from django import forms from multipage_form.forms import MultipageForm, ChildForm import calculation from .models import VinanPetLtd class ReportForm(MultipageForm): model = VinanPetLtd starting_form = "Stage1Form" class Stage1Form(ChildForm): display_name = "Transaction History" required_fields = ["entry_Date", "branch", "product"] next_form_class = "Stage2Form" class Meta: fields = ["entry_Date", "branch", "product"] widgets = { 'entry_Date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Stage2Form(ChildForm): display_name = "Tank History" required_fields = "__all__" next_form_class = "Stage3Form" class Meta: fields = [ "tank_1_Opening", "tank_1_Closing", .... ] widgets = { 'tank_1_Difference': calculation.FormulaInput('tank_1_Opening-tank_1_Closing'), 'tank_1a_Difference': calculation.FormulaInput('tank_1a_Opening-tank_1a_Closing'), 'tank_1b_Difference': calculation.FormulaInput('tank_1b_Opening-tank_1b_Closing'), ...] viwes.py from django.urls import reverse_lazy from django.views.generic import TemplateView from multipage_form.views import MultipageFormView from .forms import JobApplicationForm class JobApplicationView(MultipageFormView): template_name = 'mpf/form_page.html' form_class = JobApplicationForm success_url = reverse_lazy("mpf:thank_you") class JobApplicationThankYouView(TemplateView): template_name = 'mpf/thank_you.html' The fields are 12 and all 12 fields are not applicable to users. I want users to only fill fields applicable to them and submit with other fields as 0 initial value. I was wondering if overwriting the init function of would solve the problem. -
Fail to serialize body, when trying to send a post request with kotlin ktor to django rest API
I'm getting the following error, when I try to make a post request to my django rest API with ktor Error: Fail to serialize body. Content has type: class com.example.watchwithmemobile.domain.dto.user.UserPostRequest (Kotlin reflection is not available), but OutgoingContent expected. If you expect serialized body, please check that you have installed the corresponding feature(like Json) and set Content-Type header. I'm trying to get the username, email, password, password_check from a composable textField in kotlin, then within ktor to send an HTTP post request to my django REST API. However, I get the errors listed above. I'm catching the exception in the PostServiceImplementation as custom exception, I also have the 4xx exceptions catcher. I'm currently using Ktor 1.6.3, I do not want to migrate to version 2.x.x. The create user view in django accepts: username = request.data.get('username') email = request.data.get('email') password = request.data.get('password') password_check = request.data.get('password_check') and it is accessed by http://127....../user/register its response is a {'Actuvation': 'Account created'} in kotlin, the Response/Request look as follows: data class UserPostResponse ( val activation: String ) data class UserPostRequest( val username: String, val email: String, val password: String, val password_check: String ) and the post service implementation: override suspend fun createUser(postRequest: UserPostRequest): UserPostResponse? { return … -
How do I check the count of different requests?
I'm working on a small project, and I want to write a function that will count the number of requests. If this is the first request to this url, then the cookie value is false, and if this request is greater than 1, then the value is true, but I ran into a problem. My function is not reset after changing the url; how can I fix it? My code: def request_counter(request, request_number=[0]): request_number[0]+=1 return request_number[0] def set_cookie(url: str) -> str: try: session = requests.Session() cookie = requests.cookies.create_cookie(name='unique', value=url, expires=None, domain=url) session.cookies.set_cookie(cookie) except Exception as e: return HttpResponse(e.args) return session.cookies.get_dict() def get_full_url(url: str, unique: bool) -> str: try: link = Links.objects.get(short_url__exact=url) if not link.is_active: raise KeyError('Ссылка больше недоступна!') except Links.DoesNotExist: raise KeyError('Попробуйте другую ссылку. Этой нет в базе данных!') if not unique: link.unique_requests_count +=1 link.requests_count +=1 link.save() else: link.requests_count +=1 link.save() return link.full_url def redirection(request, short_url): try: if request_counter(request) == 1: full_link = get_full_url(short_url, False) else: full_link = get_full_url(short_url, set_cookie(short_url)) return redirect(full_link) except Exception as e: return HttpResponse(e.args) -
User Authentication using Angular and Django Mat-error from response is not being Displayed
I’m working on Signup page and I want to handle 'if username already Exists' I have tried to console.log the Error I want to display and it’s been logged on the Console but not appearing on the Mat-error Label. This is my HTML code: <mat-form-field class="example-full-width" appearance="outline"> <mat-label>Username</mat-label> <input matInput formControlName="username" required /> <mat-error *ngIf="registrationForm.get('username')!.hasError('required')" > Username is <strong>required.</strong> </mat-error> <mat-error *ngIf=" registrationForm.get('username')!.hasError('pattern') && !registrationForm.get('username')!.hasError('required') " > Username should start with <strong>a letter or underscore.</strong> </mat-error> <mat-error *ngIf=" (registrationForm.get('username')!.hasError('minlength') || registrationForm.get('username')!.hasError('maxlength')) && !registrationForm.get('username')!.hasError('required') " > Username should be <strong>between 2 and 12 characters.</strong> </mat-error> <mat-error *ngIf="usernameTakenError"> {{ usernameTakenError }} </mat-error> </mat-form-field> and That’s my Form Submit Method. submitForm(): void { if (this.registrationForm.valid) { this.http.post('http://localhost:8000/api/register', this.registrationForm.getRawValue()) .subscribe( () => { this.router.navigate(['login']); }, (errorResponse) => { if (errorResponse.status === 400) { const errors = errorResponse.error; console.log(errors); if (errors.email && errors.email.length > 0) { this.emailTakenError = errors.email[0]; console.log(this.emailTakenError); } else { this.emailTakenError = null; } if (errors.username && errors.username.length > 0) { this.usernameTakenError = errors.username[0]; console.log(this.usernameTakenError); } else { this.usernameTakenError = null; } } else { // Handle other types of errors (e.g., server errors) here. } } ); } } How can I handle it and make it display the Error? By … -
Django access local storage
I am using jwt tokens for authentication, react for frontend and django for backend. I have two models User and Post. When a new post is made I want to associate it with the user who made it. I use axios to make a post where I send a request in a django serializer. class PostSerializer(serializers.ModelSerializer): class Meta: model = Post depth = 1 fields = '__all__' def create(self, validated_data): print(self.context['request'].auth) return Post.objects.create(user=self.context['request'].user) The problem is that the current user is AnonymousUser even if the token exists. So I thought to access the authToken from localStorage and add it by the token. Should I store authTokens in cookies and access them by there or is there another way? Is it even good to store them in cookies. Edit: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } -
Chrome GUI not showing in IIS windows server
I have a Django web scrapping project that is using Selenium and Chromedriver. Everything works fine and I tested multiple times on the local host . The problem is when I run that through my IIS server in a Windows operating system , its working in the task manager but not showing GUI. I also tested that code on that windows server using : python manage.py runserver And that was showing chrome GUI in that server local host also . So the only problem is when I run it through the IIS . How to solve this problem? Is that about security permissions? -
server error (500) after deploying to heroku - but only one page
I have recently deployed a project onto heroku using AWS for media and elephantsql. Things seem to be working okay however there is only one page that returns a server 500 error. Does anyone have any idea of where I can start to investigate? I've tried moving the checkout page. here is the page code i am trying to access {% extends "base.html" %} {% load static %} {% load bag_tools %} {% block extra_css %} <link rel="stylesheet" href="{% static 'checkout/css/checkout.css' %}"> {% endblock %} {% block page_header %} <div class="container header-container"> <div class="row"> <div class="col"></div> </div> </div> {% endblock %} {% block content %} <div class="overlay"></div> <div class="container"> <div class="row"> <div class="col"> <hr> <h2 class="logo-font mb-4">Checkout</h2> <hr> </div> </div> <div class="row"> <div class="col-12 col-lg-6 order-lg-last mb-5"> <p class="text-muted">Order Summary ({{ product_count }})</p> <div class="row"> <div class="col-7 offset-2"> <p class="mb-1 mt-0 small text-muted">Item</p> </div> <div class="col-3 text-right"> <p class="mb-1 mt-0 small text-muted">Subtotal</p> </div> </div> {% for item in bag_items %} <div class="row"> <div class="col-2 mb-1"> <a href="{% url 'product_detail' item.product.id %}"> {% if item.product.image %} <img class="w-100" src="{{ item.product.image.url }}" alt="{{ product.name }}"> {% else %} <img class="w-100" src="{{ MEDIA_URL }}noimage.png" alt="{{ product.name }}"> {% endif %} </a> </div> <div … -
when i whant to use views.py i give 'QuerySet' object has no attribute error
i want to open course detail with next and previouse course but my try doesnt workes and i give 404 error and when i delete try and except i give 'QuerySet' object has no attribute error and says error is from counted_viewsenter image description here views.py: ``` def course_detail(request,id): try: course = Courses.objects.get(id=id) id_list = [] course = Courses.objects.filter(status = True) for cr in course : id_list.append(cr.id) if id_list[0] == id: next_course = Courses.objects.get(id=id_list[1]) previous_course =None elif id_list[-1] == id: next_course = None previous_course = Courses.objects.get(id=id_list[-2]) else: next_course = Courses.objects.get(id=id_list[id_list.index(id)+1]) previous_course = Courses.objects.get(id=id_list[id_list.index(id)-1]) course.counted_views += 1 course.save() context = { 'course': course, 'next_course': next_course, 'previous_course': previous_course, } return render(request,"courses/course-details.html",context=context) except: return render(request,'courses/404.html') ``` urls.py: ``` from django.urls import path from .views import * app_name = 'course' urlpatterns = [ path('',Maincourse,name='courses'), path('category/<str:cat>',Maincourse,name='course_cat'), path('teacher/<str:teacher>',Maincourse,name='course_teacher'), path('search/',Maincourse,name='course_search'), path('course_detail/<int:id>',course_detail,name='course_detail'), ]``` models.py: ```class Courses(models.Model): title = models.CharField(max_length=40) content = models.TextField(max_length=1000) teacher = models.ForeignKey(Trainer,on_delete=models.CASCADE) price = models.IntegerField(default=0) image = models.ImageField(upload_to='courses',default='default.jpg') category = models.ManyToManyField(Category) counted_views = models.IntegerField(default=0) counted_likes = models.IntegerField(default=0) status = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add = True) updated_date = models.DateTimeField(auto_now = True) available_seats = models.IntegerField(default = 0) schedule = models.DateTimeField(default=datetime.datetime.now()) ``` enter image description here -
How to combine multiple external REST API services in the same network using Django
I have a central Django REST API and want to serve multiple different machine learning models which I package as individual Flask REST apps. In order to provide a unified REST interface I would like to use the Django REST server as relay / proxy to the individual Flask services. All services are currently built and deployed using docker swarm/compose. What I currently can do is build for each individual Flask app the URL outlets in urls.py and then write code for each GET/POST method in Django to call the Flask outlet. However, I was wondering if in Django I could simply redirect all REST calls requesting: http://localhost/api/v1/model1 To the Flask app providing model1 and the Flask app then response for example to a request of http://localhost/api/v1/model1/submitData without needing Django to explicitly define http://localhost/api/v1/model1/submitData in urls.py. Alternatively I was thinking using Nginx to redirect all calls to http://localhost/api/v1/model1 to the Flask app instead of Django which is the default for http://localhost in my case. I hope the question is clear enough. Bottom line is that I am looking for the most convenient way to have a single REST interface but some REST services should run on individual docker images as … -
django-parler show fields only in one language on the django admin panel
[enter image description here](https://i.stack.imgur.com/aXTm0.png) I used django-parler to translate models. In some models field only show in Persian tab and don't show other language tab. Django language settings: LANGUAGES = [ ("de", "German"), ("fa", "Persian"), ("ru", "Russian"), ("tr","Turkish"), ("ar", "Arabic") ] LANGUAGE_CODE = 'de' Parler Settings: PARLER_DEFAULT_LANGUAGE_CODE = 'de' PARLER_LANGUAGES = { config('SITE_ID', cast=int): ( {'code': 'de', }, {'code': 'fa', }, {'code': 'ru'}, {'code': 'tr'}, {'code': 'ar'} ), 'default': { # defaults to PARLER_DEFAULT_LANGUAGE_CODE 'fallbacks': ['de'], # the default; let .active_translations() return fallbacks too. 'hide_untranslated': False, } } models.py: class Sliders(TranslatableModel): PRIMARY = 'PR' SECONDARY = 'SE' POSTION_IN_INDEX_CHOICES = [ (PRIMARY,_('erster Platz')), (SECONDARY,_('zweiter Platz')), ] translations = TranslatedFields( title = models.CharField(_('Titel'), max_length=50), image = FileBrowseField(_('Bild'), max_length=200, directory="first-page- sliders/images", extensions=[".jpg",".png",'jpeg']), link = models.URLField(_('Adresse'), max_length=200,default=None,null=True,blank=True), button_caption = models.CharField(_('Schaltflächentext'),max_length=10), ordering = models.SmallIntegerField('Bestellung'), postion = models.CharField(_('Position'),choices=POSTION_IN_INDEX_CHOICES,max_length=2,default=PRIMARY), created = models.DateTimeField(_('Erstellungsdatum'), auto_now=True, auto_now_add=False), updated = models.DateTimeField(_('Aktualisierungsdatum'), auto_now=False, auto_now_add=True), service = models.ForeignKey("service.Service", verbose_name=_("service"), on_delete=models.CASCADE,default=None, null=True,blank=True) ) class Meta: verbose_name = _('Schieberegler') verbose_name_plural = _('Schieberegler') def __str__(self): try: return self.title except TranslationDoesNotExist: return '' admins.py: @admin.register(Sliders) class SlidersAdmin(TranslatableAdmin): model = Sliders -
Django QuerySet Object Has No Attribute
I'm trying to add a new action to my OrderAdmin class called "order_shipped", whereby it'll send an email to the customer informing them that their order has been shipped. class OrderAdmin(admin.ModelAdmin): actions = ['order_shipped'] def order_shipped(self, request, obj): customer_email = obj.customer.email if request.method == 'POST': send_mail( 'Order Shipped', 'Your order has been shipped. Please expect it within the next 3-5 days. Thank you for your business.', EMAIL_HOST_USER, [customer_email], fail_silently=False ) return HttpResponseRedirect('/admin/store/order') order_shipped.short_description = 'Send Order Shipped Email' The problem that I'm having is that I keep getting this error: 'QuerySet' object has no attribute 'customer'. obj <QuerySet [<Order: 19>]> request <WSGIRequest: POST '/admin/store/order/'> self <OrderAdmin: model=Order site=AdminSite(name='admin')> If I add a new column called "order_shipped_btn" to the list_display using the code below, it shows the correct email for each customer. def order_shipped_btn(self, obj): return format_html('<a href="mailto:{}">SEND</a>', obj.customer.email) What I'm super confused about is why does it work for the later, but not the former? What am I doing wrong with the former? -
OTP verification failed pyotp
I am working on a django rest framework project, everything is working file but i encounter 1 problem class OTP: @staticmethod def generate_otp(): base32secret3232 = pyotp.random_base32() otp = pyotp.TOTP(base32secret3232, interval=300, digits=6, ) time_otp = otp.now() return time_otp, base32secret3232 @staticmethod def verify_otp(user, otp): return pyotp.TOTP(user.get("otp_secret"), interval=300, digits=6).verify(otp) Here OTP for user is generated successfully and i saved otp and secret in that user record and i send the user a email containing that otp for account verification. When user send the otp then for the first time it shows invalid OTP, then on subsequent changes it verify the user.I want to solve that issue First I check that whether I am entering the correct otp or not and otp,secret saved in database correctly or not. And these are working correctly. I want this issue to be resolved. -
No List matches the given query
I want to be able to add a comment on the product page, but after clicking on the comment button, it gives this error. What is the problem? I tried this code before, it worked perfectly, but now it gives an error. views.py ``` `def item_detail(request, item_bid_id): get_item = get_object_or_404(List, pk=item_bid_id) get_item_2 = get_item.first_bid filter_item = Bidmodel.objects.filter(listb_id = item_bid_id) comment = Comments.objects.filter(listc_id = item_bid_id) context = { 'item' : get_item, 'now_bid': auxiliary(get_item_2, filter_item), 'comments' : comment, } return render(request, 'auctions/item_detail.html', context ) # comment @login_required(login_url="login") def comments(request): comment = request.GET["comment"] username = request.user.username list_id = request.POST.get("listid", False) newcomment = Comments(user = username, comment = comment, listc_id = list_id) newcomment.save() return item_detail(request, list_id)` ``` item_detail.html: ``` `{% extends "auctions/layout.html" %} {% block body %} {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif %} <img src= {{ item.image.url }} alt = "{{item.title}}"><br> <a><a>Product:</a>{{ item.title }}</a><br> <a><a>Category: </a>{{ item.category }}</a><br> <a><a>Desc: </a>{{ item.description }}</a><br> <a><a>Status: </a>{{ item.status }}</a><br> <a><a>Frist Bid: </a> {{ item.first_bid }} $ </a><br> <div><a><a>Current Bid: </a> {{ now_bid }} $ </div> <div><a><a>Listed By: </a> {{ item.user }}</div> <h3 id="h3">Comments</h3> <div> <ul> {% for comment in comments %} <li><a><a>{{ comment.user }} … -
NameError: name 'django' is not defined [closed]
I am not able to run django. I have set the path too. But still I am getting error while running django. Please help! I have tried to run django. I have installed django using pip and also have set the path. I am expecting some solution to this problem so that I can run django on my system successfully. -
Django DRF with django-tenants Unit Test Issue
Description: I am working on a Django project using Django Rest Framework (DRF) and django-tenants for multi-tenancy. In my unit tests, I'm encountering an error that I need help resolving. I'm using django-tenants for multi-tenancy. The error suggests a 404 status code instead of the expected 201 Created status when creating a restaurant. I've verified my URL configuration, view names, and tenant setup, but the issue persists. Request: I'm looking for guidance on how to resolve this error and successfully create a restaurant in my unit test using django-tenants with DRF. Any insights or suggestions would be greatly appreciated. Thank you! Issue: When running a unit test to create a restaurant using the TenantTestCase, I am getting the following error: Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_create_valid_restaurant (django_apis.restaurants.tests.RestaurantCreateTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\OK\BackendProjects\apis\django_apis\restaurants\tests.py", line 55, in test_create_valid_restaurant self.assertEqual(response.status_code, status.HTTP_201_CREATED) AssertionError: 404 != 201 ---------------------------------------------------------------------- Ran 1 test in 4.596s FAILED (failures=1) Destroying test database for alias 'default'...``` **Code**: Here's the relevant code for the unit test: class RestaurantCreateTest(TenantTestCase): tenant = None # Define a class attribute to store the tenant instance @classmethod def setup_tenant(cls, tenant): # Create … -
Django : 405 Method Not Allowed
This is the Api class UnAssignEmployeeToOrderItemTaskViewSet( ResponseViewMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet, ): queryset = Order.objects.all() serializer_class = AddOrderItemSerializer def update(self, request, *args, **kwargs): try: order = Order.objects.get(id=kwargs['order_id']) order_item = OrderItem.objects.get(id=kwargs['order_item_id'], order=order) item_task = OrderItemTaskEmployee.objects.get(id=kwargs['task_id'], item=order_item) d = UnAssignEmployeeToOrderItemTaskViewSetSerializer(instance=item_task) item_task.assignee = None item_task.assigned_at = None item_task.save() serializer = OrderItemsListSerializer(order_item) return self.jp_response(s_code="HTTP_200_OK", data=serializer.data) except Exception as e: print(e) return self.jp_error_response( "HTTP_500_INTERNAL_SERVER_ERROR", "EXCEPTION", str(e) ) url router.register(r'(?P<order_id>.+)/items/(?P<order_item_id>.+)/task/(?P<task_id>.+)/unassign', UnAssignEmployeeToOrderItemTaskViewSet, 'unassign-order-items-task') But api call returns an error I spent a lot of time trying to fix this error. Please give me a solution to overcome this problem -
Why isn't it showing Id? It shows Game Object(none) instead of id
so i'm making a site that takes id for different pages for the path 'games/(id)'. when i make an object in the database table 'games', and pass it to html with context, django knows it exists and doesnt give error on the page. but when i write in the html to show {{game}} it shows Game Object(none) instead of Game Object('insert id here'). and when i do {{game.name}} it shows nothing. heres the code in 'views.py': def game(request, pk): game = Games.objects.get(id=pk) context = {'Game':Games} return render(request, 'games/games.html', context) i tried different way to do this, but nothing. still shows none. i've tried different ways with the model, but still nothing. -
I want the articles of my academic site created using django to be indexed in Google Scholar
I want the articles of my academic site created using django to be indexed in Google Scholar. Do you have a special python library for this or a way you recommend? I've tried using the fiduswriter library but I'm having trouble getting it to work and I can't find the information I need. -
psycopg2.errors.UndefinedColumn: column "source_id_id" of relation "service_approval_domains" does not exist
I have created model in django for my database. After trying to add data to table I got this error: ` lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column "source_id_id" of relation "service_approval_domains" does not exist LINE 1: ...domains" ("domain", "created_at", "retrieved_at", "source_id... ^ I am not really sure where is the problem since I have checked everything and did not find any declaration of source_id_id column. Here is my model: class ServiceApprovalDomains(models.Model): id = models.BigAutoField(primary_key=True) domain = models.TextField(unique=True ,null=False) created_at = models.DateTimeField(auto_now_add=True) retrieved_at = models.DateTimeField(auto_now=True) source_id = models.ForeignKey( ServiceApprovalDomainSources, on_delete=models.CASCADE ) class Meta: managed = False db_table = '"privacy"."service_approval_domains"' And I used manual migration so here is my SQL file: CREATE TABLE "privacy"."service_approval_domains"( "id" BIGSERIAL PRIMARY KEY, "domain" TEXT UNIQUE NOT NULL, "created_at" timestamp with time zone not null default current_timestamp, "retrieved_at" timestamp with time zone default current_timestamp, "source_id" bigserial not null references service_approval_domain_sources("id") on delete cascade ); And this is the function I am using to add data to database: def add_domains(data: list[AddServiceApprovalDomains]): for domain in data: source = ServiceApprovalDomainSources.objects.get_or_create(name=domain.source.name) try: ServiceApprovalDomains.objects.create(domain=domain.domain, source_id=source[0]) except IntegrityError: pass return True -
How to use different tables for authentication in django?
I am from Laravel background and new to django. My concern is how can I use two different tables for authentication in django. For example, admins table for admin authentication and users table for user authentication. Both tables will have column email, password. In laravel, we can use auth guard for this scenario. I want to know how can I implement this in django. I know we can use groups with auth_user table. But I would like to use different tables for user and admin. I have not tried anything yet about this. I am looking for business logic for this implementation in django. Also any code reference will be great help to me. -
Django tried using these urls... empty path didnt match any of these
Not sure why can't django find the empty path, I included the app path to the project's urls, I added path "" to the app's urls.py. so what's wrong here Here is the code for my app views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello world!") urls.py from django.urls import path from . import views urlpatterns = [ path("",views.index,name="index") ] the project's url.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('pricelist/',include("pricelist.urls")) ] -
Handling the case where the user closes the browser or stops the process in the middle of the OAuth flow Google API in Python
I am integrating Google Drive API in my Django project. My code is working perfectly but when I try to abort the authentication by either closing the browser without authenticating myself by logging into it or any sort of aborting results in freezing the whole app. Here is the code, flow = InstalledAppFlow.from_client_secrets_file(settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, self.SCOPES,redirect_uri='show_courses') creds = flow.run_local_server(port=0) with open(token_path, 'w') as token_file: token_file.write(creds.to_json()) everything get stuck on this line if user close the browser without authentication creds = flow.run_local_server(port=0) Please let me know how to handle this situation. I am struggling for this from last few months.