Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin custom action request
I've written a custom action and through model permissions have granted these to 2 users but now only want one of them to run it at any one time. So was thinking whenever they select the actionbox and press the action button it checks if a request.POST is already being made. So my question is can I interrogate if there any other http requests made before it takes the user to the intermediary page and display a user_message.....without having to mine the server logs. -
How to remove whitespace around a character in a Django Template?
I have a template that looks like this: ({% if condition_a %} <a href="{{ link_a }}" role="button">Add</a> {% endif %} {% if condtion_a and condition_b %} | {% endif %} {% if condition_b %} <a href="{{ link_b }}">Edit</a> {% endif %}) I was hoping it would render with the parentheses next to the words. For example, in the case of condition_a: (Add) But due to the way html handles line breaks, the page is rendered like this: ( Add ) The same is true for the other conditions (ie. condition_a and conditon_b): Expected: (Add | Edit) Result: ( Add | Edit ) I tried adding the Django spaceless tag, but that didn't work as it only strips whitespace around html tags. I could jam a few more if statements in to my code, but would prefer not to. I also tried adding white-space: nowrap; to the a tags in the css but that failed as well. Is there any way I can trim the whitespace around words? -
404 error for file initiated by vendor.js while integrating Angular with django
I get the following error message in browser console when I try to integrate my angular front end with django. GET http://127.0.0.1:8000/assets/another.js 404 (Not Found) I believe I have configured static file settings in django correctly as it is able to locate all the other static files, ie main.js, polyfills.js, vendor.js etc. This assets/another.js call initiated by vendor.js. I have all these files in the same static dir. When I run python manage.py findstatic --verbosity 2 assets/another.js I get the following response - Found 'assets/another.js' here: /home/path/to/project/server/static/assets/another.js Looking in the following locations: /home/path/to/project/server/server/static /home/path/to/admin/static # irrelevant in this case -
How to restrict an access to media files in Django on a production environment for anonymous users?
I need to restrict an access to media files in Django (1.11) on a production environment for anonymous users. I found this snippet and it looks like what I want, but I need to use mod_wsgi with apache2. Is that possible and how could it be accomplished? Apache config: Alias /static /home/user/myproject/static <Directory /home/user/myproject/static> Require all granted </Directory> Alias /media /home/user/myproject/static <Directory /home/user/myproject/static> Require all granted </Directory> <Directory /home/user/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-home=/home/user/myproject/myprojectenv python-path=/home/user/myproject WSGIProcessGroup myproject WSGIScriptAlias / /home/user/myproject/myproject/wsgi.py -
Django How to send my db data to zapier?
I am beginner in django . i read the docuemntation of rest api . kindly please tell me how to send my model detail to zapier and how to make rest api and configuration. -
Issue with using Django context variables in template CSS
I don't know it can be write like that or not but I am trying to set height to html item in css style. Height is being passed in context variable from Backend Django. I am trying this: <style> .fc-agendaWeek-view tr { height: '{{row_height|add:"0"}}'"px" } </style> {{row_height|add:"0"}} => this is context variable passed from Django Backend which is integer i-e 70 , 80. Where I am wrong? Can we even write like that. Any help will be appreciated. -
How do I serialize a class with Django and non-Django properties for Json ajax output?
Lets say have this object: class Zoo: def __init__(self, animal): self.animal = animal # a Django Model Animal object self.list_of_sounds = [] # type: list[a Django Model Sound Object] self.add_sounds() def add_sounds(self): for id in list(range(0, 5)): AnimalSound(animal_id=id, noise='woof') self.list_of_sounds.append(AnimalSound) animal = Animal.objects.filter(pk=1).first() zoo = Zoo(animal) json_to_output_via_ajax = serializers.serialize('json', [zoo]) This throws an error: {AttributeError}'Zoo' object has no attribute '_meta' because zoo has a the property list_of_sounds which is not a Django object. What is the best way to send this object's json via ajax? -
Wagtail: Creating Recurring Events from Event page
I am creating a Wagtail site with an Events component. Some of these events are recurring, with the only difference being the start and end dates/times. I have created a Recurring Events Orderable that is bound to the Event model (which extends from Page), with start and end dates/time fields. Is there a way to automatically create a new Event page for each recurring event when the main Event page is published? So, if I had an Event page, and added 2 Recurring Events to it, how can I take some of the data from the main Event page (like title, location, etc.), combine it with the date/time from the Recurring Event Orderables, and instantiate 2 more Event pages besides the main Event page when published? -
Check the existence of instance with Django ManyToManyField
Hello Awesome People! How to check whether a similar record is already in database with ManyToManyField(): class Room(): created_by = models.ForeignKey(User) allowed_users = models.ManyToMany(User,related_name='rooms_as_guest') is_active = models.BooleanField(default=True) In my view before creating a new room, I want to make sure there's wasn't an active room with exactly the same participants. The following example won't work, it's just to show you what I expect allowed_users = User.objects.filter(id__in=request.POST.get("ids",[])) if allowed_users: Room.objects.get_or_create( created_by = request.user, allowed_users = allowed_users, # won't work is_active = True, ) How could I proceed to do what I want? -
Failed to load resource: the server responded with a status of 502 (Bad Gateway)
How can you solve a 502 error? I purposefully put a syntax error in my code to spot what line of code is causing the 502 error. (if the 502 error is caused before the syntax error it means the line causing the 502 is before the line of code containing the the syntax error) I believe whats causing the 502 error is a nested loop that contains heavy calculations. It would take up to 2 minutes for it to finish that block of code on my local server. However on a public server I just get this 502 Bad Gateway nginx/1.10.3 (Ubuntu) My site is made with django. I am also using numpy (i installed it on the public server), js, html, and css. Any ideas for where to start looking to solve this error? -
how to make a form to take dynamic number of inputs from user in django giving dynamic number of form fields
i need forms.Form not forms.ModelForm...because saving to model is not required. class form_name2(forms.Form): a1 = forms.CharField(widget=forms.TextInput(),max_length=100,label="1",required=False) a2 = forms.CharField(widget=forms.TextInput(),max_length=100,label="2",required=False) a3 = forms.CharField(widget=forms.TextInput(),max_length=100,label="3",required=False) -
How to include delete function in UpdateView instead a DeleteView
I have a UpdateView for editing a post, but instead of making a DeleteView for delete a post, i try to make UpdateView include a function to delete the post. So ,i want to edit and delete a post in UpdateView. Is that possible ? i think i missing something in my code so the code keep getting error. views.py class PostUpdate(LoginRequiredMixin,generic.UpdateView): model = PostModel fields = ['title','file','description'] template_name = 'post/post_update.html' success_url = reverse_lazy('user_profile:profile') def form_valid(self, form, pk): if 'confirm_post' in self.request.POST: form.instance.user = self.request.user elif 'confirm_delete' in self.request.POST: post_delete = PostModel.objects.get(pk = id) post_delete.delete() return super(PostUpdate, self).form_valid(form) urls.py from django.conf.urls import url from . import views from django.urls import path app_name = 'post' urlpatterns = [ url('user_post/', views.PostView.as_view(), name= 'user_post'), url('post_list/', views.PostList.as_view(), name='post_list'), path('<int:pk>', views.PostDetail.as_view(), name= 'post_detail'), path('update/<int:pk>/', views.PostUpdate.as_view(), name= 'post_update'), ] post_update.html {% extends 'base.html'%} {% load bootstrap3%} {% block content %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form%} <input type="submit" name="confirm_post" value="Confirm"> <input type="submit" name="confirm_delete" value="Delete"> </form> {% endblock %} -
Django Like function with ajax
First of all : I already checked all the related answers and questions .... they didn't help me so I am trying to create ajax based like button with multiple users and multiple objects or posts i tried a lot but none of them works but i steel have the base models.py: class BlogPost(models.Model): #some fields class Like (models.Model): user = models.ForeignKey(User) post = models.ForeignKey(BlogPost) views.py from .models import Like def PostLikeToggle(request): #here i want to capture the request check if the user liked the post or # no by sending user.username and post.title to the endpoint like.html #and then update his status return render(request, 'like.html') urls.py from plateform import views as plateform urlpatterns = [ #other urls url(r'^like/', plateform.PostLikeToggle, name='PostLikeToggle'),] like.html {% if liked == 'false' %} false {% elif liked == 'true' %} true {% endif %} blogpost.html #ajax $('.thumb').click(function () { $.ajax({ type: 'POST', url: '/like/', data: { 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(), }, success: LikePost, dataType: 'html' }); function LikePost(data, jqXHR) { console.log(data) } }); -
Overwrite parent model attribute from child model
I have the following model parent class ModelParent(PolymorphicModel): company = models.CharField(max_length=50) ....... and the model child class ModelChild(ModelParent) company = models.CharField(max_length=10, blank=True) ........... how can I make the model child company attribute overwrite the parent company model attribute without making the abstract parent model -
Filter data in Many-to-Many relationship
I have the following two models: class Creator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # ... more fields here class Content(models.Model): title = models.CharField(max_length=100) # ... more fields here and I create a Many-To-Many relationship between them by using the following model: class ContentCreator(models.Model): content = models.ForeignKey('Content', on_delete=models.CASCADE) creator = models.ForeignKey('Creator', on_delete=models.CASCADE) Now, in my ListView, I want to retrieve a QuerySet that contains all the Content items of a Creator (the authenticated user in this case): class ContentListView(ListView): model = Content def get_queryset(self): content_creator = ContentCreator.objects.filter(creator=self.request.user.creator) qs = super().get_queryset().filter(?????) return qs What do I use in the qs filter? I was looking at __in lookup and I could get a list of all the PKs of Contents from content_creator, then filter using pk__in like this: content_creator = ContentCreator.objects.filter(creator=creator) content_creator_pks = content_creator.values_list('pk', flat=True) qs = super().get_queryset().filter(pk__in=content_creator_pks) But I feel like I do too many operations and I make it more complicated than necessary. Is there a better/easier way to achieve what I want? -
Django and Cropper; Cropped Image cannot be uploaded on AWS S3
I'm creating a project using Django and I was trying to adapt cropper into my project. I was following this tutorial https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html but I found out the cropped image cannot be uploaded on S3 and the original image is shown up. What is wrong with it and how can I fix this? views.py def edit_profile_image(request): try: image = ProfileImage.objects.get(user=request.user) except: image = None if request.method == 'POST': form = EditProfileImageForm(instance=image, data=request.POST, files=request.FILES) if form.is_valid(): resized_image = form.save(commit=False) resized_image.user_id = request.user.id resized_image.save() return HttpResponseRedirect(reverse_lazy('blog:my_profile')) else: form = EditProfileImageForm(instance=image) return render(request, 'blog/edit_profile_image.html', {'form': form, 'image': image}) forms.py class EditProfileImageForm(forms.ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = ProfileImage fields = ('file', 'x', 'y', 'width', 'height', ) def save(self, *args, **kwargs): photo = super(EditProfileImageForm, self).save(*args, **kwargs) x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(photo.file) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) resized_image.save(photo.file.name) return photo -
Generate Google Calendar link from django app
How do i generate a Google Calendar link from django 1.11 application. I am getting the events from an API(meetup.com).I want the users to be able to add the events to their google calendar -
Django button to send emails
How would you go about creating a button in your templates of an app in Django. I have a script in my views.py: def my_python_script(request): if request.is_ajax: # stuff here else: return HttpRequest(status=400) But how do I actually turn this into a button? Is there some html or css I need to put somewhere? I saw some things about a templates directory in the application but I'm unsure on what things to put there and in what formats. -
Django redirect after ajax on the server
What is the best way to redirect on the server after an ajax request in django. Say I have this view function that receives an ajax call def view(request): if request.is_ajax(): do_something() # This function does something on the server return redirect('') # Redirect back to the same view's get It seems like the server redirects but on the client side the browser is not refreshed because the post method was through Ajax. I have some ideas in mind but they may not be so optimal. Is there an optimal way to go about this? Thanks. -
Google drive access from django-python
In Django am implemented social login using social auth app Django and I followed this link to configure https://hashedin.com/blog/a-guide-to-using-social-login-with-django/. Goolge OAuth is working good. google-oauth2 access token is stored in extra data field. Now I want to list google drive files using this access token. I tried with this. def drive(request): user = request.user social = user.social_auth.get(provider='google-oauth2') response = requests.get('https://www.googleapis.com/auth/drive.metadata.readonly',params={'access_token': social.extra_data['access_token']}) print(response) return render(request,'home/drive.html',{'checking':response} Am getting a Response [200] but I don't know how to list files.Am using django version 2.0.3 and python version is 3.5 -
Django-table2 : Link Column
TypeError at /customers/ for linkify=True, '9887' must have a method get_absolute_url Request Method: GET Request URL: http://127.0.0.1:8000/customers/ Django Version: 2.1 Exception Type: TypeError Exception Value: for linkify=True, '9887' must have a method get_absolute_url Exception Location: G:\Python\Python36_64\lib\site-packages\django_tables2\columns\base.py in compose_url, line 116 -
Django - print length of dict in template
I believe this one will be very basic. I am trying to show the number of values in a dictionary on a template. Here is my method for the template route: # url: localhost/books/home/ def books_home(request): if request.method == "GET": first_name = User.objects.get(id=request.session['uid']).first_name last_name = User.objects.get(id=request.session['uid']).last_name email = User.objects.get(id=request.session['uid']).email user_id = User.objects.get(id=request.session['uid']).id reviews = Review.objects.filter(created_by=request.session['uid']).order_by("-created_at")[:3] context = { 'first_name' : first_name, 'email' : email, 'last_name' : last_name, 'reviews' : reviews, } return render(request, 'html_files/home.html', context=context) Then the pertinent code in the template: <div class="container"> <div class="card"> <h3>Information for {{ first_name }} {{ last_name }}</h3> <p>email: {{ email }} </p> <p>Number of reviews: {{ len(reviews) }}</p> </div> <div class="card"> <h3>Your recent reviews:</h3> {% for review in reviews %} <p>Review for: <a href="/books/book/{{ review.book.id }}/">{{ review.book.title}}</a> by {{ review.book.author.first_name }} {{ review.book.author.last_name }} <br><br> Your review: {{ review.comments }} <br><br> Your rating: {{ review.rating }} out of 5</p><br><br><br> {% endfor %} </div> I thought that {{ len(reviews }} would do it, since as you can see below, "reviews" has been successfully passed to the context dict. But I am getting a "could not parse remainder" error. Your help is appreciated. -
Django API REST framework - VIEWS/SERIALIZERS
I have to do a REST API in Django, but I have several questions. I do not even know if I should use Class Based Views, Viewsets or other. My main question is how to use the Serializers and Views. First, I need to allow a specific attribute (not all) to be edited by a superuser, but not by other users. Second, I need to delete an item if I am the owner of the item or an administrator. My experience with Django is few. Thanks -
Load data into DataTable in Django
So I have been working on this small project which involves loading data from the server as json response and loads into the DataTable. The thing is the JSON response is not compatible with the DataTable and does not load. Image - Empty DataTable These are my code snippets which I think would help debug. Model.py class ErrorData(models.Model): module_id = models.ForeignKey(ModuleData, to_field='module_id', on_delete=models.CASCADE) error_id = models.CharField(max_length=10,unique=True,default=timezone.now) error_name = models.CharField(max_length = 1000) error_description = models.CharField(max_length = 1000) error_mitigation = models.CharField(max_length = 1000) link_valid = models.BooleanField(default=False) screenshot_link = models.CharField(max_length = 1000) author = models.CharField(max_length = 1000) error_validated = models.BooleanField(default=False) error_validator = models.CharField(max_length = 1000) editors_list = models.CharField(max_length = 1000) def __str__(self): return "%s" % (self.error_name) class Meta: ordering = ('error_id',) verbose_name = "Error Data" verbose_name_plural = "Error Data" View.py def ajax(request): sample_data = ErrorData.objects.all() context = { 'sample_data' : serializers.serialize("json", sample_data), } return render(request, 'sample/ajaxTrial.html', context) Result.html <div class="container"> <div class="row table-responsive"> <table class="table table-striped table-bordered" style="width:100%" id="dataTable" data-order='[[ 0, "asc" ]]' data-page-length='5'> <thead> <tr> <th>module_id</th> <th>error_id</th> <th>error_name</th> <th>error_description</th> <th>error_mitigation</th> <th>link_valid</th> <th>screenshot_link</th> <th>author</th> <th>error_validated</th> <th>error_validator</th> <th>editors_list</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script> var jsErrorData = {{sample_data|safe}} console.log(jsErrorData) // advanced search modal $(document).ready(function () { // table pagination $('#dataTable').DataTable({ "pagingType": "full_numbers", … -
Django2.0 urls.py conversion from url() to path()
I am trying to convert the URL below to a path format I could nt find a proper way can you help me? url(r'^profile/<int:pk>/$', views.profile, name='profile_with_pk'), I am currently using dango2.0 and want to convert into path format