Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Downlodable pdf files in django
i am developing a web page where users should able to download a PDF forms or file.is it possible in Django, like normal HTML? i have tried bit it's not working for me. thank you in advance. here is my modle class Notice(models.Model): SL_no= models.IntegerField() Description = models.TextField() Date = models.DateTimeField(default=timezone.now) File = models.FileField(upload_to='files') -
Is it considered good practice using too many factories in pytest?
I am trying to write tests for Django/DjangoREST project. I have decided to use pytest. I have poor experience in writing tests for Django projects specifically. So I am confused now. Here is an example: @pytest.mark.django_db def test_some_view( api_client, simple_user, model1_factory, model2_factory, ... # many other model factories modelN_factory ): # ... # creating here other objects that really depends on each other # ... model2_obj = ... # model2 object on its own side depends on model3, model4... and so on model1_objs = [] for i in range(10): model1_objs.append(model1_factory(some_field=100, some_model2_rel=model2_obj) assert len(model1_objs) == 1, "Created items with duplicate `some_field`" As you can see I have too many factories to be used in one test. But looking at my model structure right now, I can't think of a better way. Is it ok to use so many factories for one test? Or should I find some issues related to my tables' relations? Any help is appreciated. Thanks in advance -
Have problem to auto create profile after register new user in django the error show this 'Manager' object has no attribute 'created'
Django show AttributeError at /ezz/register/ (this is my url) 'Manager' object has no attribute 'created' signals.py files from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.created(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() apps.py file from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals -
Django password_change gives an error on Heroku but not on localhost
I deployed my Django app on Heroku. I'm using the default password_change route from Django admin to allow the users to change their password but the problem is that whenever I go to change the password I get the following error "Connection closed without response". If I go and change a password on localhost then it works. -
How to correctly configure for page refresh with Vuejs frontend served by nginx proxying to gunicorn + django?
I have a production set up as follows; Django REST Framework backend Vuejs frontend Docker container that builds Vuejs for production and copies to Django Docker container /static/ and /template/ folders nginx reverse proxy to handle incoming requests Everything works fine when I navigate to home page (no backend API calls on homepage) and then navigate around the SPA using the navigation drawer. I start to get problems when I try to go directly to a Page in the SPA. The backend API requests fail, the response is HTML (I would have expected JSON) and it displays the message from my index.html (SPA page) that javascript is not enabled (the message withing the <noscript> tags). I have seen some people suggest this is related to Vue router being in history mode, which I would like to keep. The main suggested remedy is to add try_files $uri $uri/ /index.html; as a catch all to the nginx config. However, as I am simply proxying all requests to Django to handle the initial stage of routing, and I already have a catch all in my urls.py file (re_path(r"^.*/$", TemplateView.as_view(template_name="index.html"), name="frontend")) then I think I have this covered. Why would the API requests (which … -
Why django temlate if statement works wrong?
I am using Django 3.1.0 and i have problem with the below if statement. {% if group == "TEACHER" %} {% include "staticPages/components/teacher_dash.html" %} {% else %} {% include "staticPages/components/student_dash.html" %} {% endif %} the group variable stored the name of user.Groups.objects.first().name as string. While the group variable is equal to TEACHER it runs the forth line instead of the second line. I have tried printing out the group variable and copying it to the if condition but it did not worked. Every answer would be appreciated. -
how to use jinja2 in Django 3.1
Now I am using the Django 3.1 template engine but I am not satisfied with it. But I see that jinja2 template engine is very powerful that it. Thought Django says it has support for jinja2 template engine and I was following this Django documentation, but I couldn't use that. So, please tell me how do I do it? -
Subset of Django Group model in Form
I have a model for an event which contains the user and a group. curr_User = settings.AUTH_USER_MODEL class CoronaEvent(models.Model): #query_set = Group.objects.filter(user=curr_User) user = models.ForeignKey(curr_User, default=1, null=True, on_delete=models.SET_DEFAULT, related_name='group') group = models.ForeignKey(Group, on_delete=models.CASCADE) title = models.CharField(max_length=120) description = models.TextField(null=True, blank=True) slug = models.SlugField(unique=True) event_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Within my form (I use crispy forms) I want to only offer the list of groups, the current user is member of. After selecting a group I want to save the result. What I currently have achieved is to pass the group list from current user (request.user.groups.all() to my form and set the list (by using value_list()) as choices for the choisefield. But than Django is not able to save the results because the model expects an instance of group instead of the couple. How can I achieve two use a subset of group in my choices and save the selected group? -
I dont understand why my django signals isnt creating object into database
Im trying to build a notification app where a user follows another user, they get notified in a notification page, my problem now is that i don't understand why the signals isnt creating an object into the notification model database. Please help. Heres the code Models: class Notification(models.Model): assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notifications_assigned_to_user") group = models.CharField(max_length=2, choices=notification_types, default='N') creation_date = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) body = models.TextField(default='No Description') pk_relation = models.IntegerField(blank=True, null=True) def __str__(self): return f"For: {self.assigned_to.username} // id: {self.id}" Signals.py: @receiver(post_save, sender=Follow) def create_notification(*args, **kwargs): follow = kwargs['instance'] if kwargs['created']: # if task.created_by != task.assigned_to: if follow.follow_user != follow.user: Notification.objects.create( assigned_to = follow.user, group='NF', body=f"{follow.follow_user} followed you! ID: {follow.id}", pk_relation=follow.id ) else: # if follow.created_by != task.assigned_to: if follow.follow_user != follow.user: if follow.follow_user != follow.old_instance.follow_user: Notification.objects.create( assigned_to = follow.user, group='NF', body=f"{follow.follow_user} unfollowed you.", pk_relation=follow.id ) @receiver(post_save, sender=Notification) def send_notification_info(*args, **kwargs): if kwargs['created']: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( f"notification_group_{kwargs['instance'].assigned_to.id}", { 'type':'notification_info' } ) Please help. Im not too good, i feel i have left something out -
render_to_string seems to remove value of an variable
I am creating a like unlike button in Django and I ran into a wall. I am using ajax grab id and post to render to string. When button gets clicked first time everything is fine but render_to_string does not return value attr. And I have no idea why? def in views I have: def like_post(request): # post = get_object_or_404(Post, id=request.POST['post_id']) id = request.POST.get('id') post = get_object_or_404(Post, id=id) # check if this user already is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True context = { 'is_liked': is_liked, 'value': id, } if request.is_ajax(): html = render_to_string('post/like_section.html', context, request=request) print("=====4======") print(context) print("=====4======") return JsonResponse({'form': html}) section where this is being rendered: <div id="like-section"> {% include 'post/like_section.html' %} </div> my jquery $(document).on('click', '#like', function(e) { e.preventDefault(); var id = $(this).attr("value"); var url = '{% url "like_post" %}'; $.ajax({ type: 'POST', url: url, data: { id: id, csrfmiddlewaretoken: '{{ csrf_token }}' }, dataType: 'json', success: function(response) { $('#like-section').html(response['form']) }, error: function(rs, e) { console.log(rs.responseText) } }); }); section that is being rendered <form action='{% url "like_post" %}' method="post"> {% csrf_token %} {% if is_liked %} <button name="post_id" class="likes" id="like" type="submit" value="{{ Post.id }}" like-count="{{ Post.likes.count }}">click 1</button> {% … -
Calling a JS function from iterated objects on pageload
Good evening, I want to set my progressbars dynamically through Javascript by replacing the width value to the calculated percentage. I am running Django with a Postgres DB. Now I can set the styling just fine through a JS function but how would I have the function trigger at pageload? Through the view I can pass the relevant number of votes for the iterated object (poll_product) and the total nr of votes. Those two I'd like to pass to my JS function as arguments, so I can calculate the percentage there and set it. I hope I explained it clearly enough, but please ask away for anything I need to elaborate on. {% for poll_product in poll_product_list %} <form action="{% url 'add_vote' poll_product.id %}" method="POST"> {% csrf_token %} <div class="row mt-1"> <div class="col-8"> <h5>{{ poll_product.product_type }} : {{ poll_product.votes }}</h5> </div> <div class="col-4"> {% if user.is_authenticated and not voted %} <input type="submit" class="btn-sm btn-dark" value="Vote"> {% endif%} </div> /* ------------ below is the relevant part ---------------- */ <div class="col-6 progress"> <div id="progressBar{{poll_product.id}}" class="progress-bar" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div> </div> </div> <input type="hidden" name="redirect_url" value="{{ request.path }}"> </form> {% endfor %} -
Select a valid choice. ... is not one of the available choices
Hello fellow Django enthusiasts, I am trying to create a simple Django 2.2 application with single model, single model form + custom field and a simple CreateView. I am populating the choices dynamically based on a http call to a outside url. The dropdown is populated fine, but when I try to submit my form I am getting an error: Select a valid choice. ... is not one of the available choices and the form is refreshed with new 3 suggestions in the dropdown. models.py class GhostUser(models.Model): first_name = models.CharField("User's first name", max_length=100, blank=False) last_name = models.CharField("User's last name", max_length=100, blank=False) ghost_name = models.CharField("User's ghost name", max_length=100, blank=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.ghost_name}" def get_absolute_url(self): return reverse('ghost_names:ghost-update', kwargs={'id': self.id}) views.py class GhostCreateView(CreateView): template_name = 'ghost_create.html' form_class = GhostUserForm success_url = '/' # def get_context_data(self, **kwargs): # data = super().get_context_data(**kwargs) # url = "https://donjon.bin.sh/name/rpc-name.fcgi?type=Halfling+Male&n=3" # resp = urllib.request.urlopen(url) # names = resp.read().decode('utf-8') # data['ghost_suggestions'] = names.splitlines() # return data forms.py class GhostUserForm(forms.ModelForm): ghost_name = forms.ChoiceField(choices=[], widget=forms.Select()) class Meta: model = GhostUser fields = ['first_name', 'last_name'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['ghost_name'].choices = tuple(get_ghost_names()) def get_ghost_names(): url = "https://donjon.bin.sh/name/rpc-name.fcgi?type=Halfling+Male&n=10" resp = urllib.request.urlopen(url) data = resp.read().decode('utf-8').splitlines() names … -
Third party authentication for Django + React app
I am having an app with Django backend and React frontend and I'm using Azure AD for authentication. Basically, the frontend will try to authenticate users with Azure AD to obtain a token. Then, when users interact with the backend, the API call will include this token as well. At the backend, when received an API call, it will try to talk to Azure AD again to verify this token to make sure that this is a valid API request. Now, I'm thinking if there is a better way to do this, since for every API call, backend has to check for the validity of the token and it's kinda slow down the whole process. Is there anyway to improve the performance of this architecture? Thanks! -
Python Pillow - Facing issue with crop()
I am using jquery-cropper.js to crop an image on front end and then pass the values to Django form as shown below. def save(self): photo = super(MyModelForm, self).save() 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.profile_pic) cropped_image = image.crop((int(x), int(y), int(w+x), int(h+y))) cropped_image.save(photo.profile_pic.path) #resized_image = cropped_image.resize((min(new_width, new_height), min(new_width, new_height)), Image.LANCZOS) #resized_image.save(photo.profile_pic.path) return photo The issue at the moment is that image is cropped fine on the front end but not on the backend. I get black area in the cropped pic. I want exact image as I see on the front end. The coordinates on the front end and backend are same. The cropped image is like -
Make migrations several files django
I have django project with the next structure: [projectname]/ ├── core/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── custom_user/ │ ├── ...#some files │ └── models/ │ ├── user.py │ └── tags.py │ └── manage.py How I can to run command makemigrations for several files (for user.py and for tags.py), now I'm trying to implement it by command ./manage.py makemigrations custom_user, but I'm getting the next info No changes detected in app 'custom_user'., I've defined the app in settings.py file in installed_apps as: INSTALLED_APPS = [ 'custom_user.apps.CustomUserConfig' ] and in apps.py file too as: class CustomUserConfig(AppConfig): name = 'custom_user' Nevertheless if I add my models to usual models.py file everything works. -
Get request.user in __init__ of Django Admin Forms
How does one add request.user in init and save methods I want to use owner = request.user. At the moment I have hardcoded in init as owner=2 class QuizAdminForm(forms.ModelForm): class Meta: model = Quiz exclude = [] questions = forms.ModelMultipleChoiceField( queryset=Question.objects.filter(owner=1).select_subclasses(), required=False, label=_("Questions"), widget=FilteredSelectMultiple( verbose_name=_("Questions"), is_stacked=False)) def __init__(self,*args, **kwargs,): super(QuizAdminForm, self).__init__( *args, **kwargs) if self.instance.pk: print('filter questions') self.fields['questions'].initial =\ self.instance.question_set.filter(owner= 2).select_subclasses() def save(self, commit=True): quiz = super(QuizAdminForm, self).save(commit=False) quiz.save() quiz.question_set.set(self.cleaned_data['questions']) self.save_m2m() return quiz class QuizAdmin(admin.ModelAdmin): form = QuizAdminForm list_display = ('title', 'category', ) list_filter = ('category',) search_fields = ('description', 'category', ) I would also like to add owner=request.user, which I can do using the method below. But in that case question_set.set does not work which works fine in "save" method. def save_model(self, request, obj, form, change): if not obj.pk: # Only set added_by during the first save. obj.owner = request.user super().save_model(request, obj, form, change) quiz = Quiz.objects.get(id=obj.id) quiz.save() quiz.question_set.set(self.cleaned_data['questions']) -
How can I delete a record from the database through a template?
How can I delete a record from the database through a template? For example, I have a list of comments that I received from the database and displayed on the page, next to them there is an icon with a basket and when I click on the icon, the entry should be deleted from the database. -
Django survey app cannot past first iteration (UserResponse.user) must be a User instance
I am currently working on a django-survey app. To get started and after following the tutotrial I used this repo as guidance: https://github.com/tonysyu/djangosurvey. I was able to make it work however there is an issue. After entering the questions in the admin and answering them the first time it is not possible to answer a second round of questions, it is like if the database cannot be expanded past the first user (I checked the tables on sql and the structure is as wanted). Below you can find the code and error message. models.py: from django.db import models from django.contrib.auth.models import User DEFAULT_STRING_LENGTH = 200 class Question(models.Model): question_text = models.CharField(max_length=DEFAULT_STRING_LENGTH) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=DEFAULT_STRING_LENGTH) def __str__(self): return self.choice_text class UserResponse(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) def __str__(self): return '{}|{}'.format(self.user.username, self.choice.choice_text) views.py: from django import urls from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from lazysignup.decorators import allow_lazy_user from .models import Choice, Question, UserResponse from .utils import random_question @allow_lazy_user def index(request): question = random_question(request.user) context = {'question': question, 'all_answered': False} if question is None: context['all_answered'] = Question.objects.all().count() > 0 return render(request, 'polls/index.html', context) @allow_lazy_user … -
Passing a django dictionary ( or json file) to javascript function
I know there are a few ways to access django variables in javascript .However I am not able to send a django dictionary or json object to javascript . My code : {% for item in items %} <tr> <td><a onclick=edit_product("{{item|safe}}")>{{ item.product_name }}</a></td> {%endfor%} <!--- JAVASCRIPT HERE ---!> <script> function edit_product(item){ console.log(item.id) } </script> Here "items" is a json object which is a list of dictionaries (the dict has more than 20 keys and values ) there are thousands of item in list . I only want to pass the particular item user selected to js function . Is there any simple way to do it ? I don't want to include serializers or rest-framework . I don't care for security ,I will be the only one using this . I don't want to put all 20 pairs of the dictionary in html like: <input type="hidden" id="myVar" name="variable" data-prod="{{ item.product_name }}" data-id="{{ item.id }}"> -
Django: After executing a payment on PayPal how to redirect website to another page through Ajax
In my E-commerce project, when a user adds items to the cart and executes a payment via PayPal, a PayPal window is opened and after submitting payment the windows are closed but the website page remains to the payment page where there is still items in the cart because the page is not refreshed. So my question is how do I set the ajax javascript to redirect the website page to go to another link called: "order_completed.html" that I have set with Executed order details, instead of show a success message to the buyer from script. Here is the views.html: def payment_complete(request): body = json.loads(request.body) order = Order.objects.get( user=request.user, ordered=False, id=body['orderID']) payment = Payment( user=request.user, stripe_charge_id=body['payID'], amount=order.grand_total() ) payment.save() # assign the payment to order order.payment = payment order.ordered = True order.ref_code = create_ref_code() order.save() messages.success(request, "Your Order was Successful ! ") return render(request, "order_completed.html", {'order': order}) class PaymentView(View): def get(self, *args, **kwargs): # order order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = { 'order': order, 'DISPLAY_COUPON_FORM': False } return render(self.request, "payment.html", context) else: messages.warning( self.request, "You have not added a billing address") return redirect("core:checkout") # `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create # -token def post(self, *args, **kwargs): order … -
What is wrong when I cannot push my project on heroku?
When I issue $ heroku open I get this error: When I check my logs for details, the end of what appears in my terminal looks like that: Can anyone please help to solve this problem? Thanks! -
Github ssh-action configuration to deploy changes in django application
I have set up a workflow to execute a script which essentially just makemigrations, migrates and runs collectstic before restartting gunicorn and reloading nginx. I have configured my settings.py file to pick up the secret and some other variables from the environment. The problem is though, that the script executes successfully when I manually ssh into the server and run it whereas when doing the same via ssh-action, it throws an error My script # Cd into the required directory cd myproject/ # Pull the changes git pull # Makemigrations and migrate myenv/bin/python manage.py makemigrations myenv/bin/python manage.py migrate # Collectstatic myenv/bin/python manage.py collectstatic --noinput # Restart gunicorn and reload nginx systemctl restart gunicorn systemctl reload nginx My action config name: deploying changes on: push: branches: [main] jobs: build: name: Build runs-on: ubuntu-latest steps: - name: deploying changes uses: appleboy/ssh-action@master with: host: ${{ secrets.HOST }} username: ${{ secrets.USERNAME }} key: ${{ secrets.KEY }} script: | sh deploy_changes.sh This successfully connects to the server but following is the error thrown when it tries to execute the makemigrations and migrate command err: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") err: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Also, I have a … -
Variable is unused even tho it is used
The Variable post_added is unused, even tho I use it later in the code. I really can't figure out where the problem is supposed to be def post_comment_create_and_list_view(request): qs = Post.objects.all() profile = Profile.objects.get(user=request.user) p_form = PostModelForm() c_form = CommentModelForm() post_added = False profile = Profile.objects.get(user=request.user) if 'submit_p_form' in request.POST: print(request.POST) p_form = PostModelForm(request.POST or None, request.FILES) if p_form.is_valid(): instance = p_form.save(commit=False) instance.author = profile instance.save() p_form = PostModelForm() post_added = True more code -
How to check if Place is near to My driving route in GeoDjango
I want to check weather a given location (Point of Interest) is in the certain range of my Driving Route(LineString). I guess bbcontains, bboverlaps are the options but not sure since there are no video tutorials of GeoDjango. Leaving useful link below if someone can help me out here. bbcontains&bboverlaps I seen some where that an envelope can be drawn around a linestring but now unable to get the link on internet. Any help would be appreciated. Thanks :) -
How to link Django User model to certain Post models
So let's say I have a model called "Post" that looks like this: class Post(models.Model): title = models.CharField(max_length=50) body = models.TextField() def __str__(self): return self.title now, say I have an option for users to create a Post on my site. How could I alter the standard User model and give it a characteristic containing all of the posts that that user has created. For example, say we have a user who has created a post. In the interactive shell that Django has, I could enter "user.posts" and It would pull up all the posts that that user has created. How could I go about this?