Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sort by using radio button is not working django
I have a web page as shown below, so when I click on any 1 of my radio button, my url will show what I have click but, my data table won't sort in ascending order according to what I have selected, how do I fix this issue and how do I make it so that when I use the search bar and filter the page, it will still be sort in ascending order? views.py @login_required() def ViewMCO(request): search_post = request.GET.get('q') if (search_post is not None) and search_post: allusername = Photo.objects.filter(Q(reception__icontains=search_post) | Q(partno__icontains=search_post) | Q( Customername__icontains=search_post) | Q(mcoNum__icontains=search_post) | Q(status__icontains=search_post) | Q(serialno__icontains=search_post)) if not allusername: allusername = Photo.objects.all().order_by("-Datetime") else: allusername = Photo.objects.all().order_by("-Datetime") # The newest submitted log data will appear at the top page = request.GET.get('page') paginator = Paginator(allusername, 6) try: allusername = paginator.page(page) except PageNotAnInteger: allusername = paginator.page(1) except EmptyPage: allusername = paginator.page(paginator.num_pages) context = {'allusername': allusername, 'query': search_post} return render(request, 'ViewMCO.html', context) ViewMCO.html {% extends "customerbase.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, th:first-child { border-left: none; } .pagination a { padding: 10px; } … -
Sign up for membership in Django City, create admin authentication process
Currently, it is set to return to the first screen of the program when membership registration is completed in Django. However, since anyone can sign up and view information within the program, I want to make it possible to access the program's first page only after the administrator approves it when someone completes membership registration. As a result of Googling, only email verification was found, so I had to ask a question. There seems to be no admin authentication process provided by Django. Are there any similar examples or methods? -
CSRF Token problem when I add dropzone to an existing form in Django
I'm working with a Django form using dropzone to upload images. But I don't want to add the dropzone to the entire form, just to a div of it. Here is the template: {% extends 'base.html' %} {% load static %} {% load i18n %} {% block content %} <h6>UPLOAD MULTIPLE IMAGES NOW</h6> <br> <div class="formdiv" style="width:100%"> <form enctype="multipart/form-data" action="upload/" methd="POST"> {% csrf_token %} <fieldset> <label for="yourname">Yourname <input type="text" value="name" /> </label> <div class="dropzone dz" id="my-dropzone"> <div class="dz-message" data-dz-message><span>{% trans "Drop here or click to upload" %}</span></div> <div class="fallback"> <input name="file" type="file" multiple /> </div> </div> </fieldset> </form> </div> {% endblock %} The problem is that when I try to upload any image I get a Forbidden error message with the following text: CSRF token missing or incorrect. Notice that if I remove the class="dropzone dz" id="my-dropzone" from the div and I put it inside the <form> tag instead, everything will work. The problem began exactly when I moved dropzone in a div because I didn't want it to apply to the whole form. Here is my dropzone configuration code: Dropzone.autoDiscover=false; const myDropzone = new Dropzone('#my-dropzone',{ url:'upload/', maxFiles:15, maxFilesize:5, // 5 mb max //parallelUploads:2, // if image is horizontal, then … -
Celery Optimization with ECS Fargate
I'm trying to understand the most efficient way to scale celery workers in AWS ECS Fargate. If I'm trying to do a large data-add (from files), I want the data to written to the database as fast as possible. From what I understand, my options to try to make these tasks complete quicker: • I can run the celery worker concurrently with the -c option • I can run multiple tasks in ECS service • I can run multiple celery services in ECS cluster • I can increase the CPU/Memory of the ECS task Which option/combination would be the quickest? Which option would be the cheapest? -
'PdfFileWriter' object has no attribute 'seek'
I was trying to add password protection with pdf files, encounters this error, following are my code def generate_pdf(request): queryset = Subscription.objects.all() html_string = render_to_string('super_admin/member_report_pdf.html', {'object_list': queryset}) html = HTML(string=html_string) result = html.write_pdf() response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=list_people.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') inputpdf = PyPDF2.PdfFileReader(output) pages_no = inputpdf.numPages output = PyPDF2.PdfFileWriter() for i in range(pages_no): inputpdf = PyPDF2.PdfFileReader(output) output.addPage(inputpdf.getPage(i)) output.encrypt('pass') with open("member.pdf", "wb") as outputStream: response.write(outputStream) return response seeking help to sort out this error, thanks -
Django download file button takes in path
I am creating an app that allows users to convert their .ifc (3D model) files into other data forms (.xlsx, filtered .xlsx, json). I have managed to implement the upload part, but now I am not sure about the download. I would like to create a "download" button that takes in the users desired download path (maybe even file name). When I have the path I can start my conversion function with the last uploaded file. def model_form_download(request): if request.method == 'POST': download_path = ??? #How to take in the user defined upload path? last_model = Document.objects.latest("uploaded_at") last_model_name = last_model.document.name MODEL_DIR = Path(MEDIA_DIR) / last_model_name model = parser(MODEL_DIR) xlsx_name = Path(last_model_name).stem XLS_DIR = Path(download_path) / (xlsx_name + '.xlsx') model[1].to_excel(XLS_DIR) return render(request, 'core/model_form_download.html') return render(request, 'core/model_form_download.html') The extra question here is how to take in the user choice of prefered conversion format and use in this view function? -
Google Dev Tools
Hello I was wondering why Google Dev tools is loading the wrong CSS script when working on responsive design @media screen and (max-width:375px) { ... #name{ font-size: calc(.8rem + .1vw); } ... } @media screen and (max-width:480px) { ... #name{ font-size: calc(1rem + .1vw); } ... } when running the google dev tools it runs the second query rathenter image description hereer -
Field 'id' expected a number but got '(string)
I'm creating a T-shirt shop with variants/colors. In adding to cart, I get the error: Field 'id' expected a number but got 'woodstock'. Woodstock is the name of the shirt, but I'm passing the cartid to the function. cartid is actually being used in the remove_from_cart function, but I'm not sure why the error is thrown when I push add to cart. Here's the cart model: class Cart(models.Model): #user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) def __str__(self): return "Cart id: %s" %(self.id) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True, blank=True) product = models.ForeignKey(Product,on_delete=models.CASCADE) variations = models.ManyToManyField(Variation, blank=True) quantity = models.IntegerField(default=1) line_total = models.DecimalField(default=10.99, max_digits=100, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now=True) def __str__(self): try: return str(self.cart.id) except: return self.product.name views.py def view(request): print("viewing cart") try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) new_total = 0.00 for item in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity new_total += line_total request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total cart.save() context = {"cart":cart} else: empty_message = "Your cart is empty, please keep shopping" context = {"empty": True, "empty_message": empty_message} template = "cart/view.html" return render(request, template, context) def … -
Django Send_mail with PDF attachment
I already done sending email with HTML template, I want to add a attachment(PDF) in email but I got an error. AttributeError: 'int' object has no attribute 'attach'. Can you give me an Idea on how to add attach file in sending email via send_email in django?Thank you Tree ├── Folder │ ├── management │ ├── templates │ │ └── p.pdf My send_mail command are inside the management folder send email code subject = 'Management Automated Email- ' + (item.emp) html_message = render_to_string('email.html',data) plain_message = item.emp recipient_list = [item.email] from_email = <email@gmail.com>' toaddrs = recipient_list mail = send_mail(subject, plain_message, from_email, toaddrs, html_message=html_message, fail_silently=False) mail.attach('papers.pdf', 'pdf/plain') mail.send() -
How to increase password compelxity of default user model in Django?
I am required to increase the password complexity of user model in Django, How can i do that i researched about it but didnt get a answer that satisfy my requirements , so please suggest -
Display several locations stored in my database into a google map APi
well im starting to look into google maps APis, so far i managed to set the map in html with the Api key: <div id="map"></div> <script src="https://maps.googleapis.com/maps/api/js?key=<myAPiKey>&callback=initMap&libraries=&v=weekly" async ></script> and i have the js code to set the map in the user location, but i dont know where to start to do what i asked above, i already have my database where users can register store addresses so i can show them in my map, im working with Django and SQLite3, can someone help me, is the first time i work with Google maps API's and documentation is confusing. Thank you so much for your time! -
django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: staticfiles?
registry.py code for entry in installed_apps: if isinstance(entry, AppConfig): app_config = entry else: app_config = AppConfig.create(entry) if app_config.label in self.app_configs: raise ImproperlyConfigured( "Application labels aren't unique, " "duplicates: %s" % app_config.label) -
Restarting celery and celery beat schedule relationship in django
Will restarting celery cause all the periodic tasks(celery beat schedules) to get reset and start from the time celery is restarted or does it retain the schedule? For example assume I have a periodic task that gets executed at 12 pm everyday. Now I restart celery at 3 pm. Will the periodic task be reset to run at 3 pm everyday? -
how to test django views that use requests module get method?
I know how to write django test code. But I don't know how to test with views that inlcude requests.get code View code is like this. class CertificateAPIView(APIView): permission_classes = [IsAuthenticated, IsOwner] def put(self, request): imp = request.data.get("imp") response = requests.get('another server') uid = response.get('uid') if uid == None: return Response( {"detail": ValidationError(_("Certification is failed"))}, status=status.HTTP_400_BAD_REQUEST, ) ... more condition branch logics. return ... imp value is automatically created by 'another server' that I am not managing. This code is related with another server response and check condition branch with response. But before getting response with imp vlue, we can't check whether response is error. -
Problem in uploading image from form in django
I am trying to upload image from django form but it is not taking any image. It shows no file chosen. I have done all media setting in settings.py and urls.py. Still unable to upload image. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/') urls.py urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Also, I tried by using FileField in models.py models.py class Shop(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.CharField(max_length=255) image = models.ImageField(upload_to='profile/',default='/profile/my.jpg') phone = models.CharField(max_length=10) shop_code = models.CharField(max_length=10,null=True,blank=True) forms.py class ShopForm(forms.ModelForm): class Meta: model = Shop exclude = ['user'] fields = ['name','image','phone'] widgets = { 'name':forms.TextInput(attrs={'class':'form-control'}), 'image':forms.FileInput(attrs={'class':'form-control'}), 'phone':forms.TextInput(attrs={'class':'form-control'}), } views.py def create_shop(request): if request.method == "POST": form = ShopForm(request.POST or request.FILES) if form.is_valid(): shop = form.save(commit=False) shop.user = request.user shop.shop_code = get_random_string(8) shop.save() return redirect('shop_profile_info') else: form = ShopForm() context = { 'form':form } return render(request,'shop_create.html',context) shop_create.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" class="btn btn-dark mt-4"> </form> -
Django session variable value not up to date in view
i have two views to deal with some step processes. step 1: show all items with checkboxes, use ajax send seleted item's pk to backend by click button. There is a function at backend to set those values into session. def selecteditems(request): if request.is_ajax and request.method == "POST": request.session['selected'] = request.POST.getlist('items[]') request.session.modified = True return HttpResponse(status=200) step 2: get those variables from session and put them into second view. def step2(request): if request.method == "GET": selectedList = request.session.get('selected') allItems = Items.objects.all() selectedItem = allItems.filter(id__in=selectedList) context = { "selectedItem": selectedItem, } return render(request, 'step2.html', context) The problem i got is that, the second view always got "delay" values, meanning i have to refresh my page to load the latest items that i just selected, otherwise it is the data that i select in last time. -
Django model many to many through not working
i have mysql database that are already made. so models.py is created by manage.py inspectdb and i add artists = models.ManyToManyField(Artist, related_name='songs', through = "ArtistSong") to Song table like this. class Artist(models.Model): artist_id = models.IntegerField(primary_key=True) artist_name = models.TextField(blank=True, null=True) artist_main_genre = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'artist' class Song(models.Model): song_id = models.IntegerField(primary_key=True) issue_date = models.TextField(blank=True, null=True) album_name = models.TextField(blank=True, null=True) album_id = models.IntegerField(blank=True, null=True) song_name = models.TextField(blank=True, null=True) added_cnt = models.IntegerField(blank=True, null=True) thumb_url = models.TextField(blank=True, null=True) artists = models.ManyToManyField(Artist, related_name='songs', through = "ArtistSong") class Meta: managed = False db_table = 'song' class ArtistSong(models.Model): song = models.ForeignKey(Song, models.DO_NOTHING, blank=True, null=True) artist = models.ForeignKey(Artist, models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'artist_song' i want get name and artist name of song. my views.py here. class Songs(APIView): def get(self, request, *args, **kwargs): song_list= request.GET.get('song_list') queryset = Song.objects.filter(song_id__in = song_list) rec_songs = [] for song in queryset.iterator(): #for checking print(song.song_name) print(song.artists.all()) data = { 'song_name' : song.song_name, 'artist_name': [a.artist_name for a in song.artists.all()], } rec_songs.append(data) return Response(json.dumps(rec_songs,ensure_ascii = False)) print(song.song_name) shows song_name as i intened. print(song.artists.all()) shows nothing but <QuerySet []> please help! -
Do we need to close session explicitly in django request?
Let's say, we have class class Pipe(object): def __init__(self, imp_url=IAMPORT_API_URL): requests_session = requests.Session() requests_adapters = requests.adapters.HTTPAdapter(max_retries=3) requests_session.mount('https://', requests_adapters) self.requests_session = requests_session def get(self, url, payload=None) return self.requests_session.get(url, headers=headers, params=payload) views.py class RequestAPIView(APIView): pipe = Pipe() pipe.get(...) pipe.get(...) .... After call RequestAPIView, Do we need to close self.session explicitly in pipe object? Or after RequestAPIView done, Does the self.session will be closed automatically? -
Doing inference using pytorch saved weights in .tar file using django
I am doing a machine learning project where I need to display the predictions on a webpage. The webpage is build using Django. I have predictions function and the weights of the model but how to integrate the predictions function, model, and weights in the Django code and do predictions. My prediction code def predicting(model, device, loader): model.eval() total_preds = torch.Tensor() total_labels = torch.Tensor() with torch.no_grad(): for solute_graphs, solvent_graphs, solute_lens, solvent_lens in loader: outputs, i_map = model( [solute_graphs.to(device), solvent_graphs.to(device), torch.tensor(solute_lens).to(device), torch.tensor(solvent_lens).to(device)]) print(outputs) total_preds = torch.cat((total_preds, outputs.cpu()), 0) return total_preds.numpy().flatten() I have saved the weights in .tar file so I need to run the model while loading the weights for prediction. I have no idea where to keep my PyTorch model and the weights to do inference using Django. please help. -
'dict' object has no attribute 'META' redirect error
sorry for typos, I'm using translation I want to integrate virtual pos for payment method, but the error I got is as follows Error; 'dict' object has no attribute 'META' views.py: @login_required(login_url="/user/login") def payment(request): options = { 'api_key': 'api_key', 'secret_key': 'secret_key', 'base_url': 'sandbox-api.iyzipay.com' } payment_card = { 'cardHolderName': 'John Doe', 'cardNumber': '5528790000000008', 'expireMonth': '12', 'expireYear': '2030', 'cvc': '123', 'registerCard': '0' } buyer = { 'id': 'BY789', 'name': 'John', 'surname': 'Doe', 'gsmNumber': '+905350000000', 'email': 'email@email.com', 'identityNumber': '74300864791', 'lastLoginDate': '2015-10-05 12:43:35', 'registrationDate': '2013-04-21 15:12:09', 'registrationAddress': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', 'ip': '85.34.78.112', 'city': 'Istanbul', 'country': 'Turkey', 'zipCode': '34732' } address = { 'contactName': 'Jane Doe', 'city': 'Istanbul', 'country': 'Turkey', 'address': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', 'zipCode': '34732' } basket_items = [ { 'id': 'BI101', 'name': 'Binocular', 'category1': 'Collectibles', 'category2': 'Accessories', 'itemType': 'PHYSICAL', 'price': '0.3' }, { 'id': 'BI102', 'name': 'Game code', 'category1': 'Game', 'category2': 'Online Game Items', 'itemType': 'VIRTUAL', 'price': '0.5' }, { 'id': 'BI103', 'name': 'Usb', 'category1': 'Electronics', 'category2': 'Usb / Cable', 'itemType': 'PHYSICAL', 'price': '0.2' } ] request = { 'locale': 'tr', 'conversationId': '123456789', 'price': '1', 'paidPrice': '1.2', 'currency': 'TRY', 'installment': '1', 'basketId': 'B67832', 'paymentChannel': 'WEB', 'paymentGroup': 'PRODUCT', 'paymentCard': payment_card, 'buyer': buyer, 'shippingAddress': address, 'billingAddress': address, … -
m2m_changed signal with many-to-many through - save
I have these two basic models, class Product(models.Model): title = models.CharField(max_length=40) description = models.TextField(blank=True) price = models.DecimalField(decimal_places=2, max_digits=7, default=0) ... and class Cart(models.Model): user = models.ForeignKey( User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField( Product, blank=True, through='CartItem') total = models.DecimalField(default=0.00, max_digits=7, decimal_places=2) def recalculate_and_save(self): print("recalculate_and_save running") total = 0 for ci in self.cartitem_set.all(): total += ci.product.price*ci.quantity self.total = total self.save() , and a helper model for many-to-many relation above, to account for quantity: class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.SmallIntegerField(default=1) What I want to achieve is automatic calculation of Cart's total every time an item is added or removed. So, @receiver(m2m_changed, sender=CartItem) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): print(f"m2m_changed received; action={action}, instance={instance}") instance.recalculate_and_save() Then I realized, seeing pre_save and post_save actions in logs, that I'm likely doing something wrong - calling save in the function which is called (twice) from parent's save, as per docs. The first question is, then - why doesn't it send me into an infinite loop? And the second (and probably more important) - why am I only seeing the receiver function executing on removing items from the cart, but not on adding them? Removing is done via cart.products.remove(product_obj) , but … -
Django cant figure out how to use foreign key
''' class Project_types(models.Model): project_type = models.CharField(max_length=200) def __str__(self): return self.project_type class Projects(models.Model): project_types = models.ForeignKey(Project_types, on_delete=models.CASCADE) project = models.CharField(max_length=200) def __str__(self): return self.project ''' When I try to run - Project_types(project_type='games').item_set.all() I get an error saying that there is no attribute item set. -
Django filter json object's list by comparing with another list
I have a model that has a field which is a JSON field. This json_field has a value which is a list. model: attr1: attr2: attr3: json_field: { jattr1: jattr2: array_field: [values ...] } I have a queryset obtained from some other filter operation: queryset I want to apply model.objects.filter() such that I obtain every instance where array_field values are present in the queryset. For example: consider 4 instances instance1: json_field: { array_field: [1, 2, 3, 4] } instance2: json_field: { array_field: [2, 4] } instance3: json_field: { array_field: [1, 4] } instance4: json_field: { array_field: [3] } and queryset is : queryset: [2, 3] I am expecting something like this: Model.objects.filter(json_field__array_field__in=queryset) # This should return instance1: json_field: { array_field: [1, 2, 3, 4] } instance2: json_field: { array_field: [2, 4] } instance4: json_field: { array_field: [3] } Thank you for your help. -
Django how to add html style in JavaScript for load more button
I successfully implement load more button but now I can't add my html style in JavaScript. This is my original style before implement load more button. see the screenshot: after implementing load more button. I have style like this. see the screenshot below: How to implement my first style for individually showing each blog. here is my JavaScript for showing html: postsBox.innerHTML += `<div class="card mb-4" style="max-width:700px";> ${post.title} <br> ${post.body} </div> ` my .html page: <div id="posts-box"></div> <div id="spinner-box" class="not-visible"> <div class="spinner-border text-primary" role="status"></div> </div> <div id="loading-box"> <button class="btn btn-primary" id="load-btn">Load more</button> </div> -
Django - Disable authenticator for Swagger
So I have a Django app with Swagger, but I also added a custom authenticator to every endpoint automatically with REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'cheers.utils.authenticator.CognitoAuthentication', ), } How do I turn this off for swagger? The reason I'm not sure is because Swagger is added to URLs it's not a view How do I disable automatic authentication for swagger? Also I guess a side question would be how to disable this URL when debug is False