Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
I am getting an error while uploading my Django app to server
2020-10-10T15:33:00.962648+00:00 heroku[web.1]: Process exited with status 3 2020-10-10T15:33:01.005314+00:00 heroku[web.1]: State changed from up to crashed 2020-10-10T15:33:01.408833+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=writingroom.herokuapp.com request_id=c6148721-26bb-4fac-83bf-4acd4ea1365b fwd="176.233.99.0" dyno= connect= service= status=503 bytes= protocol=https Restarting dynos on ⬢ writingroom... done PS D:\visual_studio_code\python1\django\my_blog> heroku open I am getting an error while uploading my Django app to server(error code=H10 desc="App crashed" method=GET path="/" ) -
Django selected value using manual render form in django
I'm trying to implement CRUD operations in django, however, I'm stuck in the edit operation. After passing the data to edit template I need to show the selected values of operating system dropdown list, how can I achieve that? I utilized the manual rendering of django form with the following code in the template: <div class="form-group row"> <label class="col-sm-3 col-form-label">Operating System</label> <div class="col-sm-9"> <select class="form-control" name="os_id" id="os_id" required> <option value="">--Select--</option> {% for os in os %} <option value="{{ os.id}}">{{ os.key_name}}</option> {% endfor %} </select> </div> </div> <div class="form-group row"> <label class="col-sm-3 col-form-label">Title</label> <div class="col-sm-9"> <textarea class="form-control" id="title" name="title" rows="3" required>{{ servicedesk.title }}</textarea> </div> </div> here's the view code: def edit(request, id): servicedesk=Servicedesk.objects.get(id=id) softwares=Software.objects.all os=OperatingSystem.objects.all context = {'servicedesk':servicedesk, "softwares":softwares, "os":os} return render(request, 'servicedesks/edit.html', context) and the model: class OperatingSystem(models.Model): key_name = models.CharField(max_length=100,null=True) key_description = models.CharField(max_length=255,null=True) class Meta: db_table = "operating_systems" def __str__(self): return self.key_name class Software(models.Model): key_name = models.CharField(max_length=100,null=True) key_description = models.CharField(max_length=255,null=True) class Meta: db_table = "softwares" def __str__(self): return self.key_name class Servicedesk(models.Model): os_id=models.ForeignKey(OperatingSystem, on_delete=models.SET(0)) software_id = models.ForeignKey(Software, on_delete=models.SET(0)) title = models.CharField(max_length=255,null=True) I tried this but it's not working: <div class="form-group row"> <label class="col-sm-3 col-form-label">Operating System {{os_id}}</label> <div class="col-sm-9"> <select class="form-control" name="os_id" id="os_id" required> <option value="">--Select--</option> {% for os in os … -
How to make chrome webmanifest point to the right png located in Django static directory
I'm trying to add a favicon package to my website but I can't make the webmanifest point to the right source that is: static/favicon/android-chrome-192x192.png When using "src":"static/favicon/android-chrome-192x192.png" it points to static/favicon/static/favicon/android-chrome-192x192.png and when using "src":"android-chrome-192x192.png" it points to /android-chrome-192x192.png This is the webmanifest: { "name": "I.R Portfolio", "short_name": "I.R", "icons": [ { "src": "static/favicon/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "static/favicon//android-chrome-512x512.png", "sizes": "512x512", "type": "image/png" } ], "theme_color": "#ffffff", "background_color": "#ffffff", "display": "standalone" } And this is the HTML: <link rel="manifest" href="{% static 'favicon/site.webmanifest' %}"> I would be really grateful if someone could point me to the right documentation/answer or have a solution, I couldn't find anything regarding this. -
Resize imgaes Django
I have modek `from tempfile import NamedTemporaryFile #models.py upload_path = 'images' class Image(models.Model): image = models.ImageField(upload_to=upload_path, blank=True, null=True) image_url = models.URLField(blank=True, null=True) def clean(self): if (self.image == None and self.image_url == None ) or (self.image != None and self.image_url != None ): raise ValidationError('Empty or both blanked') def get_absolute_url(self): return reverse('image_edit', args=[str(self.id)]) def save(self): if self.image_url and not self.image: name = str(self.image_url).split('/')[-1] img = NamedTemporaryFile(delete=True) img.write(urlopen(self.image_url).read()) img.flush() self.image.save(name, File(img)) super(Image, self).save() This model loads the link url into the ImageField. #forms.py class ImageForm(ModelForm): class Meta: model = Image fields = ['image', 'image_url'] This is my form to add images. #views.py class DetailImage(UpdateView): model = Image form_class = ImageForm template_name = 'image_edit.html' context_object_name = 'image' How can I resize images so that the original files are retained, and only images changed in width and height are displayed in the backend? -
How to render variable to template in Django app
I'm developing Django app. I want to render variable "q_word" to the template from this views.py class DbList(ListView): model = TestEu paginate_by = 10 def get_queryset(self): q_word = self.request.GET.get('query') if q_word: sql = 'select * from test_eu' sql += " where eng_discription ~ '.*" + q_word +".*'" object_list = TestEu.objects.raw(sql) return object_list Since "get_queryset" function apply "self" as first argument def get_queryset(self): I don't know how to apply below code to render. return render(request, 'detail.html', {'q_word': q_word}) -
My app is not recognising AUTH_USER_MODEL as the default User model
I have created a custom User model. My model is as follow: class User(AbstractUser): ... Name = models.CharField(max_length=128) ... When I try to make a post request to this model through my app, in the views.py file I have code that goes like this: def post(self,request): name = request.POST['name'] email = request.POST['email'] password = request.POST['password'] age = request.POST['age'] number = request.POST['number'] gender = request.POST['gender'] organisation = request.POST['organisation'] designation = request.POST['designation'] u = User( Name = name, ... I get an error that goes like this: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/Users/adhishwars/Desktop/simulations/beergame/views/instructor.py", line 37, in post u = User( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/base.py", line 500, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: User() got an unexpected keyword argument 'Name' I made sure I included AUTH_USER_MODEL = 'app.User' in the settings.py file at the beginning of the project before I applied any migrations. Yet I still … -
After Upgrading of new version of python 3.9 ! why i am getting that type of error.Too much annoying.?
I am getting that error after upgradation of python new version 3.9 . fatal python error: init_import_size: failed to import the site module -
DRF Updating an existing model after adding values to non existing fields
I am trying to create a bet app so that user can create bet and challenge other . But when I am unable to create a new bet since I am placing the user who accepted the bet on the same model: this is how my model looking like . class CreateBet(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL,related_name="bets",null=True, on_delete=models.CASCADE) bet_name= models.CharField(max_length=255) amount = models.CharField(max_length=255) scheduled_datetime = models.DateTimeField(null=True,blank=True) accepted_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.SET_NULL,related_name="accept",null=True) status = models.BooleanField(default=False) so what I want is whenever I hit: router.register('api/bets',BetViewset,'userbets') this end point I want user to create a bet without adding to fields accepted_user and status . But if the user hit: router.register('accept_bet',AcceptBetViewset,'accept') this end point both the accepted_user will be created and status will be set to True. currently my serializer looking like this class BetCreateSerializer(serializers.ModelSerializer): class Meta : model = CreateBet exclude = ['accepted_user','status'] and its api: class BetViewset(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated ] serializer_class = BetCreateSerializer def perform_create(self,serializer): serializer.save(owner = self.request.user) def get_queryset(self): today = datetime.date.today() return CreateBet.objects.filter(scheduled_datetime__date=today) which works perfectly fine . but whenever I tried with this serializer : class AcceptBetSerializer(serializers.ModelSerializer): bet = BetCreateSerializer(many = True , read_only= True) class Meta: model = CreateBet fields ='__all__' # def update(self, instance, validated_data): # id = validated_data.pop('id') … -
Will Windows Server 2012 work with Django 3.1.2?
I would like to know if somebody has recently worked with Windows Server 2012 & Django 3.1.2. Are they compatible? Will there be any issues?