Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python requests with django.test. Send post request by django.test and have request.FILES
i have view def my_view(request): if request.method == 'POST': folder = request.POST.get('folder', '') for fname, file in request.FILES.items(): save(folder, fname, file) return HttpResponse(status=200) return HttpResponse(status=400) I send response using python lib requests like this in production requests.post(url='', data=post_data, files=files_to_send) i have request.FILES and i can save it. Now i need make tests. If i write like this i have no files in request.FILES. class Test(TestCase): def test_1(): response = self.client.post('http://127.0.0.1:8000', data={'folder': 'save_folder/'}, files=files_to_send) self.assertEqual(response.status, 200) How i can to send by post request files, and receive it on my_view in request.FILES? Or how i can use code located bellow on django.test? import requests requests.post(url=url, data=post_data, files=files_to_send) -
Cannot Get Menu item to Template
i have 2 apps in Django Project one is Saas and seccond one is Menu. from Saas i can get everything to template but from Menu i cannot get menu items in html navbar. my project Tree is Picture For Tree Code in Html Template {% for item in Menu_list %} <li class="nav-item dropdown dropdown__megamenu"> <a class="nav-link dropdown-opener" href="#"> {{ item.title }} </a> <div class="custom-dropdown-menu custom-megamenu"> <div class="content"> <ul class="megamenu"> <a href="#">დიზაინი</a> </ul> </div> </div> </li> {% endfor %} Code for Views.Py from django.shortcuts import render from .models import Menu,MenuItem def index(request): Menu_list = Menu.objects.all() MenuItem_list = MenuItem.objects.all() return render(request, 'header-footer.html',{'Menu_list' : Menu_list, 'MenuItem_list': MenuItem_list,} ) -
models.FileField.read csv returns b'0,0,0,0\n1,1,1,1'
I read the file by models.FileField and it returns myModel.document is models.FileField object. f = myModel.document.read() print(f) this might be csv file, but how can I handle this object????? b'0,0,0,0\n1,1,1,1' -
In a need of architectural advice for building a web service
I am currently planning the architecture for a web service that can process imagery using Python logic on a server. I am leaning strongly towards the Mean stack. Do I need to use Flask/Django ontop of the Mean stack or is the Mean stack itself fully interoperable with Python being executed on some kind of server? If so, is Flask good enough of a framework on its own- or do I need to use Django with the following planned features for implementation: Sending and recieving images Manage users Handle payments Handle user data I do admit that I lack certain experience in some of these fields - but I feel like it's a big waste of time to further invest time into making Tic Tac Toe games. Thank you for your time. -
How to use django request object outside of django view
def home(request): return render(request,'index.html') how to use request the request object outside of the view in Django. I want to use request.user in another simple python file in same project. -
"parcella_pk" not okay there, it cause a "ValueError". What should I use?
I don't know what type of data should I use there. With primary key I think is there are no problem. But it's not that what I needed. This is part of my models.py: from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now class Parcella(models.Model): ### user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.parcellanev class Muvelet(models.Model): ### parcella = models.ForeignKey(Parcella, on_delete=models.CASCADE) This is part of my views.py: @login_required def muvelethozzaadas(request, parcella_pk): if request.method == 'GET': return render(request, 'foldmuv/muvelethozzaadas.html', {'form':MuveletForm()}) else: try: form = MuveletForm(request.POST) ujmuvelet = form.save(commit=False) ujmuvelet.parcella = parcella_pk ujmuvelet.save() return redirect('parcellak') except ValueError: return render(request, 'foldmuv/muvelethozzaadas.html', {'form':MuveletForm(), 'error':'Nem megfelelő adat. Kérlek prbáld újra!'}) This is part of my parcellaegy.html: <form method="POST" action="{% url 'muvelethozzaadas' parcella.id %}"> {% csrf_token %} <button type="submit">Hozzáadás</button> </form> -
How to pass Two templates in a same class based views
I am having one issue with the django template view. I am having two urls 1) For Current User Profile 2) For His Team mates urls.py path('profile/', views.UserprofileIndex.as_view(), name='user-profile'), path('profile/<int:pk>', views.TeamProfileIndex.as_view(), name='team-profile'), It's views class TeamProfileIndex(TemplateView): template_name = 'accounts/profile/team_profile.html' def get_context_data(self, **kwargs): context = dict() self.pk = self.kwargs.get("pk") try: user_profile = Profile.objects.get(user=self.pk) except Profile.DoesNotExist: logger.error("Requested user profile not available") raise Http404 teams = User.objects.all() context.update( { 'user_profile': user_profile, 'teams' : teams } ) return context class UserprofileIndex(TemplateView): template_name = 'accounts/profile/index.html' def get_context_data(self, **kwargs): context = dict() try: user_profile = Profile.objects.get(user=self.request.user) except Profile.DoesNotExist: logger.error("Requested user profile not available") raise Http404 teams = User.objects.all context.update( { 'user_profile': user_profile, 'teams' : teams } ) return context In both views only one query is changing , that is 'user_profile'. Is there any way to pass this in a single views to two diffrent html pages ? -
Processing a Django Form in a Celery Task - How can the celery task see the form?
The use case is rather simple. That of a background transaction manager, which requires that this classic type of post handler: class MyCreate(CreateView): model = MyModel fields = '__all__' def post(self, request, *args, **kwargs): self.form = self.get_form() if self.form.is_valid(): self.object = self.form.save(commit=True) return self.form_valid(self.form) else: return self.form_invalid(self.form) doesn't save the form with form.save(), but rather saves the form object somewhere (to the session?) starts a Celery task which will then be responsible for running form.save() The problem I'm facing is that the form object is refusing to serialize at all, with JSON or pickle, it's just too rich an object, and starting a Celery tasks requires the arguments to be serialized. I can serialize just the POST data (request.POST) which is doable, and pass it to the Celery task as an argument which works but I can't from that find any way to reinstantiate a form, let alone a formset. if I want to start the Celery task from a view I redirect to (that implements a progress bar say) then I have the even bigger challenge of passing the form to a whole new Django view. The obvious candidate is to save it to session: self.request.session["my_form_data"] = self.request.POST But … -
Django: how to create dropdown dependancies
I have a dropdown taking distinct values from a database. Depending on the selected value in this dropdown, I want a second dropdown to be updated with other distinct values from the same table. As an example, let's say that I have a table with 'Continents' and 'Countries' fields, if I select 'Europe' for instance, I want the second dropdown to show the countries in my db which belong to this continent. I managed to create the first dropdown and connect it to the db, but I'm struggling with the second step, which is to retrieve the first dropdown's selection and use it to update the second one. Here is my views.py: def MyView(request): query_results = data_world.objects.all() continents_list = ContinentsChoiceField() countries_list = CountriesChoiceField() query_results_dict = { 'query_results': query_results, 'continents_list': continents_list , 'countries_list': countries_list , } return render(request,'home.html', query_results_dict) models.py: class data_world(models.Model): id = models.AutoField(primary_key=True) continent_name= models.TextField(db_column='CONTINENTS', blank=True, null=True) country_name = models.TextField(db_column='COUNTRIES', blank=True, null=True) city_name = models.TextField(db_column='CITIES', blank=True, null=True) class Meta: managed = True db_table = 'world' forms.py: class ContinentsChoiceField(forms.Form): continents = forms.ModelChoiceField( queryset=data_world.objects.values_list("continent_name", flat=True).distinct(), empty_label=None ) class CountriesChoiceField(forms.Form): countries = forms.ModelChoiceField( queryset=data_world.objects.values_list("country_name", flat=True).distinct(), empty_label=None ) home.html: <div class="container"> <form method=POST action=""> {{ continents_list}} </form> </div> <div class="container"> <form method=POST action=""> … -
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>