Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change CSV value into a DateTime object
I am trying to upload data from a CSV into a Django model. On the CSV there is a date field and the values look like this: 2020-11-11 14:06:25+00:00 Which brings up this error: '“Deadline” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.' I am saving the value into a DateTimeField. How would I convert the CSV data into a DateTime object? I appreciate your help on this. Thanks! -
Google Cloud Run correctly running continuous deployment to github, but not updating when deployed
I've set up a Google Cloud Run with continuous deployment to a github, and it redeploys every time there's a push to the main (what I what), but when I go to check the site, it hasn't updated the HTML I've been testing with. I've tested it on my local machine, and it's updating the code when I run the Django server, so I'm guessing it's something with my cloudbuild.yml? There was another post I tried to mimic, but it didn't take. Any advice would be very helpful! Thank you! cloudbuild.yml: steps: # Build the container image - name: 'gcr.io/cloud-builders/docker' args: ['build', '-t', 'gcr.io/${PROJECT_ID}/exeplore:$SHORT_SHA', './ExePlore'] # Push the image to Container Registry - name: 'gcr.io/cloud-builders/docker' args: ['push', 'gcr.io/${PROJECT_ID}/exeplore'] # Deploy image to Cloud Run - name: 'gcr.io/cloud-builders/gcloud' args: - 'run' - 'deploy' - 'exeplore' - '--image' - 'gcr.io/${PROJECT_ID}/exeplore' - '--region' - 'europe-west2' - '--platform' - 'managed' # Deploy container image to Cloud Run - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk' entrypoint: gcloud args: ['run', 'deploy', 'exeplore', '--image', 'gcr.io/${PROJECT_ID}/exeplore', '--region', 'europe-west2', '--platform', 'managed'] images: - gcr.io/${PROJECT_ID}/exeplore Here are the variables for GCR -
How to map out via Django Management command [duplicate]
The is active flag and blacklist flag have the same intention although both are available. Since with is active filtering is possible and it is seen in the overview all blacklist should be mapped to is active. def handle(self, *args, **options): roses.objects.filter(active=False).update(blacklist=True) -
Annotate dict data from related field Django
I have a model MyModel that contains a JSONField named calculo in MySQL and I want to annotate the value of premio to perform aggregated sum. How can I make this work? class MyModel(models.Model): ... calculo = JSONField(blank=True, null=True) ... I have tried this but got an empty dict. qs = MyModel.annotate(value=F('calculo__premio')) Fairfax field: '{"sc_ha": 2.77, "premio": 27735.84, "status": "1"}' -
Page not re-rendering when receiving post request from jquery to django backend
Jquery on HTML page in script tags $("input[type='radio']").click(function(){ var radioValue = $("input[name='filter']:checked").val(); if(radioValue){ var CSRFtoken = $('input[name=csrfmiddlewaretoken]').val(); jQuery.post("/", {filter:radioValue, csrfmiddlewaretoken: CSRFtoken }); } }); }); django view (python) def homepage(request): context = {} if request.POST: filter = request.POST.get('filter') filteredarticles = list(Article.objects.all().filter(is_draft = False, topic =filter)) context['features'] = filteredarticles print(filteredarticles) return render(request, 'homepage.html', context=context) else: allarticles = list(Article.objects.all().filter(is_draft=False)) FEATUREDQUANTITY = 7 featuredArticles = [] for i in range(FEATUREDQUANTITY): k = random.randint(0, (len(allarticles)-1)) featuredArticles.append(allarticles[k]) allarticles.pop(k) context['features'] = featuredArticles print('seen') return render(request, 'homepage.html', context=context) The thought process is as follows: Using radio buttons in HTML. Jquery listening for click actions. Sends post request to view function containing the selected radio {name:value} and the CSRF_token information. The view receives the post request and processes it through the If condition and re-renders the page with the appropriate data. Everything is working, the post request is received, the data inside filteredarticles is changing, but the website itself isn't re rendering with the new context values I am passing in. Any help would be appreicated edit: Is it because I'm not passing a success callback function in my jquery.post? -
Django - Restrict API access by geolocation
We have model and view: from django.db import models from rest_framework.decorators import api_view from rest_framework.response import Response class Store(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=100) @api_view(['get']) def get_checklist_by_store_id(request, store_id): # request.user should has access to this view only when request.user inside the store with id=store_id return Response() User can get checklist by store_id. And we need to restrict access to view get_checklist_by_store_id and allow user to have access only when user is inside the store with id=store_id. First what I thought about was to add to model Store field with geo coordinates. Then on frontend implement geolocation API. When user is trying to get access to the view to ask him turn on geolocation and at last send request with his geo coordinates. And in the view compare user's geo coordinates and store geo coordinates (with some distance error). Maybe there is another approach to solve this kind of problem? -
FullCalendar not displaying correctly in django
current Fullcalendar display Hey so I'm working with FullCalendar and I'm trying to display the calendar but it ends up displaying the way it is in the picture attached to this post. I'm not sure why it displays like this and I followed the instructions on their scripts tag page but no luck. Does anyone know why and how to fix this issue? Here's the code I'm using for this {% extends 'apisapp/base.html' %} {% load static %} {% block content %} {% block extra_css %} <style> .btn-success { background-color:#7AAF4F; } .btn { font-weight: bold; } </style> </link rel="stylesheet" href="{% static 'fullcalendar/lib/main.css' %}"> {% endblock extra_css%} <body style="background-color: #2B2B2B; color: white;"> <div class="card" style="background-color: #2B2B2B; color: white;"> <div id="calendar" class="container" ></div> </div> </body> {% block extrajs %} <script src="{% static 'fullcalendar/lib/main.js' %}"></script> <script> document.addEventListener('DOMContentLoaded', function() { var calendarUI = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarUI, { }); calendar.render(); }); </script> {% endblock extrajs%} {% endblock %} -
4 by 4 square grid for 52 random images using Django
I want to create a 4 by 4 grid of about 52 images that can randomly appear in each square of the grid. I am trying to use Django since its what im into right, but if Javascript is better than I can use it. Any suggestions to get started on this project is what i am looking for -
show products in a specific category in html
i have a products and categories Model already implemented in models.py in a django application. In an html template i want to show products of a single category that i want to define in html, like category == example or something similar. class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, related_name='products', on_delete=models.CASCADE) title = models.CharField(max_length=255) this is the models.py snippet, below is the html snippet that i am trying to use {% for product in category.products.all %} I am already using this snippet to show products on category page, the category is going to be defined using the category url, but in this case i want to do that. -
send mail contact form with django
I don't understand, when I do the message test nothing happens, and in the terminal we put dis page not found help me to solve the problem DEFAULT_FORM_EMAIL="ouesergegedeon225@gmail.com" EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'ouesergegedeon225@gmail.com' EMAIL_HOST_PASSWORD = '@@@@@@@@@@' EMAIL_USE_TLS = 'True' EMAIL_USE_SSL = 'False' def send_mail(request): if request.method=="POST": name = request.POST.get['name'] subject = request.POST.get['subject'] email = request.POST.get['email_address'] message = request.POST.get['message'] send_mail( name, subject, email, message, 'ouesergegedeon225@mail.com', ['gedeonachat@mail.com'], fail_silently=False, ) message.info (request, 'Votre message a été envoyé') return render(request, 'contact.html') path('send_mail/', views.send_mail, name="send_mail"), <div class="col-lg-5 offset-lg-6 col-md-12"> <div class="section-title v2"> <h2>Écrivez-nous par formulaire</h2> </div> <form action="send_mail" method="post" id="contact_form"> {% csrf_token %} <div class="form-control-wrap"> <div id="message" class="alert alert-danger alert-dismissible fade"></div> <div class="form-group"> <input type="text" class="form-control" id="fname" placeholder="Nom et prénom" name="fname"> </div> <div class="form-group"> <input type="text" class="form-control" id="subject" placeholder="Le sujet" name="subject"> </div> <div class="form-group"> <input type="email" class="form-control" id="email_address" placeholder="E-mail" name="email"> </div> <div class="form-group"> <textarea class="form-control" rows="8" name="message" id="message" placeholder="message"></textarea> </div> <div class="form-group"> <button type="submit" class="btn v7" >Envoyer le message</button> </div> </div> </form> </div> I don't understand, when I do the message test nothing happens, and in the terminal we put dis page not found help me to solve the problem -
Django not responding back to react
I am making a request from React frontend to a view in Django (rest framework). The view in Django will make a request to another server (Google-Ads API), the request works fine and I get the data perfectly. The post-processing of that data also works fine but Django gets stuck after that means It will not run return Response(data). Django view sample code def get(self,request): data = google_api_request(credentials) data = preprocess(data) print("end") # code stops here return Response(data,status) # this will not be executed React sample code: axiosInstance.get("url").then( (result) => { if (result.status == 200) { console.log("sucess") } } ).catch(error => { throw error; }) } When I paste the "url" directly in my browser it works and returns the Response, but only when I run it from react it does not respond. When I commented google_api_request() code for debugging It returns the Response. Note: There is no errors message in the console or Django and my CORS setting is correct as other function works fine. -
Ordering collisions when cloning Django Model
I am running into issues whenever I clone a users grocery list with a m2m relationship on groceryitems. def make_clone_for_update(self, user): clone = super().make_clone_for_update(user) for b in self.grocerylist_set.all(): b.pk = None b.user_id = clone.uuid b.order = self.get_max_default("order") b.save() def get_max_default(self, field): try: max = ( self.__class__.objects.all().aggregate(Max(field))[f"{field}__max"] + 1 ) except TypeError: max = 1 return max After a clone if I check the database I will have something that will have all of the food items cloned but sometimes will have duplicate order values. IE we will order values that look like Apple 11 Pear 11 Orange 12 Granola 12 Yogurt 13 In django admin I use adminsortable2 which has a strong suggestion to not use a unique constraint on the ordering field. I have also tried not using the get max default but instead just cloning the exact order field but that results in the same duplicating issue (But a lower order number). Is there any way to guarantee these ordering fields to be unique? -
Creating a second List in the Admin class , Django
'class BookingAdmin(admin.ModelAdmin): list_diplay=('id','title', 'roomsize', 'hostel', 'features','price','status' list_editable=('status',) the above code doesnt run, however without the second list(list_editable) as shwon below the code runs perfectly 'class BookingAdmin(admin.ModelAdmin): list_diplay=('id','title', 'roomsize', 'hostel', 'features','price','status')' the error <class 'main.admin.BookingAdmin'>: (admin.E121) The value of 'list_editable[0]' refers to 'status', which is not a field of 'main.Booking'. -
How to increase quantity of item in cart in Django?
My add-to-cart views. Hello everyone, I'm completely new to Django and I tried to create a simple eCommerce web application. I tried to create a logic that increases the item that is available in the cart, but I don't why the item in the cart is not working. Maybe there is an error in logic can someone help. def add_cart(request, product_id): current_user = request.user #Getting the product id product = Product.objects.get(id=product_id) #User is authenticated or not if current_user.is_authenticated: if request.method == 'POST': for item in request.POST: key = item value = request.POST[key] is_cart_item_exists = CartItem.objects.filter(product=product, user=current_user).exists() if is_cart_item_exists: cart_item = CartItem.objects.filter(product=product, user=current_user) id = [] for item in cart_item: id.append(item.id) else: cart_item = CartItem.objects.create( product = product, quantity = 1, user = current_user, ) cart_item.save() return redirect('cart') #User is not authenticated else: if request.method == 'POST': for item in request.POST: key = item value = request.POST[key] try: #Get the cart using cart id cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() is_cart_item_exists = CartItem.objects.filter(product=product, cart=cart).exists() if is_cart_item_exists: cart_item = CartItem.objects.filter(product=product, cart=cart) id = [] for item in cart_item: id.append(item.id) else: item = CartItem.objects.create(product=product, quantity=1, cart=cart) #create new cart item item.save() else: cart_item = CartItem.objects.create( product … -
Multi Level Template Inheritance using Jinja
I am working on a multilevel template inheritance using jinja. datasource.html and event1.html is rendering correctly but event2.html and event3.html are not rendering. when I click on Event 2 and Event 3 links, I am having the page of event1.html. Nothing happens when I click Event 2 and Event 3 links. Is it due to any mistake i done in inheriting or something else. Is there any way to solve this layout.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> <header> </header> <section> {% block content %} {% endblock %} </body> </html> datasource.html {% extends 'layout.html' %} {% block content %} <li> <a href="#tab1">Event 1</a></li> <li> <a href="#tab2">Event 2</a></li> <li> <a href="#tab3">Event 3</a></li> <div> {% block content1 %} {% endblock %} </div> {% endblock %} event1.html {% extends 'datasource.html' %} {% block content1 %} <div> <p> this is event 1 </p> </div> {% endblock %} event2.html {% extends 'datasource.html' %} {% block content1 %} <div> <p> this is event 2 </p> </div> {% endblock %} event3.html {% extends 'datasource.html' %} {% block content1 %} <div> <p> this is event 3 </p> </div> {% endblock %} -
Reverse for 'author' with arguments '('',)' not found. 1 pattern(s) tried: ['blogapp/author/(?P<pk>[^/]+)/\\Z'
while running http://127.0.0.1:8000/blogapp/blog/ , in django 4.0, i got error reverse for... not found and this error occurs when i add (post.author.id) in href which is in template mentioned line 15 if require more information please comment below views.py def authorview(request,pk): user=User.objects.get(id=pk) return render(request,'blogapp/authorview.html',{'user':user}) In template C:\Users\SHAFQUET NAGHMI\blog\blogapp\templates\blogapp\blogretrieve.html, error at line 15 templates {% load static %} {% block content %} <h1>Blog </h1> <link rel="stylesheet" href="{% static 'blogapp/blogretrieve.css' %}"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> {% for post in q %} <div class="jumbotron jumbotron-fluid"> <div class="container"> <h2 class="display-1">{{post.title}} </h2><br> <p class="display-2">{{post.Newpost}}</p> <a href="{% url 'blogapp:author' post.author.id %}">{{post.author}}</a <!-- line 15 --> <small class="display-3">{{post.created_date}}</small> </div> </div> {% endfor %} app_name='blogapp' urlpatterns=[ path('',views.home,name='home'), path('createblog/',views.blogview,name='blogview'), path('blog/',views.blogretrieve,name='blog'), path('signup/',views.signupview,name='signup'), path('login/',views.loginview,name='login'), path('logout/',views.logoutview,name='logout'), path('author/<str:pk>/',views.authorview,name='author'), ] -
saving day wise logs in Azure App Service for Django Application
Below is the logging format I have for a DRF application in azure app service. I tried using Timed Rotating File handler but I was not able to save the logs with that option. Also, when ever the app service restarts, the previous logs are getting erased. Is there a way to maintain day wise logs in azure app service. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'filters':{ 'error_mails': { '()': 'django.utils.log.CallbackFilter', 'callback':'app.log.CustomExceptionReporter' }, 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, }, 'handlers': { 'logfile': { 'level':'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': f'{BASE_DIR}/app_log.log', 'maxBytes': 9000000, 'backupCount': 10, 'formatter': 'standard' }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html' :True, 'reporter_class':'app.log.CustomExceptionReporter', # 'filters':['require_debug_false',] }, }, 'loggers': { 'django': { 'handlers':['logfile','mail_admins'], 'propagate': True, 'level':'ERROR', }, 'django.request':{ 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'app': { 'handlers': ['logfile','console'], 'level': 'INFO', 'propogate': True, } } } -
Search Django Model Returns All Instead Of Filter
I am trying to search my Django model but, cannot return the filter result. I am getting all items in the model. class singleview(generics.ListCreateAPIView): authentication_classes = [] permission_classes = [] search_field = ['name'] filter_backends= (filters.SearchFilter,) queryset = Product.objects.all() serializer_class =ProductSerializer The Url is: url(r'^api/dualsearch/$', views.singleview.as_view()), When searching: http://localhost:8000/api/dualsearch/?name=n I return all items. Could you please help return the results in the filter? -
How to get a Model variable name from another model in django
I have two models in django model Model.py class RequestTemplate(models.Model): name = models.CharField(max_length=50) Author=models.CharField(max_length=50) defaultvalues=models.CharField(max_length=50) class Request(models.Model): name = ?? # Author = ?? starttime = models.DateTimeField(default=timezone.now) endtime = models.DateTimeField(default=None) so the idea is that i want to create Requesttemplate which i can use in the future to create a Request object that will take the name and the Author variables from the template. I tried to use Forgienkey to the name variable, but in case i updated the template in the future i dont want to get my Request updated. Conclusion: I want to connect the Request with the template for one time (to get the variables names) and then keep it independent from the template. Any ideas? -
gunicorn shows connection error [Errno 111]
Hi im building a Django app with docker, gunicorn and nginx and having serious issues calling a post request from the django view. my login function - with schema_context(restaurant_schema): app = Application.objects.first() #return Response({'domain': domain_name, 'client_id': app.client_id, 'client_secret': app.client_secret,}) domain_name = 'http://localhost:1337/o/token/' headers = {'content-type': 'application/json' } r = requests.post(domain_name,headers=headers, data={ 'grant_type': 'password', 'username': email, 'password': password, 'client_id': app.client_id, # 'scope': 'read', 'client_secret': app.client_secret, },) This works fine on on manage.py runserver. but whenever Gunicorn and nginx are added to the mix it throws ConnectionError at /login HTTPConnectionPool(host='localhost', port=1337): Max retries exceeded with url: /o/token/ (Caused by NewConnectionError(': Failed to establish a new connection nginx.conf : upstream example { server web:8000; } server { listen 80; #server_name localhost; location / { proxy_pass http://example; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_read_timeout 300; proxy_connect_timeout 300; proxy_send_timeout 300; } } docker-compose file: services: web: build: context: ./ dockerfile: Dockerfile.prod command: gunicorn ExampleLiteB.wsgi:application --bind 0.0.0.0:8000 --workers 3 # volumes: # - static_volume:/home/app/web/staticfiles # - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod depends_on: - db db: image: postgres:14.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles ports: - 1337:80 depends_on: - web networks: djangonetwork: driver: bridge volumes: postgres_data: static_volume: … -
Can't find Django Shell command to purge records from one table, where matching records DON'T exist in another table
Django / ORM I have two tables, and I'm trying to purge / find all records in one table, where no matching records exist in the matching table. I'm using the Django Shell to test, but can't figure the command to say (in plain English)... Delete/Show all records in my movie table where there are no ratings for it in the ratings table The Movie table (obviously) has an id field, and the Rating table has a matching FK movie_id field) The tables are: class Movie(models.Model): imdbID = models.TextField(unique=True) title = models.TextField() year = models.TextField() class Rating(models.Model): movie = models.ForeignKey(Movie,on_delete=CASCADE) user = models.ForeignKey(User,on_delete=CASCADE) rating = models.IntegerField() A few of the Django commands I have ran are (to try to get close): >>> Movie.objects.all() ;gives all movies >>> Rating.objects.all() ;gives all ratings >>> Rating.objects.filter(movie__year=2018) ;works But when i try to dig deeper: (trying to ask for movies where movie_id equals rating movie_id), i get stuck... >>> Movie.objects.filter(movie_id=rating__movie) Traceback (most recent call last): File "", line 1, in NameError: name 'rating__movie' is not defined >>> Movie.objects.filter(rating__movie=movie_id) Traceback (most recent call last): File "", line 1, in NameError: name 'movie_id' is not defined I really want the NOT "WHERE' condition, but I can't … -
HTMX-How can I get valid form when field "keyup changed"
I have a forms.py as following. I am using htmx for validation. And I would like to get whole form for use form.is_valid() function. But in my case I am getting no valid form. Is there any way to get all form with HTMX? forms.py class UniversityForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'university-form' self.helper.attrs = { 'hx-post': reverse_lazy('index'), 'hx-target': '#university-form', 'hx-swap': 'outerHTML' } self.helper.add_input(Submit('submit', 'Submit')) subject = forms.ChoiceField( choices=User.Subjects.choices, widget=forms.Select(attrs={ 'hx-get': reverse_lazy('check-subject'), 'hx-target': '#div_id_subject', 'hx-trigger': 'change' }) ) date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date', 'max': datetime.now().date()})) class Meta: model = User fields = ('username', 'password', 'date_of_birth', 'subject') widgets = { 'password': forms.PasswordInput(), 'username': forms.TextInput(attrs={ 'hx-get': reverse_lazy('check-username'), 'hx-target': '#div_id_username', 'hx-trigger': 'keyup[target.value.length > 3]' }) } def clean_username(self): username = self.cleaned_data['username'] if len(username) <= 3: raise forms.ValidationError("Username is too short") return username def clean_subject(self): subject = self.cleaned_data['subject'] if User.objects.filter(subject=subject).count() > 3: raise forms.ValidationError("There are no spaces on this course") return subject def save(self, commit=True): """ Hash user's password on save """ user = super().save(commit=False) user.set_password(self.cleaned_data['password']) if commit: user.save() return user views.py def check_username(request): form = UniversityForm(request.GET) if form.is_valid(): print('Valid') else: print('No Valid') print(form.errors) print(form['date_of_birth']) context = { 'field': as_crispy_field(form['username']), 'valid': not form['username'].errors } return render(request, 'partials/field.html', context) Error: … -
How to accelerate the landing web page using Django on Digitalocean?
I created a "landing page website" using Django, it's a very simple website for using just for showing up the data with no query sets that coming from the database it's just 3 or 4 queries. I'm using the Nginx server for deploying and everything working properly but just the loading of the page is very very slow, I don't know where can I find the issue. I thought that the problem might become from Nginx since it has the ability to manage static files and also, I thought about maybe droplet cause such that issue. my brain is frozen about finding the core of that problem where I can't think of where the problem may happen so, how can I accelerate my web page, and what are the reasons for that problem? I don't know if StackOverflow is a good choice to ask such that question or not but I will be grateful for solving that problem in advance -
Get value from ajax to view template without using form
I have a div class that get content from for loop queryset <div class="form-group row"> <div class="col-md-4">Số hợp đồng</div> <label class="col-md-8" id="so_hd_goc">{{hd.so_hd}}</label> </div> I want to use ajax to get the value from id="so_hd_goc" and send it to views: my views: def check_so_hd(request): check_shd=request.GET.get("check_shd") print("check_shd",check_shd) return HttpResponse(check_shd) my form: <div class="card card-body"> <form method="POST" id = "save_bo_sung_sdt"> {% csrf_token %} <div class="form-group row"> <div class="col-md-6">Người liên hệ</div> <div class="col-md-6" id ="sdt_nguoi_lien_he" name="sdt_nguoi_lien_he">{{form1.nguoi_lien_he}}</div> </div> <div class="form-group row"> <div class="col-md-6">Số điện thoại</div> <div class="col-md-6" id ="sdt_dien_thoai" name="sdt_dien_thoai">{{form1.dien_thoai}}</div> </div> <div class="form-group row"> <div class="card-footer" > <button type="submit" class="btn btn-primary" id="save_phone" name="save_phone">Lưu số điện thoại</button> </div> </div> </form> </div> my ajax: <script> const form1 = document.getElementById('save_bo_sung_sdt') const sdtContainer = document.getElementById('sdt-body') form1.addEventListener('submit', checkshd) function checkshd(e){ e.preventDefault() check_shd=document.getElementById(so_hd_goc) $.ajax({ type: "GET", url: "{% url 'check_so_hd' %}", data: { check_shd:check_shd }, success:function(data){ alert(data) } }) }; </script> my url path('check_so_hd', CallerViews.check_so_hd, name="check_so_hd"), There is no error> just not print any result -
Should Response be imported or mocked when using unittest.mock
I'm learning unittest and unittest.mock with the latter not quite clicking. I'm mocking the response of an end-point and had the following: import unittest from unittest.mock import patch from rest_framework.test import APIClient class CoreTestCase(unittest.TestCase): @patch('core.views.CoreViewSet.list') def test_response(self, mock_get): mock_get.return_value = [{'hello': 'world'}] client = APIClient() response = client.get('/core/') print(response.data) Which resulted in the following error: AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'list'>` Made sense because DRF uses Response. To get around the error I modified to: import unittest from unittest.mock import patch from rest_framework.test import APIClient from rest_framework.response import Response class CoreTestCase(unittest.TestCase): @patch('core.views.CoreViewSet.list') def test_response(self, mock_get): mock_get.return_value = Response([{'hello': 'world'}]) client = APIClient() response = client.get('/core/') print(response.data) Which achieved the desired result and I was just passing in an array of objects (or list of dicts). However, I'm not sure this was the correct way of handling this and if Mock() should have been used instead. I can honestly say I haven't been able to figure out how to use Mock() or MagicMock() correctly, or find a tutorial that explains it clearly, so my attempts at using it with: mock_get.return_value = Mock([{'hello': 'world'}]) Just resulted in: TypeError: 'module' object …