Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python - Django BASE_DIR is not populating completely
I am facing a strange issue with django BASE_DIR . My codebase base directory is apisetup. When i am using BASE_DIR for linking css and js files with the help of "static". But those are not working in production. When i see console , it is giving 404 errors for css and js files. the base directory is not reflecting completely. LAST LETTER is missing in the base path. eg : *****.com/apisetu/static/js/bootstrap.bundle.min.js , but it should be apisetup settings.py file BASE_DIR = Path(file).resolve().parent.parent In local it is working fine but creating issue in hosting server. Please help me out to understand the issue and resolution. Thanks in advance. -
Django- form submitting to the same view and not to desired view
My form stopped submitting to the desired view, and submitting to its own view instead. URLS.PY: path('validate_registration', views.validate_registration,name='validate_registration'), VIEWS.PY: def user_registration(request): print("in reg") # populate form form = register_form(request.POST) print("anonymous form") template = loader.get_template('registration.html') return HttpResponse(template.render({'form':form}, request)) def validate_registration(request): if request.POST: print("validating") #populate form form = register_form(request.POST) return render(request, 'val_reg.html', {}) TEMPLATS.HTML: <form class="text-warning text-center rounded pt-2 ps-2 pe-2" method="POST" action="{% url 'validate_registration' %}" > {% csrf_token %} {{form.as_p}} <br/> <button type="submit" class="btn btn-warning mt-5">Register</button> <br/> <br/> </form> The form was working, but after change to the views.py it stopped, which made me shorten its code to few lines only. Even the print "in reg" line doesn't work. Any help please ? -
Django, checkbox add goods to cart with size that user choose by click checkbox
Good day to all. Please don't judge strictly, I'm just learning. I started learning Django and everything seemed to be going smoothly until I ran into the problem of adding an item to the cart along with the size. There is no problem adding the product itself, but I need the user to select the size through a checkbox and after clicking on the “add to cart” button, not just a product will be added to it, but with the desired selected size. Here are the product models, sizes and carts class Product(models.Model): article = models.CharField(max_length=12,null=False,blank=False,unique=True,primary_key=True) img = models.ImageField(upload_to='products_images') price = models.DecimalField(max_digits=9,decimal_places=2) description = models.TextField(null=True,blank=True) gender = models.CharField(max_length=12,null=False,blank=False) is_child = models.BooleanField(null=False) season = models.CharField(max_length=12,null=False) color = models.CharField(max_length=24,null=False) sizes = models.ForeignKey(to='Size',on_delete=models.CASCADE,to_field='article') def __str__(self): return f"{self.article}" class Size(models.Model): article = models.CharField(max_length=12,null=False,unique=True) article_size = models.ForeignKey(to='ArticleSize',on_delete=models.CASCADE,to_field='article_size') def __str__(self): return f"{self.article}" class ArticleSize(models.Model): article_size = models.CharField(max_length=12, null=False, unique=True) size_name = models.CharField(max_length=12,null=False,blank=False) qty = models.SmallIntegerField() to_article = models.CharField(max_length=12, null=False) def __str__(self): return f"{self.article_size}" class Basket(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) product = models.ForeignKey(to=Product, on_delete=models.CASCADE,to_field='article') size = models.ForeignKey(to=ArticleSize,on_delete=models.CASCADE,to_field='article_size') qty = models.PositiveSmallIntegerField(default=0) create_time_stamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Корзина для {self.user.email} товар {self.product.article},размер {self.size.size_name}" Here is the form model: class CheckboxForm(forms.Form): checkbox_size = forms.CharField(widget=forms.CheckboxInput(attrs={ 'class':'size_checkbox', 'type':'checkbox', 'name':'size_checkbox'}),required=True) class Meta: … -
Django: Application redirects to login page again and again and not to home page in local network
I have created a Django application and hosted on local network. when I use http://localhost:8000/klo/ it redirects to the login page and after successful login, it redirects to the home page http://localhost:8000/klo/home/. Same behaviour is observed with local host IP:127/0.0.1:8000. However when I use the IP addr (172.xx.xx.xx:8000/klo) to connect to the app, login page appears but even after entering the correct credentials the redirect to home page not working but login appears again and again. But the url shown with next value (http://172.xx.xx.xx:8000/accounts/login/?next=/klo/home/) settings.py includes ALLOWED_HOSTS = ['*'] LOGIN_REDIRECT_URL = 'klo-home' project level - urls.py includes path('klo/', include('users.urls')), application name - users users application level - urls.py includes path('home/', views.klo_home, name="klo-home"), users application level - views.py @login_required(login_url="/accounts/login/") def klo_home(request): return render(request, 'registration/klo_home.html') Need to know what stops the app from redirecting to klo-home page after valid login only when using IP addr (http://<ip_addr:8000/klo/>) for accessing the app. -
Fuzzy Logic numpy in Django
I'm making website for web survey project. I have fuzzy logic python program and I want to try it to implement it to Django, but I don't know how to connect it to django. This is my model, though (Idk how to post code here) Class Survey (title) Class Question (fk Class Survey; question) Class Answer (fk Class Answer, answer) Class Fuzzy (fk Class Answer, fk User, output1, output2, output3, output4, output5, output6, output7, output8) I want to gain jawaban (answer) as the input of fuzzy logic. I've planned to having 16 inputs and 8 outputs like this : (example of one of the outputs) Input1 = Answer1 Input2 = Answer2 Outputs = Input1 and Input2 Is there anything that I have to prepare like models, views, urls, etc? I'm still beginner towards Django. Help will be appreciated, thanks :) I tried many times, though, but I don't know. I want to post code here, but it always error. -
Python: Get all data from database and write csv
I want to get all data from database and write a csv. But I can't get data by using this user.lrn (for example). But if I try to remove the lrn and just use user, I only got all lrn. I don't know how to call the other field. Below is my code for the write csv function. views.py def exportStudentList(request): user = Student.objects.all() data = [user.lrn, user.lastname] # data = [user] field = ['LRN', 'Last Name'] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Students.csv"' writer = csv.writer(response) writer.writerow(field) # Header writer.writerows(data) # Rows return response Your help is greatly appreciated! -
Problem with transferring/receiving an Excel file from the backend(django_v1.9.11) to the frontend(angularjs)
On the front end there is a table and a button to export to Excel. When you click on it, you need to send ajax to the backend, generate an Excel file and transfer it to the frontend in order to download it through the browser to disk. Backend (django v1.9.11) from openpyxl import Workbook from django.http import HttpResponse def send_xl(self, request): wb = Workbook() sheet = wb.active # this is test data. real data is hidden sheet['A1'] = 'Hello world!' sheet['B1'] = 'Excel with Django.' response = HttpResponse(content_type='application/vnd.openxmlformats- officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=my_excel_file.xlsx' wb.save(response) return response HTML element Export Frontend (angularjs) $scope.downloadExcel = function(){ $.get("", {action:"send_xl", col: $scope.col, sortDirection: $scope.sortDirection }). then(function (response){ let blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); let url = URL.createObjectURL(blob); let a = document.createElement('a'); document.body.appendChild(a); a.href = url; a.download = 'filename.xlsx'; a.click(); window.URL.revokeObjectURL(url); } I expect that when the button is clicked, the browser will download a file that can be opened through Excel. The file is downloading, but Excel gives an error: (I open it via LibreOffice) "The file 'filename.xlsx' is corrupt and therefore cannot be opened. LibreOffice can try to repair the file. The corruption could be the result of document … -
Django Djoser not working in production return 405 using react as frontend
In my application, I'm using Django as my backend and react JS for frontend. I'm using Django Djoser for my user activation and reset password. Locally, everything works fine. After creating new user, activation link will be sent to the user email http://127.0.0.1/activate/MjE1/c1vk2z-0cf8bc5d2484ddd32001844b53da1900 If i'm using my domain https://workmatch.rickykristianbutarbutar.com/activate/MjE1/c1vk2z-0cf8bc5d2484ddd32001844b53da1900 then 405 comes out after clicking this link, it will navigate to the frontend activation page, then user click "Activate" const sendActivationConfirmation = async () => { setButtonLabel("Activating ..."); try { let response = await fetch(`/auth/users/activation/`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ uid: uid, token: token }) }); if (response.ok) { setAlert({ success: "Your account has been activated. We'll redirect you to the login page in 5 seconds.", }); activationSuccess.current = true; } else if (response.status === 403) { let data = await response.json(); setAlert({ error: data.error }); } else if (response.status === 400) { setAlert({ error: "Bad Request, user may have been accidentally deleted." }); } } catch (error) { if (error.name === "SyntaxError" && error.message.includes("Unexpected end of JSON input")) { console.error("Truncated data: Not all of the JSON data was received"); } else { console.error(error); } } finally { setButtonLabel("Activate"); } }; this code will be … -
Jazzmin sidebar and navbar not hidden on custom login page in Django admin
I'm working on a Django project where I'm using the Jazzmin package to customize the Django admin interface. I've created a custom login page (custom_login.html) for the admin interface, and I want to hide the sidebar and navbar on this page. However, even after ensuring that the {% block nav-global %} and {% block nav-sidebar %} blocks are empty in my custom login template, and that the Jazzmin CSS and JavaScript files are not included on the login page, the sidebar and navbar are still showing up. I've tried several approaches, including selectively including the Jazzmin files, overriding the base template to conditionally include the Jazzmin files, and removing custom CSS and JavaScript from my custom login template. However, none of these solutions have worked so far. I've also inspected the HTML of the custom login page using my browser's developer tools and checked for JavaScript errors in the console, but I couldn't find any obvious issues. Here are the relevant parts of my code: custom_login.html {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %} {{ block.super }} <link rel="stylesheet" href="{% static "admin/css/login.css" %}"> <style> .login #id_tenant { height: 2.5rem !important; padding: 8px; width: 100%; } … -
Django Cloudinary Form Field Display Image
I would like to change the way a Cloudinary field is displayed. By defauly, a link is supplied for the user to see the current image. I would like to display the image directly on the page. Can anyone advise as to how to approach this? Model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) image = CloudinaryField('image', null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now_add=True) def __str__(self): field_values = [] for field in self._meta.get_fields(): field_values.append(str(getattr(self, field.name, ''))) return ' '.join(field_values) class Meta: ordering = ['image'] Form: class UserProfileForm(ModelForm): class Meta: model = UserProfile fields = ['image'] View: def update_profile(request): try: profile = UserProfile.objects.get(user=request.user) except UserProfile.DoesNotExist: profile = None form = UserProfileForm(instance=profile) if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES, instance=profile) if form.is_valid(): form.save() return redirect('.') context = {'form': form} return render(request, 'profile.html', context) HTML: <form class="m-1 p-2" method="POST" enctype="multipart/form-data" action=''> {% csrf_token %} <div class="row mb-5"> <div class="col"> {{ form.image }} </div> </div> <input id="submit-button" class="btn btn-primary" type="submit" value="&nbsp;Save&nbsp;"> </form> The current rendering is: I would like something like this: Thanks in advance. Steve -
Add Image Gallery as TabularInline in another TabularInline model
I want to Create Product model which has some Inline query like in each product you can add different attribute like color, size, brand,... and each variation could has specefic image gallery I use two model gallery as TabularInline of Variation and Variation as TabularInline of Product But it didn't show me tha image gallery as tabularinline in variation, Here is my code: productapp.models: class Product(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=250, unique=True) description = RichTextUploadingField(null=True) short_description = RichTextUploadingField(null=True) price = models.IntegerField() sku = models.CharField(max_length=200, null=True, blank=True) dimenstions = models.CharField(max_length=200, null=True, blank=True) category = models.ManyToManyField(Category, related_name='category') tag = models.ManyToManyField(Tags, related_name='tag') attribute = models.ManyToManyField(Attribute, related_name='attribute') image = models.ImageField(upload_to='shop/image', null=True, blank=True) def __str__(self): return self.title class Variant(models.Model): title = models.CharField(max_length=200) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) variations = models.ForeignKey(Variations, on_delete=models.SET_NULL, null=True, blank=True) regular_price = models.IntegerField() sale_price = models.IntegerField(null=True, blank=True) sku = models.CharField(max_length=200, null=True, blank=True) stock_quantity = models.IntegerField(default=0) image_id = models.IntegerField(blank=True, null=True, default=0) def __str__(self): return self.title class Gallery(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='shop/gallery', null=True, blank=True) product = models.ForeignKey(Variant, null=True, on_delete=models.SET_NULL, related_name='gallery') def __str__(self): return self.title Admin.py: class GalleriesInline(admin.TabularInline): model = Gallery extra = 1 readonly_fields = ('pk',) formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'30'})}, } class VariantInline(admin.TabularInline): model = Variant inlines = [GalleriesInline] … -
Show the child Query in admin-panel of Django
I have different variation in attribute model by tabularinline: class Attribute(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(null=True, blank=True) def __str__(self): return self.title class Variations(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(null=True, blank=True) image = models.ImageField(upload_to='variations', null=True, blank=True) attribute = models.ForeignKey(Attribute, null=True, on_delete=models.SET_NULL, related_name='variation') def __str__(self): return self.title now I made a relationship Product model with Attribute: class Product(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=250, unique=True) description = RichTextUploadingField(null=True) short_description = RichTextUploadingField(null=True) regular_price = models.IntegerField() sale_price = models.IntegerField(null=True, blank=True) sku = models.CharField(max_length=200, null=True, blank=True) dimenstions = models.CharField(max_length=200, null=True, blank=True) stock_quantity = models.IntegerField(default=0) category = models.ManyToManyField(Category, related_name='category') tag = models.ManyToManyField(Tags, related_name='tag') attributes = models.ManyToManyField(Attribute, through='ProductVariation', related_name='products') image = models.ImageField(upload_to='shop/image', null=True, blank=True) # tax_class = pass # shiping_class = pass # related_product = pass # variation = pass def __str__(self): return self.title def thumbnail_tag(self): return format_html( "<img width=100 height=75 style='border-radius: 5px;' src='{}'>".format(self.image.url)) thumbnail_tag.short_description = "Thumbnail" class ProductVariation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) def __str__(self): return f"{self.product} - {self.attribute_value}" Now I want when users choose attribute 1 to show them in another field all the variations of that attribute and do this for different attributes with different variations. For example when I want to … -
Django REST: Get pk of model object in create context
I am in the middle of a project where I am creating a scheduling system for courses. Courses may have a number of sessions. I would like, upon course creation, to create a number of blank sessions (to be scheduled later) equal to a variable in the course request ("class_count"). Each Session has FKs to the user profile and course. The logic I have is something like this: serializer.save(instructor=self.request.user) for sess in range(int(request.POST.get('class_count'))): Session.objects.create(user=self.request.user.profile, session_active=True, course=request) Session.save() However, when I do this, I get this error: ValueError: Cannot assign "<rest_framework.request.Request: POST '/create/'>": "Session.course" must be a "MyCourse" instance. How would I access the instance of the MyCourse model just created? -
How to filter queryset by decimal stored in JSON?
I store some decimal's string representation in JSONField and want to filter by it. Here's the model: class Asset: cached_data = JSONField() Content of JSONFields: { "price": "123.456" } I tried a lot of ways to filter queryset by this value. The last one was Asset.objects.annotate('price_as_decimal': Cast('cached_data__price', output_field=DecimalField())).filter(price_as_decimal__gt=100) but it gives the error: django.db.utils.DataError: invalid input syntax for type integer: "none" while I'm sure there's a value for this key in the field -
django unable to implement decorator_from_middleware functionality
I am working on a project where I am trying to write a middleware which when called will verify token from a third party service and check roles stored in that token. I am able to write and use middleware successfully, but I need to implement it for selected views only, for which I am unable to convert the middleware to decorator using decorator_from_middleware to use only where it is required. This is the middleware class (with token verification part removed). class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. print(f"inside the custom middleware") response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response This is how I am trying to use it in a view file. from django.utils.decorators import decorator_from_middleware from users.middleware import SimpleMiddleware simple_decorator = decorator_from_middleware(SimpleMiddleware) class UserPoolInfo(APIView): @simple_decorator def get(self, request): user_manager_object = UserManager() user_pool_info = user_manager_object.get_user_pool_info() response_data = { "status":"Success", "statusCode": status.HTTP_200_OK, "message":"fetched user pool information", "data": user_pool_info } return Response(response_data, status.HTTP_200_OK) we are using Django 5.0 with Django Rest Framework. I have tried following answer from this … -
Validation of min and max doesn't work for custom widgets of django
I use a custom widget to show addon through the input-group of Bootstrap. It is shown but min-value and max-value operation don't work correctly and their message doesn't display. class PrependWidget(Widget): def __init__(self, base_widget, data, *args, **kwargs): u"""Initialise widget and get base instance""" super(PrependWidget, self).__init__(*args, **kwargs) self.base_widget = base_widget(*args, **kwargs) self.data = data def render(self, name, value, attrs=None, renderer=None): u"""Render base widget and add bootstrap spans""" field = self.base_widget.render(name, value, attrs) return mark_safe(( u'<div class="input-group mb-3">' u' <div class="input-group-prepend">' u' <span class="input-group-text" id="addon_{name}" value="{value}">%(data)s</span>' u' </div>' u'<input type="text" class="form-control" id="id_{name}" name="{name}" {attrs} ' u'aria-describedby="addon_{name}"> ' u'</div>'.format(name=name, value=value, attrs=attrs or '') ) % {'field': field, 'data': self.data}) hard = forms.IntegerField(min_value=0, max_value=20, required=False, widget=PrependWidget(base_widget=forms.NumberInput, data='GB')) -
how to send mail using godaddy cpanel mail in django
I created an email on godaddy c-panel hosting . I have written some codes in Django to send mail using this mail and in recipients mail I have 3 mails and one is c-panel email. It is sending mail to only c-panel mail not to others two. Also I have configured DNS and forwarder but that's also not working. -
Can't quite figure out this DRF endpoint
I am working on this endpoint to store an email. I send a POST to /emails with { "email": "user101c@email.com" } and get an error IntegrityError at /emails (1048, "Column 'user_id' cannot be null"). Clearly, this is a database level error. The user_id field shouldn't be set by the user. I'm not sure how to proceed. models.py class EmailAddress(ExportModelOperationsMixin('email_address'), models.Model): user = models.ForeignKey(User, related_name='emails', on_delete=models.CASCADE) email = models.EmailField(max_length=255) verify_key = models.CharField(max_length=255, null=True, blank=True) verified = models.BooleanField(default=False) created = models.DateTimeField(auto_now=True) verification_sent = models.DateTimeField(null=True, blank=True) reset_key = models.CharField(default=None, null=True, max_length=255, blank=True) reset_sent = models.DateTimeField(null=True, blank=True) class Meta: verbose_name = _("email") verbose_name_plural = _("emails") unique_together = [("user", "email")] ordering = ['-created'] def __str__(self): return self.email def save(self, *args, **kwargs): self.verify_key = get_random_string(length=32) if not self.id: # if new verify_email_signal.send(sender=self.__class__, email=self.email, key=self.verify_key) self.verification_sent = timezone.now() super(EmailAddress, self).save(*args, **kwargs) serializers.py class EmailAddressSerializer(serializers.ModelSerializer): class Meta: model = account_models.EmailAddress fields = ['user', 'email', 'verified', 'created', 'verification_sent', 'reset_sent'] read_only_fields = ['id', 'user'] views.py class EmailAddressViewSet(ModelViewSet): permission_classes = (permissions.IsAuthenticated,) serializer_class = serializers.EmailAddressSerializer def get_queryset(self): return account_models.EmailAddress.objects.filter(user=self.request.user) urls.py email_list = views.EmailAddressViewSet.as_view({ 'get': 'list', 'post': 'create' }) email_detail = views.EmailAddressViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) urlpatterns = [ path('emails/', email_list, name='email_list'), path('emails/<int:pk>/', email_detail, name='email_detail'), ] -
Stripe Checkout Session Django Subscription
I'm not a developer or software engineer. We've put together almost the entirety of a web app with the help of chatgpt. It's worked great up to this point... I would like to do the following: Implement payments on my website through Stripe Use the Stripe Checkout Session Use the ui_mode = embedded option. I would like an embedded form not a redirect away from our website to Stripe's Must use python django framework The Stripe documentation has a guide that I'm sure is great for a flask app but I am really struggling to adapt it to django. https://stripe.com/docs/checkout/embedded/quickstart?lang=python Would any be able to help translate the flask documentation to a django framework? -
Django not sending messages despite correct implementation
Specs: Django version 4.2.5, Python 3.11, Visual Studio Code. I use (well, attempting to use) SendGrid to send a web form & I'm currently in development (DEBUG = True). Having followed the QuickStart tutorial supplied by SendGrid, I can confirm that the SG has been installed correctly, including the .env which houses the SENDGRID_API_KEY I have also followed the following documentation to the letter: Sendgrid Django documentation I am completely stumped as to how the developers of SendGrid can justify pushing this content into the public domain because I have not seen one iota of evidence that the API is fully operable. Also, I am following this tutorial: Codemy tutorial This is my code: {% if message_name %} <center> <h1>Thanks {{message_name}}!</h1> <p>We will get back to you shortly.</p> {% else % } <section class="vp"> <div class="parent parent--headline"> <form method="POST" action="{% url 'careers' %}"> {% csrf_token %} <input required type="text" name="message-name" placeholder="First name"/><br/><br/> <input required type="email" name="message-email" placeholder="Email"/><br/><br/> <textarea required spellcheck="true" name="message" placeholder="Insert your message"></textarea> <input type="submit" value="Send feedback" class="btn btn--pink"/> </form> </div> </section> </center> {% endif %} In the settings.py, I have the following: SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY') EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey' … -
Django CREATING databases dynamically at runtime( NOT ROUTING the requests to right DB)
how does one go about creating a new database for each tenant at run time dynamically. All the examples are hard coded into settingsfile. But when a new tenant,t1, registers, I would like to create a new database for t1. and when a t2 connects I would like to be able to create that t2_db at runtime which out running any migrations or server restart. So let say we have a default db where we do our migrations,(empty) we just copy that for t1 and t2. Or is there a way to run migrations with out restarting the server. Or do people just restart the server(crazy right) If not I am thinking docker. Thanks -
Cookie set not working with django and next js app hosted on azure and confiured to use custom domain
I have two applications. A next.js frontend app and a Django backend app. The backend uses Django's session storage and I'm trying to set cookies in the browser. This was working on localhost. I'm using Azure to host my application. I bought my own domain called something.xyz. I put my frontend as an A record with host as @ in my DNS configuration and my backend as a CNAME with host as ser. There are also TXT records for azure config. When I go to ser.something.xyz I can access my backend. I can also access my frontend when I go to something.xyz. I have set both SESSION_COOKIE_SAMESITE and CSRF_COOKIE_SAMESITE to None. I have set both SESSION_COOKIE_DOMAIN and CSRF_COOKIE_DOMAIN to either something.xyz, .something.xyz, or ser.something.xyz. I also tried putting https:// in front (that's probably wrong but I'm desperate) I know this question has been asked before, but I just can't seem to get it to work. I have changed my settings several times This is the message I'm getting from the network tab: csrftoken=xxxxxxxxxxxxxxxx; Domain=['something.xyz']; expires=Mon, 03 Feb 2025 22:41:48 GMT; Max-Age=31449600; Path=/; SameSite=None; Secure this attempt to set a cookie via a Set-cookie header was blocked because its domain attribute … -
"How do I add styles to html_body in Django with win32?"
I am trying to send emails through Django using the win32 library, but the HTML styles are not being applied. The styles in the head work sporadically, and the styles in the body also work sporadically ` pythoncom.CoInitialize() dynamic_link='prueba' try: # Obtén todos los ingenieros con sus nombres concatenados outlook = win32.Dispatch('Outlook.Application') mail = outlook.CreateItem(0) # Configurar el remitente mail.SentOnBehalfOfName = 'example@outlook.com' mail.To = adminEmail mail.Subject = 'NUEVA SOLICITUD DE PRUEBAS DE LABORATORIO' html_body = f""" <html> <head> <style> body {{ font-family: Arial, sans-serif; padding: 20px; }} h1, p {{ color: #333; }} .background-red {{ background-color: red; }} #button {{ display: inline-block; padding: 10px 20px; background-color: #4CAF50; color: #fff; text-decoration: none; border-radius: 5px; }} </style> </head> <body class="background-red"> <h1>Solicitud de pruebas de laboratorio</h1> <p>Nueva solicitud pruebas de laboratorio del usuario {FullName}</p> <div style="width: 130px; height:130px; background-color:white;"> <p>El usuario {FullName} ha creado una nueva solicitud de pruebas de laboratorio para el cliente {customer} con una fecha requerida para el {require_date}</p> </div> <a href="{dynamic_link}" id="button">Ir a la página</a> </body> </html> """ mail.HTMLBody = html_body mail.Send() return Response({"message": "Correo enviado correctamente"}, status=status.HTTP_200_OK) except Exception as e: print(f"Error: {e}") finally: # Liberar recursos pythoncom.CoUninitialize()` I need help please, i'am new in django -
Python Django in Docker - Input device error
I've tried to deploy my Django App on DigitalOcean App Platform. Due to using PyAudio I had to use Dockerfile, because python3-pyaudio requires "apt-get". I've created Dockerfile and successfull installed PyAudio. Unfortunetly I've got an error "OSError: No Default Input Device Available". [speech-to-text] [2024-02-05 22:42:35] /usr/local/lib/python3.10/site-packages/pydub/utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work [speech-to-text] [2024-02-05 22:42:35] warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning) [speech-to-text] [2024-02-05 22:42:35] Not Found: / [speech-to-text] [2024-02-05 22:42:40] ALSA lib confmisc.c:855:(parse_card) cannot find card '0' [speech-to-text] [2024-02-05 22:42:40] ALSA lib conf.c:5180:(_snd_config_evaluate) function snd_func_card_inum returned error: No such file or directory [speech-to-text] [2024-02-05 22:42:40] ALSA lib confmisc.c:422:(snd_func_concat) error evaluating strings [speech-to-text] [2024-02-05 22:42:40] ALSA lib conf.c:5180:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory [speech-to-text] [2024-02-05 22:42:40] ALSA lib confmisc.c:1334:(snd_func_refer) error evaluating name [speech-to-text] [2024-02-05 22:42:40] ALSA lib conf.c:5180:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory [speech-to-text] [2024-02-05 22:42:40] ALSA lib conf.c:5703:(snd_config_expand) Evaluate error: No such file or directory [speech-to-text] [2024-02-05 22:42:40] ALSA lib pcm.c:2666:(snd_pcm_open_noupdate) Unknown PCM sysdefault [speech-to-text] [2024-02-05 22:42:40] ALSA lib confmisc.c:855:(parse_card) cannot find card '0' [speech-to-text] [2024-02-05 22:42:40] ALSA lib conf.c:5180:(_snd_config_evaluate) function snd_func_card_inum returned error: No such … -
How to test a function of view in Django
I am learning basics of Django following official tutorial and adding some new features to my application. So I added a view that can nullify all votes of particular question def nullask(request, question_id): question=get_object_or_404(Question, pk = question_id) if request.method == "GET": return render(request, "polls/nullifyask.html", {"question":question}) else: for i in question.choice_set.all(): i.votes = 0 i.save() return HttpResponseRedirect(reverse("polls:index")) So it works fine, but I wanted to practice in writing tests and wanted to write a test that test that votes are really nullified. Here it is class NullingViewTest(TestCase): def test_nulling(self): q=create_question(text="Future", days=-1) choice=q.choice_set.create(choice_text="1", votes=10) response=self.client.post(reverse('polls:nullask', args=(q.id,))) self.assertEqual(choice.votes, 0) It does't work(votes are not changing from 10 to 0 and AssertionError: 10 != 0 appears. I understand why this happens but cannot make it work like I want. What should I do here is nullify ask.html: <!doctype html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Nullyfying of {{question_id}}</title> </head> <body> <form method="post"> {% csrf_token %} <legend><h1>Do you want to nullify votes of question {{question.text}}</h1></legend> <input type="submit" name="Yes" value="Yes!"> </form> </body> </html> Here are models: class Question(models.Model): text=models.CharField(max_length=200) productiondate=models.DateTimeField("date published") def was_published_recently(self): return self.productiondate >= timezone.now() - datetime.timedelta(days=1) and self.productiondate<timezone.now() def __str__(self): return self.text class Meta: permissions=(("can_nullify","User can nullify votes" ),) class Choice(models.Model): question = …