Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to delete table content from sqlite Django
I want to delete the data when pressing the trash bin button. I am able to submit, edit petty cash into the database. I am only left with deleting the data. This is my views.py def deleteclaims(request, id): context = initialize_context(request) user = context['user'] #get id of particular form. claims = SaveClaimForm.objects.get(id=id) if request.method == 'POST': claims.name = request.POST['name'] claims.email = request.POST['email'] claims.claim = request.POST['claim'] claims.claimtype = request.POST.get('claimtype') claims.description = request.POST['description'] claims.receipt = request.FILES['receipt'] claims.cheque = request.POST.get('Cheque') claims.status = request.POST['status'] claims.delete() claims.save() return render(request, 'Login/existingclaims.html', {'claims':claims, 'user':user}, {'action' : 'Delete claims'}) In my html <tr align="center"> <td>{{ claims.id }}</td> <td>{{ claims.name }}</td> <td>{{ claims.email }}</td> <td>{{ claims.claim }}</td> <td>{{ claims.claimtype }}</td> <td>{{ claims.description }}</td> <td><a href="/media/{{ claims.receipt }}"> Click to View </a></td> <td>{{ claims.cheque }}</td> <td>{{ claims.status }}</td> <td><a href="/editclaims/{{claims.id}}"><i class="fas fa-pencil-alt"></i></a></td> <td><a href="/deleteclaims/{{claims.id}}"><i class="fas fa-trash"></i></a></td> </tr> -
Django form if input empty how to show warning
I created a form with file input. User can post the form with or without uploading a document. But how can I show a warning if the user does not upload a form when click upload button? forms.py class PdfForm(forms.ModelForm): class Meta: model = Pdf fields = ['title', 'pdf', 'document_type', 'year', 'payment_behavior'] labels = { "payment_behavior": "Please Select the Payment Behavior of the Customer: ", "document_type": "Document Type", "title": "Document Name", "pdf": "Please Select a File to Upload", "year": "Financial Table Year" } models.py class Pdf(models.Model): ... id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) pdf = models.FileField(upload_to=customer_directory_path, null=True, blank=True) document_type = models.CharField(max_length=200, default='Select', choices=CHOICES) year = PartialDateField(null=True, blank=True) ... template.html <form method="post" enctype="multipart/form-data" > {% csrf_token %} {{ form|crispy }} <div class="btn-group" role="group" aria-label="Basic example"> <button type="submit" class="btn btn-success">Upload File</button> <button type="submit" class="btn btn-warning">Non-report analysis</button> </div> </form> -
ModuleNotFoundError: No module named 'grp' on windows
As i was going through the Celery implementation from the Celery documentation, celery -A tasks worker --loglevel=INFO gave output unexpected that from the documentation, File "d:\101_all_projects\celery-testing\venv\lib\site-packages\celery\platforms.py", line 9, in import grp ModuleNotFoundError: No module named 'grp' Is this because i am on windows? -
django python if statement
I am trying to run a basic if statement in Django. I want to dispaly banner model.py class Banner(models.Model): title = models.CharField(max_length=250) sub_title = models.CharField(max_length=500) banner_img = models.FileField() def __str__(self): return self.title view.py class BannerView(generic.ListView): template_name = 'website/index.html' context_object_name = 'all_banners' def get_queryset(self): return Banner.objects.all() index.html {% if all_banners %} {% for banner in all_banners %} <img src="{{ banner.banner_img.url }}" class="card-img-top" alt="..."> {% endfor %} {% else %} <h3>You don't have any banner</h3> {% endif %} basicly i need display banner. i did upload the banner from admin page i get the output else statement pls give me adivse -
Django - Boolean Fields on Checkbox Input
I have a ModelForm which has Boolean Field and CheckboxInput. The Boolean field provides values of 0 (False) & 1 (True) by default in the MYSQL Database. The form is a modal and uses JSON to output the content from the Model. When the JSON file adds the content it enters either True or False. The issue occurs when I try to change and submit the value of the Checkbox Input from False to True. When I try this I get the following message: Oddly this works the other way around and allows me to submit the change from True to False. Below is the code (I have only included the field with the issue.) The field is First_Time_Booking Model. first_time_booking = models.BooleanField() Form Widget. 'first_time_booking': CheckboxInput(attrs={'class': 'form-check-input', 'id': 'bfbw_edit_first_time_booking', 'name': 'bfbw_edit_first_time_booking'}), View def update_bfbw(request): if request.method == 'POST': bfbw_booking_id = request.POST.get('bfbw_booking_ref') bfbw_data = BFBWBookings.objects.get(id=bfbw_booking_id) bfbw_data.school_name = request.POST['school_name'] bfbw_data.first_time_booking = request.POST.get('first_time_booking', False) bfbw_data.save() else: print(form.errors) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) I have tried writing an If function to alter the value, this then works to change the value to On but not when switching it off. I then get the below message. if request.POST['first_time_booking'] == 'on': bfbw_data.first_time_booking = True else: bfbw_data.first_time_booking = False … -
How to delete an image using default_storage.delete(file_name) in Django View?
So I have been creating a Fingerprint Matching system using Django Rest Framework. Whenever I send a fingerprint from frontend to backend to match with the stored fingerprints. The fingerprint is getting stored there which is not what I want. I want to delete it once it's use is over. Here is the Error Image: https://i.stack.imgur.com/MCXcv.png def post(self, request, format = None): serializer = serializers.MatchSerializer(data = request.data) if serializer.is_valid(): #Fetching the stored fingerprints in a different serializer. queryset = models.Profile.objects.all() serializer2 = serializers.ProfileSerializer(queryset, many=True) data = serializer2.data #Initialized a result list which will be appended with the name of the user whose #fingerprint is matched. result = [] file = request.FILES['fingerprint'] file_name = default_storage.save(file.name, file) file = default_storage.open(file_name) file_url = default_storage.url(file_name) fImage = cv2.imread(str(file)) for i in range(len(data)): print(data[i].get('fingerprint')) DbImage = cv2.imread('C:/Users/ShalomAlexander/Documents/4th Year Project/Django/FingerprintMatch/' + data[i].get('fingerprint')) if(isMatch(fImage, DbImage)): result.append(data[i].get('name')) #This is not working as expected because its raising an error ie. " Process is still #[![enter image description here][1]][1]in use" default_storage.delete(file_name) return Response(result) If you have any better approach to match fingerprints or images that will also be appreciated. Thanks in advance. The current code works fine and matches the fingerprint as expected but its storing the incoming fingerprint image … -
'for' statements should use the format 'for x in y': for allPosts in allPost1 and allPost2 and allPost3 and allPost4
I have so many keys in params and i want to display it on the template than i got an error that 'for' statements should use the format 'for x in y': for allPosts in allPost1 and allPost2 and allPost3 and allPost4 {% for allPosts in allPost1 and allPost2 and allPost3 and allPost4 %} .... {% endfor %} def search1(request): .... params = {'allPost1': allpost1,'allPost2': allpost2,'allPost3': allpost3,'allPost4': allpost4, 'query': query} return render(request, "home/search1.html", params) Please Help me. -
how to make a unique WATCHLIST for every USER in django REST and how to call the watchlist api based on that user
I am working on a practice Video streaming site based on Django and React. I am a little stuck on how to manage the Watchlist model in Django and make requests in React based on currently logged-in users. -
Website get crashed after running the game
I have a gaming website developed using the Python Django framework. In the game, more than 600 people visit at a time and it generates 1-90 random numbers to decide the winners. Every time when the game starts running the complete CPU starts to drain up to 99% and the website gets crashed. I already changed the server multiple time. Please let me know if there is any solution -
Update or Ignore || Update or Add || Add or Ignore || Ignore completely
@require_http_methods(["POST"]) @login_required def edit_guided_answer(request): req = json.loads(request.body) question_no = req["question_no"] guided_answers = req["guided_answer"] for guided_answer in guided_answers: models.ModelAnswer.objects.filter(answer_id=guided_answer["answer_id"]).update( answer_mark=guided_answer["answer_mark"], model_ans=guided_answer["model_ans"], ) for guided_answer in guided_answers: models.ModelAnswer.objects.create( question_id=models.Questions.objects.get(pk=question_no), answer_mark=guided_answer["answer_mark"], model_ans=guided_answer["model_ans"], ) return success({"res": True}) So what my code above is meant to do is to fit both the update and create at the same time, however i am trying to condition it so that i can update, add, ignore or update and add, however when i try to do this i get a key error.Is there a better solution for this? -
Django DJANGO_SETTINGS_MODULE
Is there a way i can specify the IP:Port in DJANGO_SETTINGS_MODULE (setting.py), instead of using python manage.py runserver <ip>:<port>? like we specify ALLOWED_HOST, INTERNAL_IPS etc -
How to get parent node name while using django mptt package in django rest serializers?
I am only getting parent id with this code, but i need parent node name . Is it possible to get parent node name ? class Department(MPTTModel,NameStatusModelMixin): desc = models.TextField(blank=True, null=True, default=None) slug = models.SlugField(max_length=100, blank=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') related_positions = models.ManyToManyField('Position', related_name='departments') class MPTTMeta: order_insertion_by = ['id'] def __str__(self): return self.name class DepartmentDetailSerializer(ModelSerializer): class Meta: model = Department fields = ('id', 'name', 'status', 'slug', 'desc', 'parent') -
Mysql transaction doesn't work in multi-thread
I'm using django and multi-thread in my task. Main logic code as below showed: # -*- coding: utf-8 -*- import os import logging import json import threading from django.conf import settings from django.core.management.base import BaseCommand from django.db import transaction from user_account.models import FbHandleTask, FbAccountSpendCapHandle, FbAccountBindingBmHandle, \ FbAccountNameHandle, FbAccountUserPermissionHandle, FbPixelBindingAccountHandle, FbPixelBindingBmHandel, FbBusinessUserInfo from utils.common import make_hash fb_batch_operate_logger = logging.getLogger('fb_batch_operate_producer') FB_HANDLE_DICT = { 'spend_cap': FbAccountSpendCapHandle, 'change_name': FbAccountNameHandle, 'user_permission': FbAccountUserPermissionHandle, 'binding_bm': FbAccountBindingBmHandle, 'pixel_account': FbPixelBindingAccountHandle, 'pixel_bm': FbPixelBindingBmHandel } class FbTaskTypeEnum(object): spend_cap = "spend_cap" change_name = "change_name" user_permission = "user_permission" binding_bm = "binding_bm" pixel_account = "pixel_account" pixel_bm = "pixel_bm" class FbTaskHandler(object): def __init__(self, category): self.category = category def work(self): try: accounts = FB_HANDLE_DICT[self.category].objects.filter(status=0, is_delete=0) if accounts: model_ids = [i["id"] for i in accounts.values("id")] with transaction.atomic(): accounts.update(status=4) # the status sometimes changed fb_batch_operate_logger.info("[status changed] with ids: {}".format(json.dumps(model_ids))) temp_id_list = [model_ids[i: i + 20] for i in range(0, len(model_ids), 20)] fb_task_list = [] handle_id_list = [] for handle_ids in temp_id_list: handle_ids = json.dumps(handle_ids) unique_hash = make_hash(self.category, handle_ids) fb_batch_operate_logger.info("[hash generated] hash: {}, with ids: {}".format(unique_hash, json.dumps(handle_ids))) fb_task = FbHandleTask( category=self.category, handle_ids=handle_ids, handle_status=0, user_name="automatic", unique_hash=unique_hash, ) try: FbHandleTask.objects.get(unique_hash=unique_hash) fb_batch_operate_logger.info("[hash existed] with ids: {}".format(json.dumps(handle_ids))) except Exception: fb_task_list.append( fb_task ) handle_id_list.append(handle_ids) fb_batch_operate_logger.info("[hash not existed] with ids: {}".format(json.dumps(handle_ids))) if fb_task_list: FbHandleTask.objects.bulk_create(fb_task_list) # … -
ValueError: Field 'id' expected a number but got 'Background' - Django
I have added a category feature im my image app then i got this error please help me to fix this issue as soon as possible urlpatterns = [ path('', RedirectView.as_view(url='home/')), path('home/', HomeView, name='home'), path('images/', ImageListView.as_view(), name='image_list'), path('image/<int:pk>/', ImageDetailView.as_view(), name='image_detail'), path('image/upload/', ImageUploadView.as_view(), name='image_upload'), path('image/<int:pk>/delete/', ImageDeleteView.as_view(), name='image_delete'), path('image/update/<int:pk>/', ImageUpdateView.as_view(), name='image_update'), path('category/<str:cats>/', ImageCategoryView, name='category_images'), ] def ImageCategoryView(request, cats): category_images = Image.objects.filter(category=cats) context = {'cats': cats, 'category_images':category_images} return render(request, 'main/image_category.html', context) <a href="{% url 'category_images' c.name|slugify %}" class="list-group-item list-group-item-action">{{c.name}}</a> -
how to upload images in flutter
hello i wonder to upload images in flutter i try to use http.MultipartRequest like this request.fields["name"] = "$RegisterName"; request.fields["description"] = "$RegisterDescription"; request.fields["caution"] = "$RegisterCaution"; request.fields["price"] = "$RegisterPrice"; request.fields["price_prop"] = "$RegisterPriceProp"; request.fields["user.id"] = "1"; request.fields["lend"] = "$RegisterCategory"; request.fields["category"] = "Digital"; request.fields["place_option"] = "true"; var multipartFile = http.MultipartFile.fromBytes( 'file', (await rootBundle.load('assets/images/main_1.jpg')).buffer.asUint8List(), filename: 'test01.jpg', contentType: MediaType('image', 'jpg'), ); request.files.add(multipartFile); var response = await request.send(); if (response.statusCode == 200) print('Upload'); } but this code is not working if i use this code, upload only another data upload things then json type is this json type image i want upload images files ...:( -
Query date on datetime stored within jsonfield in Postgres through Django?
I have a Postgres table with a jsonb column containing UTC timestamp data in ISO format like the following: { "time": "2021-04-13T20:14:56Z" } The Django model for this table looks like: class DateModel(models.Model): values = models.JSONField(default=dict) I need to query the table for all records with a timestamp on a certain date (ignoring time) I'm looking for a solution similar to the following: DateModel.objects.filter(values__time__date='2021-04-13') The other solution I have found is to query for records with date greater than the previous day and less than the next one. This works but I am looking for a way to do it with a single query so the code would be more concise. Any suggestions? -
Unable to render Django Rest Framework Errors on React JS page
ReactJS newbie here. I'm working on a ReactJS project with Django Backend. I'm facing an issue where I send user signup info to django api and it returns error as follows. (Note that when Data is correct, API end point works fine. And in case of error, generic error message i.e. error code 400 is displayed without) { "username": [ "A user with that username already exists." ], "email": [ "This field must be unique." ] } When I try to iterate the error, following error id displayed TypeError: Cannot read property 'map' of undefined typeof(error) shows this is an object. And when I see it in console.log, there are two arrays in the object. I'm not sure what am I doing wrong but it doesn't seem to work. I want to render errors in their corresponding fields. i.e. username error must be displayed above username input field and so on. How do I iterate the object so I may get the right message for the respective input? Thanks to all genius minds out there. -
Not able to insert value into database on django form submit by Ajax Post Data
Here I'm not able to add and update my Django form. I have use Ajax call to Post data on submit button. But it's not accepting my data and value into the database. can anyone help me to solve this problem? models.py class Order(models.Model): id = models.BigAutoField(primary_key=True) customer_id = models.ForeignKey(Customer, on_delete=models.CASCADE) product_id = models.ForeignKey(Product, on_delete=models.CASCADE) unit_price= models.DecimalField(default=0.00, decimal_places=2, max_digits=6) qty= models.PositiveIntegerField(default=1) total_price= models.DecimalField(default=0.00, decimal_places=2, max_digits=10) created_date= models.DateField(default=datetime.datetime.now()) forms.py class Orderform(forms.ModelForm): class Meta: model = Order fields = '__all__' labels = { 'customer_id':'Customer Name', 'product_id':'Product' } def __init__(self, *args, **kwargs): super(Orderform,self).__init__(*args, **kwargs) self.fields['customer_id'].empty_label = "select name" self.fields['product_id'].empty_label = "select product" main.js form.addEventListener('submit', e=>{ e.preventDefault() const fd = new FormData() fd.append('csrfmiddlewaretoken',csrf[0].value) fd.append('customer_id', customer_id.value) fd.append('product_id',product_id.value) fd.append('unit_price',unit_price.value) fd.append('qty',qty.value) fd.append('total_price',total_price.value) $.ajax({ // create an AJAX call... type:'POST', // GET or POST url: url, // the file to call data: fd, // get the form data success: function(response) { // on success.. window.location.pathname; console.log(response) // update the DIV const sText = `successfully saved ${response.customer_id}` handAlerts('sucess', sText) }, error: function(error){ console.log(error) handAlerts('danger','ups..something went wrong') }, cache: false, contentType: false, processData: false, }) }) Views.py def add_orders(request): if request.method == "GET": form = Orderform() return render(request,'addorder.html',{'form':form}) else: form = Orderform(request.POST) data = {} if request.is_ajax(): if form.is_valid(): form.save(commit=False) … -
How can i install my Django proyect in SSH?
Hey guys i want to install my Django project on my Host (Hosgator) and someone told me that is better use the SSH, but i dont know how to do it. It is the same as if I installed it on my computer locally also installing python or what the process would be like here. -
Get info from a view function and call it in a different function in view.py
I have a post page where you can see the post content and details like comments. I also want a separate page containing a form where you can type out the comment, and when the submit button is clicked, post the comment in the page. Here's what I have so far: My post view: def post_detail(request, id, slug): post = Post.objects.get(id = id) # I want this to be able to be called in a different function comments = Comment.objects.filter(post = post).order_by('-id') is_liked = False if post.likes.filter(id = request.user.id).exists(): is_liked = True context = { 'post' : post, 'is_liked' : is_liked, 'get_likes' : post.get_likes(), 'total_likes' : post.total_likes(), 'comments' : comments, } return render(request, 'post_detail.html', context) My url for post view: `url(r'(?P\d+)/(?P[\w-]+)/$', post_detail, name = "post_detail"), Here's the post_detail.html: <body> <h3>{{ post.title }}</h3> <small>Post created by: {{ post.author }}</small> <p>{{post.body|safe}}</p> {% include 'like_post.html' %} <div class= "main-comment-section"> {{comments.count}} Comment{{comments|pluralize}} {% for comment in comments %} <p class= "mb-0">{{comment.content}}</p> {% endfor %} <a href = "{% url 'add_comment' %}" class = "btn btn-secondary">Add comment</a> </div> My comment form view: def add_comment(request, id): post = Post.objects.get(id = id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit = False) comment.save() … -
How do I scope the tenants to User Model in django-multitenant?
I am using this django-multitenant package from citusdata https://github.com/citusdata/django-multitenant I tried extending the User model with a OneToOne field (I have tried both django's and yours) but I keep getting the error that User model doesn't inherit from your TenantModel/Mixin? class UsersExtended(models.Model/TenantModel): users = models.OneToOneField/TenantOneToOneField(Users,on_delete="") store = models.ForeignKey(Store) #Store is the tenant tenant_id = 'store_id' I am thinking maybe I should let go of the tenant_id thing in this usersextended model but I really am not sure. How do I relate the current user to a tenant in my middleware if I have to let go of the tenant_id thing even if I can access it via reverse relating the store field. I am having doubts on my practice. What is the correct way to scope Users to a Tenant(Store)??? Any help would be highly appreciated!!! Thank you -
What can I do if I get an operations timed out when logging into my ec2
I’ve been working on a little project using ec2 on my ssh terminal. All of a sudden it stops working and I get a “operations timed out... port 22. What can I do to avert this error . I’m a newbie -
Can't find objects in my database within month filter
I'm trying to display a count of the mentioned objects using this piece of code: day = datetime.date.today() MyModel.objects.filter(submit_date__month=day.month).count() Still, it returns a empty queryset. Below, a picture with the dates of the entries in the database, which are stored in a DateTimeField with default=timezone.now. P.S.: USE_TZ = True, TIME_ZONE = 'America/Bahia' -
Decide who get in the admin panel and who not with React Admin
I'm making a react app, that uses Django Rest Framework as a backend, and React as a fronted, I'm also using React Admin, to make all the logic of the admin panel, the thing is, I want that when someone logins to the website, the website lets you in if the "is_staff" field of the django user model is true, if it isn't, then redirect you to the home page(With your session active). I'm going to add some code that might help you to understand what I'm doing wrong. Thanks in advance TokenAuthProvider.js import { tokenAuthProvider } from 'ra-data-django-rest-framework' import apiUrl from './apiUrl' const authProvider = tokenAuthProvider({obtainAuthTokenUrl : apiUrl + '/api-token-auth/'}) export const modifiedAuthProvider = { ...authProvider, login : async ({ username, password }) => { const request = new Request(apiUrl + '/api-token-auth/', { method: 'POST', body: JSON.stringify({ username, password }), headers: new Headers({ 'Content-Type': 'application/json' }), }); const response = await fetch(request); if (response.ok) { const data = await response.json() localStorage.setItem('token', data.token); localStorage.setItem('is_staff', data.is_staff); return; } if (response.headers.get('content-type') !== 'application/json') { throw new Error(response.statusText); } const json = await response.json(); const error = json.non_field_errors; throw new Error(error || response.statusText); }, logout: () => { localStorage.removeItem('token'); localStorage.removeItem('is_staff'); return Promise.resolve(); }, … -
Django connection cursor scope
with connections['other_db'].cursor() as cursor: cursor.execute("""SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON SET CONCAT_NULL_YIELDS_NULL ON SET ANSI_WARNINGS ON SET IMPLICIT_TRANSACTIONS OFF SET ANSI_PADDING ON""") cursor.execute(sql, [self.sonumber, void_reason, rep.number]) result = cursor.fetchone() As above, do the SET commands inside that cursor will make changes to the connection globally if connection is persisted (side effects)?