Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Running a Django/Gunicorn app locally using Docker fails with ERR_CONNECTION_REFUSED
My Dockerfile, shown here, deploys to Google App Engine flex and runs with no problems. FROM gcr.io/google-appengine/python RUN apt-get update && apt-get install -y \ binutils \ gdal-bin \ python-gdal RUN virtualenv /env -p python3.6 ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH ADD requirements.txt /app/requirements.txt RUN pip install -r /app/requirements.txt RUN mkdir -p -m775 uploads ADD . /app CMD exec gunicorn -b :$PORT mysite.wsgi I can also run the application locally by getting into the virtual environment and: python manage.py runserver This allows me to view it in a browser at http://localhost:8000/ and also access the API locally. However, my problem is when I run the application locally using docker. When I go to http://0.0.0.0:8000/, I always receive an ‘ERR_CONNECTION_REFUSED’ error. I’ve tried various iterations of: docker run --entrypoint=/bin/bash django -c "python manage.py runserver 0.0.0.0:8000" and docker run --entrypoint=/bin/bash django -c "p["gunicorn", "--bind", ":8000", "--workers", "3", "mysite.wsgi:application"] And I have tried changing my Docker file cmd (and rebuilt the image) to: CMD ["python", "manage.py", "runserver", "0.0.0.0", "8000"] And ENTRYPOINT [ "python", "manage.py" ] #CMD [ "runserver", "127.0.0.1:8000" ] CMD [ "runserver", "0.0.0.0:8000" ] But keep getting the same ‘ERR_CONNECTION_REFUSED’ error I’ve been thru all the SO related questions I could find … -
django creating Profile with custom company fields
i have two forms (OwnerCreateForm, EmployeesCreateForm) and 3 models (Profile, Company). when owner signup he creates the company and his own User object. after the owner login, he can created Employees. i need to associate the owners company to the employees. here is the models i'm using: class Company(models.Model): company_name = models.CharField(max_length=100, unique=True) address = models.CharField(max_length=100) def __str__(self): return self.company_name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') company = models.ForeignKey(Company, on_delete=models.CASCADE) is_owner = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) is_systemAdmin = models.BooleanField(default=False) def __str__(self): return '{} Profile'.format(self.user.username) and here the forms: from django.contrib.auth.forms import UserCreationForm from .models import Company from django import forms class CompanyForm(forms.ModelForm): class Meta: model = Company fields = ('company_name', 'address') class OwnerCreateForm(UserCreationForm): class Meta: fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = "Email Address" class EmployeesCreateForm(UserCreationForm): is_admin = forms.BooleanField(required=False) is_manager = forms.BooleanField(required=False) is_systemAdmin = forms.BooleanField(required=False) class Meta: fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = "Email Address" and here is my views: from django.shortcuts import render, redirect from .forms import OwnerCreateForm, EmployeesCreateForm, … -
Is there a way to implement the group function as in Facebook group in Django?
I’m looking to build a community management tool, which partially is quite similar to how the Facebook (private) Groups works. Is there any existing group application in Django to achieve such function, so that use could create, view, and manage their own group? Thanks in advance :) will be looking to refine my question more if required! -
How to use Django url template in a Javascript file
I'm using Django 3.1 and I would like to know how to use Django URL template in a Javascript file. I'm trying to implement AJAX and when I try to open the connection using the following command in a Javascript file (not inside a script tag in an HTML file): var xmlhttp = new XMLHTTPRequest(); xmlhttp.open("GET", "{% url 'checkUser' %}?username=" + encodeURIComponent(username.value), true); The template is not parsed. But if I use the Javascript code inside a script tag in an HTML file, it works fine. Is it possible to use the Django templates in a JS file? How? -
How to display English to Persian numbers in Django
How to display English numbers in Persian in Django? for example: English numbers: 0 1 2 3 4 5 6 7 8 9 Persian numbers: ۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹ -
Cannot access pg_config on virtualenv python
I have a problems when try to install pip install psycopg2 the errors is Error: pg_config executable not found. but when I try access pg_config from normal terminal (not in virtualenv mode), I can access the pg_config Anyone can help ? Screenshot of pg_config not found on venv, but found on normal terminal mode