Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a python drop down box readonly?
How do you make a drop down box in python readonly to only display the previously chosen selection? I already tried putting in a ReadOnlyFormMixin in the classes and that worked for most of the fields. class ReadOnlyFormMixin(ModelForm): def __init__(self, *args, **kwargs): super(ReadOnlyFormMixin, self).__init__(*args, **kwargs) for key in self.fields.keys(): self.fields[key].widget.attrs['readonly'] = True def save(self, *args, **kwargs): # do not do anything pass class ViewPartForm(ReadOnlyFormMixin, ModelForm): description = forms.CharField(label='Description', widget=forms.Textarea(attrs={'rows': 3, 'cols': 35, 'max_length': 800}), required=True) char1 = forms.CharField(label='field2', widget=forms.Textarea(attrs={'rows': 1, 'cols': 25, 'max_length': 800}), required=True) char2 = forms.CharField(label='field3', widget=forms.Textarea(attrs={'rows': 1, 'cols': 25, 'max_length': 800}), required=True) class Manufacturer1Form(ReadOnlyFormMixin, ModelForm): manufacturer = forms.ModelChoiceField(queryset=Vendor.objects.filter(vendor_type='manufacturer').order_by('name')) class Meta: model = Manufacturer1Relationship exclude = ('part',) Putting the ReadOnlyFormMixin worked for the first class but not for the second one. The choice field still lets users change what is selected. -
Django url redirect in form action
I have tried a lot of different things, but I cannot get my action to redirect once my form saves. My loans_form.html: <form action="{% url loans %}" method="post"> {% csrf_token %} {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }}: {{ field }} </div> {% endfor %} <p><input type="submit" value="Submit loan request" /></p> </form> And my urls.py from django.urls import path from .views import LoanListView, LoanCreateView urlpatterns =[ path('', LoanListView.as_view(), name='loans'), path('create', LoanCreateView.as_view(), name='create') ] -
Storing media files on Django with heroku
I'm hosting my dja fo web app with Heroku. I realize that Heroku resets the media files every time the Dyno resets by default. My webapp is very small and I would like to store a few media files on my dja go Heroku app. What would be the easiest and cheapest way to do this ? I'm open to abandoning Heroku completely for another mentor of hosting django web apps that also let's me upload some media files for free. -
how to edit a existing database value in django
I have user profile database(example:-columns like id, First_name, Last_name, Phone Number, Email).I want to display this data into HTML form and user is able to edit the information. Once user submit the edited information it will store in the database in-place of existing user data.Thanks in advanced. -
How to fix " '__proxy__' object has no attribute 'get' " when trying to update wrongly a form
Guys I have a simple book model: class Book(models.Model): isbn = models.CharField(_('ISBN'), validators=[RegexValidator('^[0-9 -]+$', message="ISBN must contains only numbers or hyphens!")] , max_length=13, unique=True) title = models.CharField(_('Book\'s title'), max_length=128) publisher = models.CharField(_('Publisher'), max_length=64) author = models.CharField(_('Author'), max_length=64) pages = models.IntegerField(_('Pages'), default=0) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('books:detail', kwargs={'isbn': self.isbn}) Im coding a crud system and having problem with the UpdateView. This view works properly when I try to do a correct update, but when I insert wrong values (like letters in isbn or letters in pages) I have this error: AttributeError at /books/update/31234-15/ '__proxy__' object has no attribute 'get' This is my view: class BookUpdateView(UpdateView): """Update the requested book.""" model = Book form_class = BookForm def get_object(self): pk = self.kwargs.get(self.pk_url_kwarg, None) queryset = self.get_queryset() queryset = queryset.filter(isbn=self.kwargs['isbn']) if not queryset.exists(): messages.error(self.request, 'This book doesnt exist!') return get_object_or_404(Book, **self.kwargs) return queryset.get() def get_success_url(self): messages.success(self.request, 'The book updated successfully!') return reverse_lazy('books:detail', kwargs = {'isbn': self.object.isbn}) def form_invalid(self, form): messages.error(self.request, 'The update has failed') return reverse_lazy('books:index') and my update url: urlpatterns = [ url(r'^update/(?P<isbn>[\d\-]+)/$', view=views.BookUpdateView.as_view(), name='update'), ] I need to use Django 1.10 in this project idk why. If someone can reccomend me … -
How can i use angular as a frontend for a particular app in a django?
I am using bootstrap in django project as a frontend technology,but now the complication is increased in my project for which i want to use Angular. How can i use angular for a particular app in in django project. I don't frontend and backend on diffrent domains. -
How do I access a model's nested one-to-many relations?
I have three models as shown below: class Restaurant(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200) category = models.CharField(max_length=100, blank=True, null=True) class MenuCategory(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) name = models.CharField(max_length=200) class MenuItem(models.Model): menu_category = models.ForeignKey(MenuCategory, on_delete=models.CASCADE) name = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) A restaurant has many menu categories, which has many menu items. Is this the right way to lay out these relationships? What's the most efficient way to get ALL the menu items for a given restaurant? I'm hoping there's a more effective way than to loop across all menu categories for a given restaurant. -
Django ORM: Select rows by distinct column value
This may sound like a silly question but I just can't figure out how to convert this simple query into django queryset. select distinct locality, id from shootsta_bookings.users_useraddress; I've tried this: @list_route(methods=['GET'], url_path='locations') def locations(self, request, *args, **kwargs): **localities = models.UserAddress.objects.all().values('locality').distinct()** data = self.get_serializer(localities, many=True, context={'request': request}).data return response.Ok(data) But it only returns the distinct values without the ids. Here's my serializer if that helps: class LocationListSerializer(serializers.ModelSerializer): class Meta: model = models.UserAddress fields = [ 'id', 'locality', ] I'm looking for a clean solution without having to filter the queryset with in clause. -
Serializing to namedtuple raises "too many values to unpack"
I would like to use Serializer to validate and deserialize JSON. I've tried: Candidate = namedtuple("Candidate", ["name", "description"] ) class CandidateSerializer(serializers.Serializer): name = serializers.CharField() description = serializers.CharField() def to_internal_value(self, data): return Candidate(**data) And then in the repl : >>> s = CandidateSerializer(data={'name': "Seb", 'description':"Hello"}) >>> s.is_valid() Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py", line 236, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py", line 436, in run_validation self.run_validators(value) File "/usr/local/lib/python3.6/site-packages/rest_framework/serializers.py", line 465, in run_validators to_validate.update(value) ValueError: too many values to unpack (expected 2) What am I doing wrong? -
'BooleanField' object has no attribute 'attrs'
I am getting the error 'BooleanField' object has no attribute 'attrs' I am creating a form to create a new user and save the details in the database searched for a while but no luck {{ field.label_tag }} field.label_tag shows error for bollean field error is this id_ = widget.attrs.get('id') or self.auto_id AttributeError: 'BooleanField' object has no attribute 'attrs' -
Django form submit for multiple urls (or) views
Is there any way to use a submited form data to apply all the view, For example, I have a form in one page, <form method="POST" autocomplete="off" action="{% url 'a_view' %}"> <label for="BookName">BookName</label> <input class="form-control" placeholder="Enter Customer Code" type="text" id="BookName"> <button class="btn btn-primary">Apply</button> And have a other form in another page with same form inputs, <form method="POST" autocomplete="off" action="{% url 'b_view' %}"> <label for="BookName">BookName</label> <input class="form-control" placeholder="Enter Customer Code" type="text" id="BookName"> <button class="btn btn-primary">Apply</button> From this form I get a text for filtering the data for different models,after I have to send to the different view. what I want to do is, when the form is applied,it should apply the form to all the views in my app. Please help me to sort out, Thanks. -
Issues setting up Apache config to serve /static Django files with Gunicorn proxy
As the title says, I'm having difficulty getting Apache setup correctly to serve Django static files in production with a Gunicorn proxy for the backend. I'm finding that when I switch DEBUG = False that the app quits working with: < unexpected token. Reading about it, it has to do with the use of STATIC_ROOT being incorrect. I have my STATIC_ROOT = os.path.join(BASE_DIR, 'static'), and I'm running python manage.py collectstatic which is collecting all the assets to /static in the project root. Then I run gunicorn wsgi -D in the same directory as wsgi.py. Anyway, this is how the Apache configs are setup: HTTP: ServerName www.website.com ServerAlias website.com Alias /static /home/website/src/static ### Redirect http to https RewriteEngine On # This will enable the Rewrite capabilities RewriteCond %{HTTPS} !=on # This checks to make sure the connection is not already HTTPS RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L] # This rule will redirect users from their original location, to the same location but using HTTPS. # i.e. http://www.example.com/foo/ to https://www.example.com/foo/ # The leading slash is made optional so that this will work either in httpd.conf # or .htaccess context HTTPS: ServerName www.website.com ServerAlias website.com Alias /static /home/website/src/static ProxyPreserveHost On ProxyPass / http://localhost:8000/ retry=5 ProxyPassReverse … -
How to import images from body of DetailView and use it as thumbnail in ListView/?
I have a form that allows user to add a title and content for their posts. In content they can upload pictures using tinymce editor like: forms.py: class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class BlogForm(forms.ModelForm): title = forms.CharField() content = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 20, 'rows': 10} ) ) image = forms.ImageField() class Meta: model = BlogPost fields = [ 'title', 'content', 'image' ] How do I use this picture as thumbnail in ListView. Please help me do it. Thank you so much. -
How to execute code in Django after response has been sent to the client (on PythonAnywhere)?
I'm looking for a way to execute code in Django after the response has been sent to the client. I know the usual way is to implement a task queue (e.g., Celery). However, the PaaS service I'm using (PythonAnywhere) doesn't support task queues as of May 2019. It also seems overly complex for a few simple use cases. I found the following solution on SO: Execute code in Django after response has been sent to the client. The accepted answer works great when run locally. However, in production on PythonAnywhere, it still blocks the response from being sent to the client. What is causing that? Here's my implementation: from time import sleep from datetime import datetime from django.http import HttpResponse class HttpResponseThen(HttpResponse): """ WARNING: THIS IS STILL BLOCKING THE PAGE LOAD ON PA Implements HttpResponse with a callback i.e., The callback function runs after the http response. """ def __init__(self, data, then_callback=lambda: 'hello world', **kwargs): super().__init__(data, **kwargs) self.then_callback = then_callback def close(self): super().close() return_value = self.then_callback() print(f"Callback return value: {return_value}") def my_callback_function(): sleep(20) print('This should print 20 seconds AFTER the page loads.') print('On PA, the page actually takes 20 seconds to load') def test_view(request): return HttpResponseThen("Timestamp: "+str(datetime.now()), then_callback=my_callback_function) # This … -
models relationship whether to use foreignkey or onetomany
I'm making a blog that has collection of my favorite videos for fun. # I want to categorize the videos class blog(models.Model): name = models.CharField(max_length=255) #name can be dogs, cats, cars relatedVideo = models.ForeignKey(video, on_delete=models.CASCADE) class video(models.Model): name = models.CharField(max_length=255) #the video name description = models.TextField() am I connecting them right? -
how can i use urls properly always showing import error
want to build blog application following by the tutorials but urls show some import error as cannot import name URLs from django.contrib import admin from django.conf.urls import include,url app_name='blog' namespace='blog' urlpatterns = [ url('admin/', admin.site.urls), url(r'^blog/',include('blog.urls',)), ] -
Django Error in Django Setting File - TypeError: expected str, bytes or os.PathLike object, not tuple
I am using Django for a project. I am getting this error --> TypeError: expected str, bytes or os.PathLike object, not tuple. It indicates that line 17 in my setting.py file. The code in line 17 is as below. 14: import os 15: # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 17: TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') Any suggestion? -
AttributeError at /registration/list/ 'str' object has no attribute 'get'
I am trying to display the records on the basis of login users and receive AttributeError: 'str' object has no attribute 'get' error with below codes. Would someone please tell me how to fix it? Thank you. class ListRegistration(LoginRequiredMixin, FilterView): model = models.NewRegistration template_name = 'registration_list.html' context_object_name = 'registrations' paginate_by = 10 def get_queryset(self): user_id=self.request.user.id profile_qs = Profile.objects.filter(id=user_id).values_list("user_id", flat=True) return models.NewRegistration.objects.filter(is_forwarded=False,user_id=user_id).order_by('-id') -
Django 'Query' object has no attribute 'contains_column_references'
As i'm tring to insert some data using POST request into mysql dataBase i'm getting an error informing me that AttributeError 'Query' object has no attribute 'contains_column_references' it gives error at: contents = Contents.objects.create(content=request.POST['content'],lesson_id_id=lessons,material_title=request.POST['material_title'] from django.db import models from lessons.models import Lessons from django.utils.datastructures import MultiValueDictKeyError class Contents(models.Model): material_title = models.TextField() content = models.TextField() lesson_id = models.ForeignKey(Lessons,on_delete= models.CASCADE) The following code gets the POST request parameters and inserts it into the database def create_content(request): print("=================== create_content=============================") if request.method == 'POST': if request.POST['lesson_id'] and request.POST['content'] and request.POST['material_title']: if request.POST['lesson_id']!='' and request.POST['content']!='' and request.POST['material_title']!='': ls = Lessons.objects lessons = Lessons.objects.filter(id=request.POST['lesson_id']) contents = Contents.objects.create(content=request.POST['content'],lesson_id_id=lessons,material_title=request.POST['material_title']) # contents.save() print("=======================") topic = Courses.objects.filter(userId=request.user) materialsbylesson = Lessons.objects return render(request,'contents_create.html', {'error':'Lesson Has been created successfully','topics':topic,'lessons':materialsbylesson}) else: print("not all Available else statement3") topic = Courses.objects.filter(userId=request.user) materialsbylesson = Lessons.objects wikidata = Wikidata.objects return render(request,'contents_create.html', {'error':'Lesson Has been created successfully','topics':topic,'lessons':materialsbylesson}) else: print("not all Available else statement2") print(request.POST['content']) topic = Courses.objects.filter(userId=request.user) materialsbylesson = Lessons.objects wikidata = Wikidata.objects return render(request,'contents_create.html', {'error1':'some inserted data is missing','topics':topic,'lessons':materialsbylesson}) else: # user = User.objects.get(username = request.POST['username']) try: # MARK get topics by user # MARK get lessons by topic print("==================================not post request") topic = Courses.objects.filter(userId=request.user) lessonsByTopic = Lessons.objects lessonsByUser = [] for topicls in topic: lessons_hierarchy = … -
Developing shopping cart with sessions in django
I want to create shoppig cart. I use a lot of my code from "Beginning Django E-Commerce" book (author: Jim McGaw). Code errors have been fixed and the system is almost ready so that it can be used as a complete project for the shopping cart. However, it is still not complete and there are problems that I will continue to discuss. For now, see my files: urls.py app_name = 'shop' urlpatterns = [ path('product/', views.all_product, name='all_product'), path('product/<slug:slug>/', views.single_product, name='single_product'), path('cart/', views.show_cart, name='show_cart'), ] Views.py def single_product(request, slug): p = get_object_or_404(Product, slug=slug) # need to evaluate the HTTP method if request.method == 'POST': # add to cart…create the bound form postdata = request.POST.copy() form = ProductAddToCartForm(request, postdata) # check if posted data is valid if form.is_valid(): # add to cart and redirect to cart page add_to_cart(request) print("************^^^^(((((((((((") # if test cookie worked, get rid of it if request.session.test_cookie_worked(): request.session.delete_test_cookie() return redirect('show_cart') else: # it’s a GET, create the unbound form. Note request as a kwarg form = ProductAddToCartForm(request=request) # assign the hidden input the product slug form.fields['product_slug'].widget.attrs['value'] = slug # set the test cookie on our first GET request request.session.set_test_cookie() template = 'shop/client_shop/single_product.html' context = {'product': p} return render(request, template, … -
Compare Two String With Optional Characters
consider we have a function (in Django || python) which compares two strings, one is the correct answer and another is student answered string. correct = '(an) apple (device)' student_answerd = 'apple device' I want to check student_answered with the correct string but parentheses are optional it means all the below student_answered is correct: case 1: an apple device case 2: an apple case 3: apple device notice: we don't have the same correct format for all questions it means the location of parentheses is different for example maybe we just have one parentheses or more. -
Query in geodjango only accepts numeric values
I've done a query with GeoDjango to show the places closest to the user, but it is returning the following error: Only numeric values of degree units are allowed on geodetic distance queries. My model looks like this: class Local(models.Model): location = models.PointField() My query: user_location = Point(latitude, longitude, srid=4326) Local.objects.filter(location__distance_lt=(user_location, D(m=500))) I am using MySQL as database Anyone know how I can solve this? -
how to do async task in django?
Suppose I need to request multiple servers to make a response def view_or_viewset(request): d1 = request_a_server() # something like requests.get(url, data) d2 = request_b_server() d3 = request_c_server() return Response({"foo1": d1, "foo2": d2, "foo3": d3}) I'm doing synchronous requests for each request, and I guess there must be a better way of handling this kind of scenario.. (I would use celery if it is long task, but it is not, still doing multiple synchronous requests doesn't seem right) What's the recommended paradigm (?) of handling this? -
How to fix "react-dom.development.js:287 Uncaught TypeError: Cannot read property 'setState' of undefined"
I am trying to upload my react forms to the state so I can fetch an API with those credentials I have tried creating a function that looks like this: handleEmail(event) { this.setState({email: event.target.value}); } handlePassword(event) { this.setState({password: event.target.value}); } render() { return ( <div> <NavBar /> <form className="pt-6 container"> <div className="form-group"> <label className="mt-6" >Your email</label> <input name className="form-control" onChange={this.handleEmail} placeholder="Email" type="email" /> </div> {/* form-group// */} <div className="form-group"> <a className="float-right" href="#">Forgot?</a> <label>Your password</label> <input className="form-control" onChange={this.handlePassword} placeholder="******" type="password" /> </div> {/* form-group// */} -
Blog Project: has no column named post_id. What might be the problem?
Simple project and I believe its a trivial error, but can't find it. Getting the following error: table blog_blogcomment has no column named post_id Where to add that post_id? Thank you for all the comments views.py: def post_detail(request, post_id): single_post = get_object_or_404(BlogPost, pk=post_id) single_post.views += 1 single_post.save() form = BlogCommentForm(request.POST) if request.method == 'POST' and request.user.is_authenticated: if form.is_valid(): comment = form.save(commit=False) comment.post = single_post comment.save() return redirect(post_detail, post=single_post) else: form = BlogCommentForm() context = {'single_post': single_post, 'form': form} return render(request, 'post_detail.html', context) models.py class BlogComment(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) post = models.ForeignKey(BlogPost, related_name='comments') comment_text = models.TextField() date_commented = models.DateTimeField(default=timezone.now) post_detail.html {% block features %} <h1>{{ single_post.title }}</h1> <p>Posted by: {{ single_post.author }} on {{ single_post.date_posted }} </p> <p>{{ single_post.text }}</p> <p>{{ single_post.views }}</p> {% if user.is_authenticated %} <a href="{% url 'add_comment' single_post.id %}">Leave a comment</a> {% else %} <p><a href="/accounts/register">Register</a> or <a href="/accounts/login">Log-in</a> to comment </p> {% endif %} {% for comment in single_post.comment.all %} {{ comment.comment_text }} {% empty %} <p>There are no comments yet. Be the first</p> {% endfor %} <h3>Post a comment</h3> <form method='POST'> {% csrf_token %} {{ form | as_bootstrap }} <button type="submit">Submit</button> </form> {% endblock %}