Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
It gives me AddForm() missing 1 required positional argument:'request' .. What is wrong?
Views.py Html Error message that is all -
How to add Request Samples of PHP and C# in Django ReDoc
I am using drf-yasg package for my Django Rest API Documentation. By default It showing only one Request sample called "Payload" like shown in below link. https://i.stack.imgur.com/1Pno2.jpg I want to Add More Request Sample like shown in the picture below. https://i.stack.imgur.com/yy9tv.png -
pipenv Could not find a version that matches pathspec
There was a problem downloading awsebcli to deploy the Django project on AWS. pipenv install awsebcli enter image description here this is my pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] flake8 = "*" black = "*" [packages] pathspec = "== 0.5.9" django = "==3.0.3" [requires] python_version = "3.7" [pipenv] allow_prereleases = true -
ValueError: Buffer dtype mismatch, expected 'SIZE_t' but got 'long'
This occurs while loading a pickle file which contains my ML algorithm. Why am i getting this error in django? -
Divide in Django Templates
I have django template in which I want to divide a td component by another, How cain I do that ? {% for i in query %} <tr> <td class="align-middle">{{ i.pending_docket_list.sales_order.owner }}</td> <td class="align-middle">{{ i.pending_docket_list.sales_order.pk }}</td> <td class="align-middle">{{ i.pending_docket_list.sales_order.flow }}</td> <td class="align-middle">{{ i.pending_docket_list.sales_order.kit.components_per_kit }}</td> <td class="align-middle">{{ i.pending_docket_list.sales_order.quantity }}</td> <td class="align-middle">{{ i.pending_docket_list.sales_order.is_allocated }}</td> <td class="align-middle">{{ i.pending_docket_list.sales_order.created_on }}</td> </tr> {% endfor %} I want to do something like this: <td class="align-middle">{{ divide i.pending_docket_list.sales_order.quantity i.pending_docket_list.sales_order.kit.components_per_kit }}</td> But when I do this I get the following error: Invalid block tag on line 42: 'divide', expected 'empty' or 'endfor'. Did you forget to register or load this tag? How can I do this ? -
How to Croppie one image uploaded
I have been looking the Croppie library: https://foliotek.github.io/Croppie/ But I can't realize how to use it properly if I upload one image (the webpage needs a bit more info). How can I set my uploaded image inside of the croppie? I have tried bind or other ways but I can't show it inside. I leave you here my code (almost the same saw it in the official page): HTML <div class="form-group"> <div id="image_user_profile" class="custom-input-file text-center"> <input id="fileInput" name="fileInput" type="file" size="1" class="input-file"/> <img id="img_user" alt="Upload user image" src="{{ user.get_picture }}" width="50%" height="50%" style="background-color: #eee; min-height:100px"/> </div> </div> <div class="row"> <div class="col-xs-12"> <div id="img-user-prueba2"> </div> </div> </div> JS var uploadCrop = $('#img-user-prueba2').croppie({ enableExif: true, viewport: { width: 200, height: 200, }, boundary: { width: 300, height: 300 } }); $('input[name=fileInput]').change(function(ev) { RegisterTraveler.readURL(this); }); -
Django 2.2 conditional item in SUIT_CONFIG MENU
Django 2.2 django-suit==0.2.26 in my settings.py I have SUIT_CONFIG with MENU inside: SUIT_CONFIG = { # Change Admin header 'ADMIN_NAME': 'My Name', #this controls number of entries in the view on the web page 'LIST_PER_PAGE': 20, .......blah-blah...... # Main Menu manager 'MENU': ( { 'label': 'Label1', 'url': SCRIPT_NAME + '/some_url1', }, { 'label': 'Label2', 'url': SCRIPT_NAME + '/some_url2', }, { 'label': 'label3', 'url': SCRIPT_NAME + '/some_url3/', }, ) } Is it possible to make one of the MENU items optional? Thanks -
How to correct TypeError: Unicode-objects must be encoded before hashing with ReportLab in Python
Recently, I have been working ReportLab. At the moment, I would like to generate clickable Table Of Contents in PDF using ReportLab. When I tried to see how it works, I keep getting this error: TypeError: Unicode-objects must be encoded before hashing When I tried to execute this code on Python 3.7.4 using ReportLab library: class MyDocTemplate(BaseDocTemplate): def __init__(self, filename, **kw): self.allowSplitting = 0 apply(BaseDocTemplate.__init__, (self, filename), kw) template = PageTemplate('normal', [Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1')]) self.addPageTemplates(template) def afterFlowable(self, flowable): "Registers TOC entries." if flowable.__class__.__name__ == 'Paragraph': text = flowable.getPlainText() style = flowable.style.name if style == 'Heading1': level = 0 elif style == 'Heading2': level = 1 else: return E = [level, text, self.page] #if we have a bookmark name append that to our notify data bn = getattr(flowable,'_bookmarkName',None) if bn is not None: E.append(bn) self.notify('TOCEntry', tuple(E)) centered = PS(name = 'centered', fontSize = 30, leading = 16, alignment = 1, spaceAfter = 20) h1 = PS( name = 'Heading1', fontSize = 14, leading = 16) h2 = PS(name = 'Heading2', fontSize = 12, leading = 14) # Build story. story = [] toc = TableOfContents() toc.levelStyles = [ PS(fontName='Times-Bold', fontSize=20, name='TOCHeading1', leftIndent=20, firstLineIndent=-20, spaceBefore=10, leading=16), PS(fontSize=18, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, … -
Django AttributeError when trying to add an object to a ManyToManyField
I have a webapp where I have a friends system. You guys here helped me out with that earlier, but now I have another problem. Here is my models in UserProfileInfo friends = models.ManyToManyField(User,blank=True,related_name='user_connections') And here is my AddFriendRedirect view class AddFriendRedirect(RedirectView): def get_redirect_url(self,*args,**kwargs): username = self.kwargs.get("username") obj = get_object_or_404(UserProfileInfo,slug=username) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated: if user in obj.friends.all(): obj.friends.remove(user) user.friends.remove(obj) # these are the fields causing the error else: obj.friends.add(user) user.friends.add(obj) # these are the fields causing the error return url_ And here is the error AttributeError at /mainapp/profile/don0024/add/ 'User' object has no attribute 'friends' Traceback: File "C:\Users\don0024\interests\interests_env\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\don0024\interests\interests_env\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\don0024\interests\interests_env\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\don0024\interests\interests_env\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\don0024\interests\interests_env\lib\site-packages\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "C:\Users\don0024\interests\interests_env\lib\site-packages\django\views\generic\base.py" in get 188. url = self.get_redirect_url(*args, **kwargs) File "C:\Users\don0024\interests\interests\mainapp\views.py" in get_redirect_url 238. user.friends.remove(obj) File "C:\Users\don0024\interests\interests_env\lib\site-packages\django\utils\functional.py" in inner 257. return func(self._wrapped, *args) Exception Type: AttributeError at /mainapp/profile/don0024/add/ Exception Value: 'User' object has no attribute 'friends' The obj.friends.remove(user) removes and adds the current user to the ManyToMany field on obj. How am I able to … -
Want to pass data from componentDidMount but it's always undefined
Getting data from server in componentdidmount and passing to handlesubmit function but it always returns undefined: constructor() { super(); this.state = { data: [] }; } componentDidMount() { fetch(BASE_URL_API + "/payments/subscriptions/") .then(res => res.json()) .then(json => this.setState({ data: json })); } handleSubmit = async event => { event.preventDefault(); const data = this.props; console.log("Token is: ", data); }; -
django admin scrapy with UI
i m new to this and struggling to find a way where i can possibly integrate scrapy into my django admin. Meaning there by , - able to trigger scrapy spider from my django admin I have already - created the spider to collect data - persisting data into mongodb (so no worries of using wrapper to w.r.t performance) - have django admin interface able to read that data and display in admin Now i would like to put a feature where i can see this is my spider and i use the clickbutton to trigger it. OR alternatively, can you advise if i can integrate sxrapy into djangocms??? I have gone through numerous examples and tutorials but not making sense to me. How and what should i do? Please share some thoughts. thanks -
Django Rest Framework GET request with params
I'm trying to make a get request with params (srcFilename) in Django Rest Framework. I'm pretty confused about where to add the "req.query.srcFilename" (as it would be in javascript) in django. I read I have to add the complete url with the params in "<>" as shown in the code below, but it wont find the url. views.py: @api_view(['GET']) def api_generate_signed_url(request, srcFilename): print(f'srcFilename: {srcFilename}') bucket = storage_client.bucket(bucket_name) blob = bucket.blob(srcFilename) if request.method == 'GET': url = blob.generate_signed_url( version="v4", # This URL is valid for 15 minutes expiration=datetime.timedelta(minutes=15), # Allow GET requests using this URL. method="GET", ) print(f"Generated GET signed URL: {url}") return Response(url) urls.py: urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path(r'signedurl?srcFilename=<srcFilename>', api_generate_signed_url), ] When trying this in Postman I get the following error: The current path, signedurl, didn't match any of these. Postman screenshot -
Django APP on AWS Beanstalk stopping during process
I have developed a Django APP in AWS Beanstalk. it works but after the lastest deploy, the process starts correctly but at a certain position in the code, it stops without errors (I have seen in both AWS Beanstalk logs and my app logs) and doesn't go ahead. is it possible that I should erase or cancel some cache file or something like that? Thank you in advance -
django create random url valid id sequence for objects
I want to create a more ore less short think youtube url codes (watch=dQw4w9WgXcQ), which contain all URL legal characters to use as an id for my objects. Is there a library that allows me to do this? Basicly instead of using a consecutive number to identify and object, use a random sequence. I know theres a UUID libarary, but 16 bytes just seams to long, I would like to keep my URLs a bit shorter. So whats is the best way to do this? -
how do i combine pagination and taggit(categorizing my blog)?
So im trying to make a blog page with django. i wanted to categorize the posts with taggit and i have done it correctly. then i wanted to paginate the blog posts and that worked well too. but when i want to combine them together, the tags dont work. the pagination works but when i click the tags they just show a blank page this is my views.py: from django.shortcuts import render, get_object_or_404 from .models import Post from taggit.models import Tag from django.template.defaultfilters import slugify from django.core.paginator import Paginator def blog_view(request): posts = Post.objects.all() paginator = Paginator(posts, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) common_tags = Post.tags.most_common()[:] context = { 'common_tags':common_tags, 'page_obj': page_obj, } return render(request, 'blog.html', context) def tagged(request, slug): tag = get_object_or_404(Tag, slug=slug) common_tags = Post.tags.most_common()[:4] posts = Post.objects.filter(tags=tag) context = { 'tag':tag, 'common_tags':common_tags, 'posts':posts, } return render(request, 'blog.html', context) this is my models.py: from django.db import models from taggit.managers import TaggableManager from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=250) description = models.TextField() summ = models.TextField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) published = models.DateField(auto_now_add=True) prof = models.CharField(max_length=100) tags = TaggableManager() slug = models.SlugField(unique=True, max_length=100) def __str__(self): return self.title and this is my template: <ul> … -
How can I get current Value of Selected button from the following?
I want to create a button group, where button from a group can be selected at once. Let's suppose we have got three buttons, the user should be able to select only one button, so if user selects "English" then they shouldn't be able to select the English button again. <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> <input type="radio" name="options" id="option1" checked> English </label> <label class="btn btn-primary"> <input type="radio" name="options" id="option2"> Hindi </label> <label class="btn btn-primary"> <input type="radio" name="options" id="option3"> Urdu </label> </div> -
Why we need `django-webpack-looader` to serve Vue application through django?
I want to serve my Vue application (as SPA) through django, and I passed across this article. The author use django-webpack-loader to achieve this, but is not adding a simple TemplateView around dist/index.html will do the job: url(r'^app/', TemplateView.as_view(template_name='index.html'), name='app'), also this require altering settings.by as follow: 'DIRS': [ BASE_DIR + "/templates/", BASE_DIR + "/dist/", ] My question is what is the role of django-webpack-loader in the process if the app is already build using vue-cli? -
Image labeling web application using django
I am working on a project where I have to label the points on Image and whenever user will click on that point the label will appear. Is there any dependencies available for performing such kind of operations on Python. My web app will be based on Djnago. Ignore these. type Stats interface { CountUsers() int } var stats Stats func SetStats(s Stats) { stats = s } func GetStats() Stats { return stats -
AJAX POST not actually sending POST data with Django
I want to submit a form to my Django back end using an AJAX post. I have multiple forms on the page but only want the one the user submits to be the one that sends. The form is held in a modal: <div class="modal-body"> <div class='content-section'> <form method="POST" id="form{{ prod.id }}" class="showform" value="{{ prod.id }}" > <input type="hidden" value="{{ prod.id }}" name="prodid"> {% csrf_token %} <fieldset class='form-group'> {{ form|crispy}} </fieldset> </form> </div> </div> <div class="modal-footer"> <div class='form-group'> <button class="btn btn-outline-info submit-form" value={{prod.id}} form="form{{ prod.id }}" >Save To Profile</button> </div> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> When the submit button is pressed, it triggers the following AJAX : $(document).on('click', '.submit-form', function () { var thisButton = $(this)[0] var prodID = $(this).val(); var form = $("form" + prodID); $.ajax({ type: 'post', headers:{ "X-CSRFToken": '{{ csrf_token }}' }, url: '/ajax/validate_showadd/', dataType: 'json', contentType: 'json', data: { 'form': form.serialize(), "prodID":prodID, }, success: function (data) { console.log("sent") }, error: function(data) { console.log("error") } }); return false; }); However, within Django whenever I try access any of these values it just returns 'None' and the QueryDict for the POST request is empty. Thank you -
Python Django - Count objects based on owner that is the user
I have users who listed their textbook. I need to count objects in Textbook model and display total count in the side menu. Here is my Model from django.db import models from django.http import HttpResponse from django.urls import reverse from django.contrib.auth.models import User from django.utils.functional import cached_property class Textbooks(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT, null=True, blank=True) title = models.CharField(max_length=1000) isbn = models.CharField(max_length=20) author = models.CharField(max_length=250) edition = models.CharField(max_length=50) rrp = models.CharField(max_length=30) about = models.TextField(max_length=1000, null=True) textbook_image = models.FileField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('textbooks:detail', kwargs={'pk': self.pk}) def __str__(self): return self.title I used Custom template tag class CustomTag(template.Node): def render(self, context): context['my_custom_tag_context'] = Textbooks.objects.filter(owner=self.user.request).count() return '' @register.tag(name='get_custom_tag') def get_custom_tag(parser, token): return CustomTag() enter image description here AttributeError at / 'CustomTag' object has no attribute 'user'. It seems that i cant use filter in template tag. is there any other way i can filter them and show the count by owner who is logged in? Here is what i intend to have. enter image description here -
Get Order_id and save to OrderItem
Tell me how I can get the order_id in order to add the product to the model OrderItem on page view detail order. I open the order page and I see the goods in the order and also on this page I have to add goods to the order. The product is stored in the database, but the order id does not accept and does not save. How to do it? views.py #saving product to order def ajax_add_own_product(request): data = dict() if request.method == 'POST': form = OwnOrderItem(request.POST) if form.is_valid(): data['form_is_valid'] = True else: data['form_is_valid'] = False else: form = OwnOrderItem() context = {'form': form} data['html_form'] = render_to_string('include/order_container.html', context, request=request ) return JsonResponse(data) forms.py class OwnOrderItem(ModelForm): class Meta: model = OrderItem fields = ('sku', 'product_name', 'qty', 'price') model.py class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT, null=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items', null=True) product_name = models.CharField(max_length=255, null=True) qty = models.PositiveIntegerField(default=1) price = models.DecimalField(default=0.00, decimal_places=2, max_digits=20) discount_price = models.DecimalField(default=0.00, decimal_places=2, max_digits=20) final_price = models.DecimalField(default=0.00, decimal_places=2, max_digits=20) total_price = models.DecimalField(default=0.00, decimal_places=2, max_digits=20) outsource_id = models.ForeignKey(Outsource, on_delete=models.PROTECT, null=True) technology_id = models.ForeignKey(Technology, on_delete=models.PROTECT, null=True) shipment_status_id = models.ForeignKey(ShipmentStatus, on_delete=models.PROTECT, null=True) sku = models.CharField(max_length=70, null=True) -
DJANGO/MAPBOX (mysql querey using js and returning to template which is mapbox)
Im looking for some help. I have a simple html template that displays a map using mapbox. The template calls a .js (app.js) which should query my remote MySQL DB and return the data and then plot it on the map. Error is 'data' is not defined. 1st question am I going about this in the right way? If not looking for advice. 2nd question how do I fix the error and will fixing it achieve what I want to do? app.js below; console.log("Starting..."); define(function (require){ var mysql = require(['node_modules/mysql']); var con = mysql.createConnection({ host: "connection details", user: "connection details", password: "" }); con.connect(function(err) { if (err) throw err; console.log("Connected!"); con.query("SELECT * FROM MCC_234", function (err, result, fields){ if (err) throw err; console.log(result); }); }); }) var data = [{ type:'scattermapbox', lat:['45.5017'], lon:['-73.5673'], mode:'markers', marker: { size:14 }, text:['Montreal'] }] var layout = { autosize: true, hovermode:'closest', mapbox: { bearing:0, center: { lat:45, lon:-73 }, pitch:0, zoom:5 }, } Plotly.setPlotConfig({ mapboxAccessToken: "access token" }) Plotly.newPlot('myDiv', data, layout) map3.html below; <html> <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <script src="https://requirejs.org/docs/release/2.3.1/minified/require.js"></script> <title>Harry's Map</title> <style> .modebar { display: none !important; } </style> </head> <body> <div id='myDiv'></div> <script> src="js/app.js" </script> </body> </html> Still learning so any help greatly … -
how to extract the banks that were closed on 25th october 2019 from this dataset?
please The links is here for the dataset ='http://www.fdic.gov/bank/individual/failed/banklist.html' -
Django CreateView test fail
My configuration below (django 3.02): Models: class Assets(models.Model): assettag = models.CharField() ... class Item(models.Model): asset = models.OneToOneField('Assets') ... def __str__(self): return (f"{self.rfid_tag}" + " - " + f"{self.asset.assettag}") class Comments(models.Model): # I know, it should not be plural. item = models.ForeignKey('Item', default=None, null=True, on_delete=models.CASCADE, ) text = models.TextField() ... Form: class ItemInsertForm(forms.ModelForm): rfid_tag = forms.CharField(label='RFID Tag', widget=forms.TextInput(attrs={"placeholder":"96 bit EPC code", "pattern":"^[a-fA-F0-9]{24}$", "size":"25", "id":"rfid_tag", } ) ) asset = forms.CharField(label='AssetTag', widget=forms.TextInput(attrs={"placeholder":"Item Inventory Tag", "pattern":"{some regex}", "size":"25", "id":"asset", } ) ) comments = forms.CharField(label='Comments', required=False, widget=forms.Textarea(attrs={"rows":5, "cols":50, "id":"comments", } ) ) class Meta: model = Item fields = [ 'rfid_tag', 'asset', 'image', 'date', ] def clean_rfid_tag(self, *args, **kwargs): return self.cleaned_data.get("rfid_tag").lower() def clean_asset(self, *args, **kwargs): AssetTag = self.cleaned_data.get("asset") try: _asset = Assets.objects.get(assettag = AssetTag) except Assets.DoesNotExist: raise forms.ValidationError("Asset does not exist !") self.Asset = _asset return self.Asset View: class InsertView(SuccessMessageMixin, AuditMixin, generic.CreateView): template_name = '{some template}' success_message = "Item succesfully created" form_class = ItemInsertForm def form_valid(self, form): item = form.save(commit=False) _comment = form.cleaned_data.get('comments') item = form.save() if _comment: item.comments_set.create(text =_comment) self.log_insert(item) return super().form_valid(form) Test: class TestViews(TestCase): @classmethod def setUpTestData(cls) -> None: # create dummy assets cls.asset = Assets.objects.create(assettag="{some assettag #1}",) cls.asset2 = Assets.objects.create(assettag="{some assettag #2}") # create dummy item cls.item = Item.objects.create(rfid_tag='abcdef012345678900000000', asset=cls.asset) … -
Calling function from request function in views Django
I have simple html template with link, that starts script, in views that retrieves data to the page,in views file I have two functions: render function def output(request):(it retrieves data to the page) and another function def summoner(): that makes postgres quires in cycle and appends results to the list. Separately each of them work fine, but I have to call second function from render function and retrieve the data to the page, but now when I do that all I am getting is empty list. enter image description here template: <html> <head> <title> Python script </title> </head> <body> <a href="{% url 'script' %}">Execute Script</a> <hr> {% if data %} {{ data }} {% endif %} </body> </html> views: from django.shortcuts import render import pandas as pd import psycopg2 import os, glob conn = psycopg2.connect(host='127.0.0.1', database='db', user='user', password='pass') cur = conn.cursor() def insert_data_as_is(file_name): cur.execute('truncate table test_inv.start_tbl') with open(file_name, 'r') as file: cur.execute("insert into test_inv.start_tbl values {0}".format(file.read())) conn.commit() def insert_data_to_be(file_name): cur.execute('truncate table test_inv.res_calc_ratios_t') with open(file_name, 'r') as file: cur.execute('insert into test_inv.res_calc_ratios_t (test_no, test_name, hcode_id, ' 'hcode_name, hcode_' 'unit_name,' ' org_id, dor_kod, duch_id, nod_id, date_type_id, metric_type_id, cargo_type_id, val_type_id,' ' unit_id, dt, value, ss, dir_id, kato_id, vids_id) values {0}'.format(file.read())) conn.commit() path_start = 'files/csv_s/as_is/' …