Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Busy GPIOs Raspberry Pi 5
When trying to interface with the GPIO of the RPi 5 using gpiozero, I am running into an error stating that the GPIO is busy. The context is that I am running this code in a Celery task in Django. The issue is similar to this, but the fix provided did not work in this context. -
Triggering Python Function on Django + React
I am attempting to send data from my React frontend to a Django backend and trigger a function. I'm developing a Django REST API using Django Rest Framework, and I've set up a view in the calculator app to handle POST requests. The objective of the calculator view is simply concatenate text from frontend: #app/calculator/views.py from django.http import JsonResponse def concat_text(request): if request.method == 'POST': received_text = request.POST.get('text', '') result = received_text + ' =)' print(result) return JsonResponse({'result': result}) else: return JsonResponse({'error': 'Only POST requests are allowed'}) However, when I make a request from my React frontend, I'm receiving a 403 error (Forbidden). I am sending the text value via frontend by: const handleButtonClick = async (e) => { e.preventDefault(); try { const response = await fetch(`${URL}/calculator/calculator/`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ text }), }); The URL is simply the "http://localhost:8000". I have also defined the calculator urls: #app/calculator/urls.py from django.urls import path from .views import concat_text urlpatterns = [ path('calculator/', concat_text), ] My app urls: #app/urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView from core import views as core_views โฆ -
Unable to Store data in order placed table and deleting data from cart table after completion of payment
4 i am using razorpay payment gateway web integration for my learning eccomerce project everyhing work fine payment can be done all i want is to store my cart data in OrderPlaced table and delete the cart data from Carts table and redirect the page on home after payment done in my order model using test mode. but in this code something is wrong after payment completion Nothing happen no changes nor in Carts table neither in OrderPlaced table. This is my Checkout View for the payment initiation class checkout(View): def get(self, request): user = request.user add = Customer.objects.filter(user=user) cart_items = Cart.objects.filter(user=user) famount = 0 for p in cart_items: value = p.quantity*p.product.discounted_price famount = famount+value totalamount = famount+30 razoramount = int(totalamount * 100) client = razorpay.Client( auth=(settings.RAZOR_KEY_ID, settings.RAZOR_KEY_SECRET)) data = {"amount": razoramount, "currency": "INR", "receipt": "order_rcptid_12"} payment_response = client.order.create(data=data) print(payment_response) order_id = payment_response['id'] order_status = payment_response['status'] if order_status == 'created': payment = Payment( user=user, amount=totalamount, razorpay_order_id=order_id, razorpay_payment_status=order_status ) payment.save() return render(request, 'app/checkout.html', locals()) And this is my paymentDone View here i try to store all cart items in OrderPlace table and delete item from the Cart table.. def payment_done(request): order_id = request.GET.get('order_id') payment_id = request.GET.get('payment_id') cust_id = request.GET.get('cust_id') user = โฆ -
Handling Multiple dependent drop down lists in a form using Django and jquery
I want to create a form with 4 drop down list in which two of them are dependent on the other two, example i have a country and city drop list in which the city is dependent on the country i.e. when a country is selected only cities in that country will show in the city drop down and its working perfectly but my department and unit are not working as expected. I wand same for my department and units, if a department is selected only units in that department should show. I want to implement this in one form. <form method="post" enctype="multipart/form-data" autocomplete='off' class="mt-3" novalidate id="personForm" data-cities-url="{% url 'ajax_load_cities' %}" data-units-url="{% url 'ajax_load_units' %}"> <div class="row"> <div class="col-3">{{ form.country|as_crispy_field}}</div> <div class="col-3">{{ form.city|as_crispy_field}}</div> <div class="col-3">{{ form.department|as_crispy_field}}</div> <div class="col-3">{{ form.unit|as_crispy_field}}</div> </div> <script> $("#id_country").change(function () { const url = $("#personForm").attr("data-cities-url"); const countryId = $(this).val(); $.ajax({ url: url, data: { 'country_id': countryId }, success: function (data) { console.log(data); $("#id_city").html(data); }); } }); }); $("#id_department").change(function () { const url = $("#personForm").attr("data-units-url"); const departmentId = $(this).val(); $.ajax({ url: url, data: { 'department_id': departmentId }, success: function (data) { console.log(data); $("#id_unit").html(data); } }); }); </script> -
htmx: hx-target-error fails when hx-target defined (django python)
I am using the htmx extension "response-targets" via "hx-ext" in a python django project. The Problem "hx-target-error" will not work when "hx-target" is also defined, but works when it is the only target. Environment htmx 1.9.10, response-targets 1.9.10, python 3.12, django 5.0.1 Example html: <div hx-ext="response-targets"> <button hx-get={% ur "appname:endpoint" %} hx-target-error="#id-fail" hx-target="#id-success" type="submit" > Press Me! </button> </div> hx-target Have tried with various other type of targets such as "next td", "next span", etc. All of them produce value "request.htmx.target" values in the endpoint defined in views.py. hx-target-error Have also tried various alternatives supported in response-targets such as "hx-target-*", "hx-target-404", etc with no change in results. I verified that "response-targets" is installed correctly and being used correctly because when "hx-target" is removed from the "button", then "hx-target-error" works. Error generation in views.ph @login_required def endpoint(request) return HttpResponseNotFound("Not found 404") Logs Bad Request: /testbed/endpoint/ 127.0.0.1 - [27/Feb/2024] "GET /testbed/endpoint/ HTTP/1.1" 400 response-targets extension https://htmx.org/extensions/response-targets/ -
Could anyone tell me the step by step process to implement this project?
๐ฃ๐ฟ๐ผ๐ฏ๐น๐ฒ๐บ ๐ฆ๐๐ฎ๐๐ฒ๐บ๐ฒ๐ป๐ : Language translator tool to convert English to Hindi (official Language) which can be used by all the government organizations websites officially. ๐๐ฒ๐๐ฐ๐ฟ๐ถ๐ฝ๐๐ถ๐ผ๐ป : The objective is to develop a language translator tool specifically designed for government organizations in India. The tool should provide the capability to translate English content into Hindi, the official language of the country. This will enable government websites to cater to a wider audience, including Hindi-speaking citizens who may have difficulty understanding English. The language translator tool should possess the following key features: Translation Accuracy: The tool should offer accurate translations, maintaining the context and meaning of the original English content. It should handle various language intricacies, idiomatic expressions, and technical terms commonly used in government-related documents. User-Friendly Interface: The tool should have a simple and intuitive interface, ensuring ease of use for both website administrators and end-users. It should seamlessly integrate into government websites, allowing users to translate content with minimal effort. Website Integration: The language translator tool should be compatible with different website architectures and frameworks commonly used by government organizations. It should provide developers with an API or plugin that can be easily integrated into existing websites without significant code โฆ -
Joining Tables in Django ORM with Left Outer Join and Additional Condition
I'm trying to perform a left outer join between two models in Django using the ORM. I need to include an additional condition within the ON clause of the join to filter the results based on specific criteria. from django.db import models class Author(models.Model): id = models.BigIntField(primary_key=True) name = models.CharField(max_length=50) book_title = model.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, db_column='author') Is there a way to retrieve all the book objects along with the name of the author where the title and book_title are equal. The sql will look like: select title, author, name as author_name from book left outer join author on (book.author = author.id AND book.title = author.book_title) Since the table is very large ( 13m ) I cannot resort to raw query because I will lose the ability to use PageNumberPagination. I don't want to use extra because this may lead to problems in future. Is there any other way I can achieve the above sql using django orm?? -
Django project deployment on Vercel got me an error
I have created a simple blog application using django and postgres database. While I wants to deploy to vercel it throws a different errors like this error error How can i solve this error? build_files.sh pip install -r requirements.txt python3.10 manage.py collectstatic vercel.json { "version": 2, "builds": [ { "src": "blog/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.10" } }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } } ], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "blog/wsgi.py" } ] }``` I have build_files.sh and vercel.json. I think there is no problem. I also have requirements.txt file. Pushed to github and tried deployment but no progress at all. -
django.core.exceptions.FieldDoesNotExist: Document has no field named 'header'
So, i am trying to add parler to my models in order to translate them. models.py from django.db import models from django.utils.translation import gettext_lazy as _ from ckeditor.fields import RichTextField from parler.models import TranslatableModel, TranslatedFields from simple_history.models import HistoricalRecords class Document(TranslatableModel): class DocumentStatus(models.TextChoices): ACTIVE = 'active', 'Active' ARCHIVED = 'archived', 'Archived' translations = TranslatedFields( header=models.CharField(_("Header"),max_length = 32), body=RichTextField() ) category = models.ForeignKey(Category, on_delete = models.CASCADE) timestamp = models.DateTimeField(auto_now_add = True) status = models.CharField(max_length = 10, choices = DocumentStatus.choices, default = DocumentStatus.ACTIVE) history = HistoricalRecords() def __str__(self): return self.header so basically it says that it has no header field, but when i add it outside of the translations it says that it ALREADY HAS header field. How do i fix it? -
Some example schemas on swagger not displaying
New over here.. Has anyone encountered a problem that occurs in swagger where it shows some specific number of urls with their properties and example schemas. While for the rest it just gives the default value "string". E.g If I have a total of 70 urls for the first 30 urls it gives the accurate example schemas while for others it just gives "string" as the example schema My swagger UI The "string" Example value then shows up for all urls after the api/user/verify I have tested both drf_yasg and drf-spectacular but got the same result -
Django order by number of related objects in class Meta
In Django, i want to set the default model ordering to be by the number of related objects. In my case i would like to order the objects by the number of likes, where likes is a ManyToManyField of users that have liked the post: class Post(models.Model): likes = models.ManyToManyField(User) class Meta: ordering = [] # What can i put here? The common solution seems to be django aggregation: from django.db.models import Count top_posts = Post.objects.annotate(num_likes=Count('likes')).order_by('-num_likes') But this is called on the queryset, and doesn't seem like an option when defining the model. -
How do I resolve "Serverless Function has exceeded the unzipped maximum size of 250 MB" error on Vercel?
I have a personal project that I am building in Python using Django. When deploying it to Vercel, it worked fine until eventually the amount of libraries that I imported (included in my requirements.txt file) became too large, I assume, and now I face the "Serverless Function has exceeded the unzipped maximum size of 250 MB" error. The library that takes up the most space is Wordcloud (and botocore / boto3). Surely there must be a way around this? As far as I'm aware, paying for a higher tier of Vercel will not resolve this issue. Is there any workaround to this issue, or is the best option to just use a different service other than Vercel? This is my requirements.txt: Django==4.2.8 psycopg2-binary==2.9.8 Pillow==8.2.0 django-storages==1.14.2 boto3==1.34.4 botocore==1.34.4 Pyrebase4==4.7.1 regex==2020.11.13 python-dateutil==2.8.2 textblob==0.17.1 nltk==3.6.3 json5==0.9.14 jsonpath-ng==1.5.3 jsonpointer==2.4 jsonschema==4.19.0 jsonschema-specifications==2023.7.1 wordcloud==1.9.2 matplotlib==3.7.2 matplotlib-inline==0.1.6 Obviously when I remove the libraries from my project that takes up the most space, it does build successfully. So the problem is not with my code itself, and it does build and start up successfully when I open a local instance. I'm still relatively new with Python, so I would appreciate any help, even if it is "basic" - โฆ -
hello Iโve got big problem when I open my site Iโve got โSyntaxError at / invalid syntax (views.py, line 78)โ for review
It does not tell me which of my views has this problem. It is strange that there is no problem in http://127.0.0.1:8000/, but there is a problem in the host I bought. I have also talked to the support and they said that it is a python problem and you have to solve this problem with a python programmer here is my project, accounts and blog app views: `from django.shortcuts import render,get_object_or_404,redirect from blog.models import Post from django.utils import timezone from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger from blog.models import Comment from blog.forms import CommentForm from django.contrib import messages from django.urls import reverse from django.http import HttpResponseRedirect def blog_view(request,kwargs): posts=Post.objects.filter(status=1,published_date__lte=timezone.now()) if kwargs.get('cat_name')!=None: posts=posts.filter(category__name=kwargs['cat_name']) if kwargs.get('author_username')!=None: posts=posts.filter(author__username=kwargs['author_username']) if kwargs.get('tag_name')!=None: posts=posts.filter(tags__name__in=[kwargs['tag_name']]) posts=Paginator(posts,4) try: page_number=request.GET.get('page') posts=posts.get_page(page_number) except PageNotAnInteger: posts=posts.get_page(1) except EmptyPage : posts=posts.get_page(1) # return render(request, 'blog/post_detail.html', {'post': post}) # posts=Post.objects.filter(status=0) context={'posts':posts} return render(request,'blog/blog-home.html',context) def blog_single(request,pid): if request.method=='POST': form =CommentForm(request.POST) if form.is_valid(): form.save() messages.add_message(request,messages.SUCCESS,"your comment submited") else: messages.add_message(request,messages.ERROR,"your comment didnt submited") post = get_object_or_404(Post,pk=pid,status=1,published_date__lte=timezone.now()) post.counted_views += 1 post.save() previous_post = Post.objects.filter(id__lt=pid,status=1,published_date__lte=timezone.now()).order_by('-id').first() next_post = Post.objects.filter(id__gt=pid,status=1,published_date__lte=timezone.now()).order_by('id').first() if not post.login_require: comments=Comment.objects.filter(post=post.id,approved=True).order_by('-created_date') form=CommentForm() context={'post':post,'previous_post': previous_post,'next_post': next_post,'comments':comments,'form':form} return render(request,'blog/blog-single.html',context) else: return HttpResponseRedirect(reverse('accounts:login')) def blog_category(request,cat_name): posts=Post.objects.filter(status=1) posts=posts.filter(category__name=cat_name) context={'posts':posts} return render(request,'blog/blog-home.html',context) def blog_search(request): posts=Post.objects.filter(status=1,published_date__lte=timezone.now()) # print(request.__dict__) if request.method=='GET': # print(request.GET.get('s')) if s:=request.GET.get('s'): **that's โฆ -
How to make an ajax jquery request to get data from a Django ListView?
I have a base template in which I have a header and in that header, there are some link buttons that I would like to change the appearance of when clicked, for this it would be necessary to use ajax to avoid reloading the page. The request must be a GET to display the updated page data. That is, the ajax script must be done in my base.html at the button click event, to load the template that extends the base. Right? The view: class HomeListView(ListView): model = Cars template_name = 'cars.html' context_object_name = 'cars' def get_queryset(self): cars = super().get_queryset().order_by('model') return cars The data in the template cars.html (which extends base.html) is processed in this way: <div class="car-grid"> {% if cars %} {% for car in cars %} <div class="car-card"> <img src="{{ car.photo.url }}" alt="{{ car.model }} - {{ car.brand }}"> <h2> {{ car.brand }} {{ car.model }} </h2> <p> {{ car.factory_year }} - $ {{ car.value }} </p> </div> {% endfor %} {% else %} <p class="no-results">No results found. </p> {% endif %} </div> What is the smartest way to make this ajax request to get the updated cars context variable? Is there any way to pass it to โฆ -
How to create a Django queryset based on values of recursive ManyToManyField?
I have a dictionary app where words (Lemma) can be optionally composed of other words. In my models.py, this looks like: cf = models.CharField(max_length=200) #citation form pos = models.ForeignKey(Pos, on_delete=models.CASCADE) #part of speech components = models.ManyToManyField("self", symmetrical=False, blank=True) #component Lemma I want to return two query sets: All compound verbs: Lemma that have values in self.components and where self.pos.term="verb" All unique components of compound verbs that are nouns: Lemmas that are values of some other Lemma's self.component_set() and which themselves have self.pos.term="noun". I want to use views to pass these two lists to a template. I'm able to get queryset 1 pretty easily, but my solutions for queryset 2 are all quite convoluted. The relevant class in my views.py looks like this: model = Lemma queryset = Lemma.objects.filter( Q(pos__term="verb") & ~Q(components=None) ).order_by("cf") #queryset 1, compound verbs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) nouns = self.queryset.values_list("components") nouns = set([Lemma.objects.get(pk=l[0]) for l in nouns]) nouns= [l for l in nouns if l.pos.term == "noun"] context["nouns"] = nouns #queryset 2, nouns that are components of compound verbs return context This also leaves me with a regular list for my verbs variable rather than a proper queryset where I can use the .order_by() method โฆ -
when creating zoom i am getting invalid access token error when my keys are valid
import requests import json API_KEY = 'API KEY' API_SEC = 'SECRET KEY' zoom_api_url = 'https://api.zoom.us/v2/users/me/meetings' meeting_details = { "topic": "The title of your Zoom meeting", "type": 2, "start_time": "2024-02-27T10:00:00", "duration": "45", "timezone": "Europe/Madrid", "agenda": "Test Meeting", "settings": { "host_video": "true", "participant_video": "true", "join_before_host": "False", "mute_upon_entry": "False", "watermark": "true", "audio": "voip", "auto_recording": "cloud" } } headers = { 'Content-Type': 'application/json', } auth = (API_KEY, API_SEC) response = requests.post(zoom_api_url, headers=headers, auth=auth, data=json.dumps(meeting_details)) print(response.json()) after I am getting access token but its saying invalid access token i have added keys and allowed authentication on zoom i have tested it with postman as well as through my django app From every platform i am getting same error ** Invalid Access Token** I tried to create access with jwt.io too but still its not working if anyone can help what is wrong? -
How can I assign a url to a button that redirect users to an external website when the data is split up into two data frames?
I have function in my view that fetches data from multiple spreadsheets and normalizes said data into one single data frame via Pandas. This df1 is eventually rendered and displayed in a webapp in the form of a bootstrap table using Django. For the sake of simplicity, letโs say this table has two columns: โGamesโ and โLinkโ. โGames" shows all the soccer matches for today and โlinkโ simply has a button for each of the games. This button does nothing for now. Now, I have another function that fetches data from a different source and again, normalizes the data using Pandas creating a df2 with three columns: โGamesโ: shows some soccer matches for today (this column has some but not all the games in df1 with exactly the same format). โIdโ: a 4-digit identifier that is unique to each of the games above. โUrlโ: a url that contains the โidโ and redirects the user to an external website that provides the user with extra information about that particular match. Iโm trying to figure out a way where the users can click on the buttons available in the webapp (which are linked to the games in df1) and get redirected to โฆ -
Django display DateFormat as dd/mm/yyyy
I have a form in Django where the user needs to select the date. When the user selects the date the date is displayed in the following format mm/dd/yyyy (eg. 02/29/2024). I want the date in the form to be displayed as dd/mm/yyyy (eg. 29/02/2024 ). This is the date field in my form: date = forms.DateField( widget=forms.DateInput(format='%d/%m/%Y', attrs={'type': 'date', 'min': str(timezone.now().date()), 'max': str((timezone.now() + timedelta(days=365)).date())}), help_text='Select a date', input_formats=['%d/%m/%Y'], validators=[validate_future_date], ) I also tried: In settings.py: DATE_INPUT_FORMATS = ('%d-%m-%Y',) USE_I18N = True USE_L10N = True In the form: input_formats=settings.DATE_INPUT_FORMATS, After both of these approaches the format was still displayed as dd/mm/yyyy. -
Django View to return template with refreshed modal window
I'm using Django form in modal window where core content (in container) generated by JS. On submit django model instance saved without any issues if form.is_valid() == True a modal window closes with switching focus on current background page. However if form.is_valid() == False the modal content just opens in separate URL instead and takes all browser screen as View renders just a short code fragment in .html file. The goal is to refresh the modal window on current condition in case if form_is_valid() == False with form errors. Template "accounts/profile_settings.html" contains a form and submit button which renders inside <div class="preferences_content"> {% comment %} JS generated dynamic content depends on tab pressed. {% endcomment %} </div> My JS knowldge is very basic so I appreciate any suggestion on this topic. The View : def profile_update_view(request): """ Updates current Profile instance.""" if request.method == "POST": current_profile = request.user.profile profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=current_profile) if profile_form.is_valid(): profile_form.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', "/")) else: profile_form = ProfileUpdateForm() return render(request, "accounts/profile_settings.html", {'profile_form': profile_form}) else: profile_form = ProfileUpdateForm() return render(request, "accounts/profile_settings.html", {'profile_form': profile_form}) document.addEventListener("DOMContentLoaded", function() { var openModalLink = document.getElementById("openPreferencesModal"); var modal = document.getElementById("preferencesModal"); var span = modal.querySelector(".close"); var preferencesContent = modal.querySelector(".preferences_content"); var tabs = modal.querySelectorAll(".tab"); โฆ -
Django losing session state?
I have a VPS running apache. Apache is serving two domains, my homepage (django, django-cms, zinnia) and a prod site (django, oscar). I use falkon browser. When I change the items in site's admin (I change values in a row, it's list_editable, and then click Save), sometimes (quite often), the response returned is a redirect to login, as if the session cookie is not passed. What is interesting, if I save the POST request as curl and retry it, it succeeds. Since there are several redirects after I hit save, I've seen it failing on the first one (so the item is not saved), or the second one (the item is therefore saved, but I find myself not on the list page, but on the main admin page). How do I debug it? I suspect it may be a browser issue, I'll try mitmproxy now to see what's really hitting the network. But maybe someone has seen this behaviour before. -
Migrate project from Django 1.8 to 1.11 and TemplateDoesNotExist at /accounts/login/
i am beginner in Python and Django. I must update project from Django 1.8 to 1.11 (and in past to 2,3,4). I make update my requirements file and pip. When I write in WSL: ./.venvs/bin/python3 manage.py runserver I have error i browser: TemplateDoesNotExist at /accounts/login/ _accounts/login.html Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/ Django Version: 1.11 Exception Type: TemplateDoesNotExist Exception Value: _accounts/login.html my urls.py: from django.conf import settings from django.views.generic.base import TemplateView from django.conf.urls import include, url from django.contrib.auth.views import login from go.accounts.decorators import check_login_abuse from go.accounts.forms import AuthenticationForm, PasswordResetForm from go.insurance.views import index urlpatterns = [ url(r'^$', index), url(r'^accounts/login/$', check_login_abuse(login), {'template_name': 'accounts/login.html', 'authentication_form': AuthenticationForm}), url(r'^accounts/logout/$', logout, {'template_name': 'accounts/logout.html'}), ] How can i repair this problem? I use Python 3.8 -
Static files on EC2 instance, AWS
I recently deployed my project to an Ubuntu EC2 instance and I noticed that the static files (css) don't seem to be loading(same with the images from sqLite3-database). For my website I use django: What I'm getting: When I enter my website, my css and media doesn't load. What's more I can't access one of my slug-pages, because I always get 500 bad request: [27/Feb/2024 09:53:36] "GET /about-me/ HTTP/1.1" 500 145 [27/Feb/2024 09:53:58] "GET / HTTP/1.1" 200 12343 [27/Feb/2024 09:53:58] "GET /static/css/home.css?%201709027638 HTTP/1.1" 404 179 [27/Feb/2024 09:53:58] "GET /media/images/Crawler_Post_Picture.png HTTP/1.1" 404 179 *my setup: โโโ core โโโ db.sqlite3 โโโ home โโโ manage.py โโโ media โโโ requirements.txt โโโ static โโโ staticfiles โโโ templates โโโ venv What I've already tried: collectstatic migrate change my settings.py into: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' 5)urls.py: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) add this in my homepage.html template <head>: <link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}?{% now " U" %}" /> I'm a newbie, so thanks in advance! -
Django mocking a function in a View does not work
Ok so here is the situation. I'm using Django, DRF and for tests django.test and unitest.mock I have a View which executes a method inside a post request sending a message to Kafka (send_message_to_kafka). This method is not in a viewset and I am trying to mock it. I wrote 2 tests. to call a method wrapper_send_message_to_kafka() which calls send_message_to_kafka inside it. self.client.post("/viewset/", data=payload). Both of these tests mocks the function send_message_to_kafka bypassing the actual publish to Kafka. @mock.patch('utils.send_message_to_kafka', return_value={"success": True, "message": "Message sent to Kafka successfully!"}) But the first works as expected and the second is not mocked. View @api_view(["POST"]) def example_view(request): if request.method == "POST": ... result = send_message_to_kafka(json.dumps((message))) Tests from django.test import TestCase import unittest.mock as mock ... @mock.patch('utils.pubsub.send_message_to_kafka', return_value={"success": True, "message": "Message sent to Kafka successfully!"}) def test_send_message_to_kafka(self, send_message_mock): result = wrapper_send_message_to_kafka() self.assertTrue(result["success"]) @mock.patch('utils.send_message_to_kafka', return_value={"success": True, "message": "Message sent to Kafka successfully!"}) def test_start_run(self, send_message_mock): response = self.client.post( "/execute/", data=payload, format="json", ) -
Django Register View not Saving User Model to Database
I built a registration form + view + template, but when I try to register, the user is not being saved to the database, neither does it log me in. I expected my form to register my user and save it to the database. This is my code (Register form) from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserRegistrationForm(forms.ModelForm): email = forms.EmailField() password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email'] def check_password(self): if self.cleaned_data['password'] != self.cleaned_data['password2']: raise forms.ValidationError('Passwords do not match!') return self.cleaned_data['password2'] (Register view) def register_view(request): if request.method == 'POST': register_form = UserRegistrationForm(request.POST) if register_form.is_valid(): user = register_form.save(commit=False) user.set_password = register_form.cleaned_data['password'] # Automatically log in the user after registration username = register_form.cleaned_data['username'] password = register_form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page or home page return redirect('home1:index') # Adjust 'home' to your home page URL name else: register_form = UserRegistrationForm() return render(request, 'register.html', {'register_form': register_form}) (Register Template) <form class="form" method="post"> {% csrf_token %} <label class="label" for="email">Email:</label> <input class="input" type="text" id="email" name="email"> <label class="label" for="username">Username:</label> <input class="input" type="text" id="username" name="username"> <label class="label" for="password">Password:</label> <input โฆ -
I issue with my Django project recognizing mysqlclient module installed with xampp
I got this error on trying to install Xampp: 'Important! Because an activated User Account Control(UAC) on your system some functions of Xampp are possibly restricted. With UAC please avoid to install Xampp to C:\Program Files(missing write permissions). Or deactivate UAC with msconfig after this setup' If i go ahead and install xampp, then mysqlclient module is not seen by the project. I also get the warning that xampp doesn't have admin previledges. If I give xampp admin previledges, I see 'x' mark on my xampp interface against Apache, Mysql & Tomcat. Even installing in another directory hasn't worked either. I don't know what I am doing wrong. If i go ahead and install xampp, then mysqlclient module is not seen by the project. I also get the warning that xampp doesn't have admin previledges. If I give xampp admin previledges, I see 'x' mark on my xampp interface against Apache, Mysql & Tomcat. Even installing in another directory hasn't worked either. I don't know what I am doing wrong.