Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model (Questions) object is not iterable
error: 'Questions' object is not iterable models.py code: class Questions(models.Model): title = models.CharField(max_length = 150) slug = models.SlugField(max_length = 10, unique = True) body = models.TextField() category = models.ManyToManyField(Category, related_name = "questions") author = models.ForeignKey(User, on_delete = models.CASCADE) created = models.DateTimeField(auto_now_add = True) picture = models.ImageField(upload_to = "questions/%Y/%m/%d", null = True, blank = True) status = models.BooleanField(default = True) def get_absolute_url(self): return reverse("questions:ques_detail", args = [self.slug, self.id]) views.py code: def QuestionDetail(request, question, pk): question = get_object_or_404(Questions, slug = question, id = pk) return render(request, "questions/ques_detail.html", {"questions": question}) urls.py code: urlpatterns = [ path('<slug:question>/<int:pk>', QuestionDetail, name = "questiondetail") -
How to remove Django MPTT trailing slash at the end?
I've set up a simple path for categories url url(r'^kategorie/(?P<path>.*)', mptt_urls.view(model='categories.models.EcommerceProductCategory', view='ecommerce.views.category_view', slug_field='slug'), name='category_view'), models.py def get_absolute_url(self): return reverse('ecommerce:category_view', kwargs={'path': self.get_path()}) using this documentation: https://pypi.org/project/django-mptt-urls/ but when i go into an url lets say http://127.0.0.1:8000/ecommerce/category/x/ works just fine, but when i remove the trailing slash http://127.0.0.1:8000/ecommerce/category/x i get an error AttributeError at /ecommerce/category/x 'NoneType' object has no attribute 'get_ancestors' Do you have any idea how to not include the trailing slash? -
How to render a django message after page refresh
Hi i am trying to show a message but the django message is not showing. The way i want to access this is if i send a webhook to a function in python for example. ill send a webhook post request using postman , and i will receive the message But if i then go to my page it is not showing so my question is why is it working when i am using postman and not when using the browser, i also have a option to send the webhook request using a form on the app itself and ive added a refresh method as well but still nothing happpens. is there a way to get a message on django if the python function is triggered with a webhook? i am currently using 2 methods , both are working when using postman but neither works on the app itself method 1 messages.add_message(request, messages.INFO, 'LONG was placed.') {% if messages %} {% for message in messages %} <div class = "alert alert-{{message.tags}}">{{message}}</div> {% endfor %} {% endif %} and method 2 storage = messages.get_messages(request) for message in storage: a=(message) print(a) storage.used = False context = {'a':a} return render(request,'crodlUSDT/syntax.html',context) and then just … -
Create an object using Django Query in Shell
I am learning django. I am trying to create an object within Blog model using Django Query in Shell In the models.py file I have created the following models- from django.db import models # Create your models here. class Blog(models.Model): name = models.CharField(max_length=120) created_on = models.DateTimeField(auto_now_add=True) class Article(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=120) body = models.TextField() draft = models.BooleanField(default=False) I typed the following commands in the shell >>> from blog.models import Blog >>> blog = Blog(name='My Shell Blog') >>> blog.save() >>> article = Article(blog, title='My article from shell',body= 'I created this article from shell') >>> article.save() I got the following error- Traceback (most recent call last): File "/home/anshul/my-django/myapp_env/lib/python3.8/site-packages/django/db/models/fields/_init_.py", line 1988, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'Blog' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/anshul/my-django/myapp_env/lib/python3.8/site-packages/django/db/models/base.py", line 806, in save self.save_base( File "/home/anshul/my-django/myapp_env/lib/python3.8/site-packages/django/db/models/base.py", line 857, in save_base updated = self._save_table( File "/home/anshul/my-django/myapp_env/lib/python3.8/site-packages/django/db/models/base.py", line 970, in _save_table updated = self._do_update( File "/home/anshul/my-django/myapp_env/lib/python3.8/site-packages/django/db/models/base.py", line 1013, in _do_update filtered = base_qs.filter(pk=pk_val) File "/home/anshul/my-django/myapp_env/lib/python3.8/site-packages/django/db/models/query.py", line 1071, in filter return self._filter_or_exclude(False, args, kwargs) … -
502 Bad Gateway nginx/1.18.0 (Ubuntu) Django Digital ocean
I want to deploy my django project with Ubuntu and Digital Ocean. It's not the first time I do it but now I keep getting this error and I don't know what's causing it. I used this video as guide for the process: https://www.youtube.com/watch?v=US9BkvzuIxw. It's really annoying because the only message that I get is "502 Bad Gateway nginx/1.18.0 (Ubuntu)" and what I found on internet to solve it doesn't work. All nginx tests I run say it works correctly. This is the code where I think the error must be: /etc/nginx/sites-available/locallibrary server { server_name vvmwp.nl; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/locallibrary; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=sammy EnvironmentFile=/home/sammy/locallibrary/env WorkingDirectory=/home/sammy/locallibrary ExecStart=/home/sammy/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ locallibrary.wsgi:application [Install] WantedBy=multi-user.target /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Thanks in advance -
django-session-security not working for remember me
I'm trying to make remember me on login page, but not working. I tried set settings.SESSION_EXPIRE_AT_BROWSER_CLOSE=False on views.py or delete SESSION_EXPIRE_AT_BROWSER_CLOSE on settings.py, but nothing of that working. Can somebody help? settings.py SESSION_SECURITY_EXPIRE_AFTER=6 SESSION_SECURITY_WARN_AFTER=5 SESSION_EXPIRE_AT_BROWSER_CLOSE=True views.py def loginPage(request): if request.user.is_authenticated: return redirect('indexPage') else: if request.method == 'POST': salary_number = request.POST.get('salary_number') password = request.POST.get('password') user = authenticate(request, salary_number=salary_number, password=password) if user: login(request, user) remember_me = request.POST.get('remember_me') if remember_me: request.session.set_expiry(0) request.session.modified = True if password == '123456': return redirect('changePassword') else: return redirect('indexPage') context = {} return render(request, 'login.html', context) -
how can I add kakao pay to my django app?
hello in my app I did paypal but now I wanna add also kakao pay, I have tried somethings but doesn't work, is there any well explained turorials for that, and how can I install kakao pay in django app and work with that. Note : I have already registred to kakao developers and created an app there but can't understand how to make it work in the programming side -
Django automatically logouts when page reloads
I use SESSION_EXPIRE_AT_BROWSER_CLOSE = True for logging out the user once browser closes and it works fine in local computer but when I deploy the site and use this feature it immediately logouts the user once I login. I am using heroku as deployment server. Session settings in Settings.py :- SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_COOKIE_AGE = 1000 SESSION_SAVE_EVERY_REQUEST = True SESSION_EXPIRE_AT_BROWSER_CLOSE = True -
Arithmetic Operations in django template
\<tr\> {% for i in portfolio %} \<!-- \<th scope="row"\>{{i.id}}\</th\> --\> \<td\>{{ i.stock }}\</td\> \<td\>{{ i.quantity }}\</td\> \<td\>{{ i.purchasedPrice }}\</td\> \<td\>{{ i.currentPrice }}\</td\> \<td\>{{ i.quantity\*i.currentPrice - i.quantity\*i.purchasedPrice|safe }\</td\> \<td\>\</td\> \</tr\> {% endfor %} I want to do display the mongodb fetched results in the above format but <td>{{ i.quantity*i.currentPrice - i.quantity*i.purchasedPrice|safe }</td> This line of code is thorwing error of "TemplateSyntaxError at / Could not parse some characters: i.quantity|i.currentPrice - i.quantityi.purchasedPrice||safe" How can fix this? -
How to give view authorization/access to a object of a model to different users by the creator of the object in django
I am doing an online classroom project in Django where I created a model named course which is accessible by teachers. When I create a class/new course it creates an object of that.Now I am trying to add students/users in a particular course/class object by inviting students or students can enroll using "clasroom_id"(a unique field I used in the model) just like we invite people in google classroom to join classes. How to do that? How to add course material to an individual course I added the models and views of the course object below. models.py class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.course_name def is_valid(self): pass views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): course = form.save(commit=False) course.created_by = request.user course.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) def view_courses(request, *args, **kwargs): students = course.objects.filter(created_by=request.user) dict = {'course':students} return render(request, 'teacherhome.html',dict) -
Django Passing Dynamic Model Field
Suppose I want to create a Dynamic Model Field. I am trying to explain it more. Suppose use want to create a something like Add a field then asking for field name and what is the field type user want can be char, date, text etc. User pass this to backend now I am wondering How can I get those and pass it in a model below? class DynamicModel(models.Model): dynamic_field_name = models.DynamicFieldType() After passing it how can I sync the db without using python manage.py migrate and makemigrations?? I saw one website using this feature and it built with Django. So I am wondering How they do this? -
How to post only date while updating
My Model. class CenterCampPackage(core_models.TimestampedModel): centers = models.ManyToManyField(Centers, related_name="camp_centers", blank=True) package = models.ForeignKey("package.Package", related_name="camp_package",null=True, blank=True,on_delete=models.CASCADE) valid_till = models.DateTimeField(null=True, blank=True) valid_from = models.DateTimeField( null=True, blank=True) is_active = models.BooleanField(default=True) My Serializers: class CenterCampPackageUpdateSerializer(serializers.ModelSerializer): centers = serializers.PrimaryKeyRelatedField(queryset=Centers.objects.all(), many=True) package = serializers.PrimaryKeyRelatedField(queryset=package_models.Package.objects.all(), allow_null=True, required=False) valid_from = serializers.DateTimeField(allow_null=True, required=False) valid_till = serializers.DateTimeField(allow_null=True, required=False) is_active = serializers.BooleanField(default=True) class Meta: model = CenterCampPackage fields = "__all__" def update(self, instance, validated_data): centers = validated_data.get("centers") package = validated_data.get("package") valid_from = validated_data.get("valid_from") valid_till = validated_data.get("valid_till") is_active = validated_data.get("is_active") if centers: instance.centers.clear() instance.centers.add(*centers) if package: instance.package = package if valid_from: instance.valid_from = valid_from if valid_till: instance.valid_till = valid_till if is_active is not None: instance.is_active = is_active instance.save() return instance I have created a model with dateime field. But while updating the data i want to only post date. How to achieve this wtihtout altering the field. I tried to use date() but is not working. Can somebody help. Thank you !! -
Remove Z from DateTimeField in serializer
Is there a way to make my serializer print the datetimefield by default like this 2022-03-28T00:00:00+00:00 Instead of this 2022-03-23T03:16:00Z I get the first output when I do this return obj.time.isoformat() -
PythonAnywhere "ModuleNotFound Error django"
Im working on hosting a Django app on pythonanywhere. I had it semi working before changing a few things that a guide suggested, before it started running a ModuleNotFoundError saying Django was not installed, even though I did install it in the virtual environment. The changes I made before this started happening are: I remade my Github repo by incorporating a .gitignore file before pushing to the repo as suggested by the guide (I forgot to make this file the first time I made the repo and cloned into PythonAnywhere). The file consists of this: # Python *.pyc *~ __pycache__ # Env .env myvenv/ venv/ # Static folder at project root /static/ # macOS ._* .DS_Store .fseventsd .Spotlight-V100 # pycharm .idea/ I pushed my project to Github, and then at the repo on github I manually inserted this into the .gitignore file before cloning to PythonAnywhere: wintergardendjango/settings.py I then cloned this repo via the console on pythonanywhere and made a new virtual environment where I again installed django. I updated all my paths to reflect the new virtual environment ect. The error being called is in the WSGI file which is: # To use your own django app use code … -
Django - is there way to connect Cytoscape? (Not CytoscapeJs)
I am looking a way to use Cytoscape library with Python via Django. I would like to go to route and be able to click node and have an output. I want this to be similar to this one video: https://www.youtube.com/watch?v=g8xBlilTV4w I have represented this problem on image below: enter image description here How should I tackle the problem? -
Connecting to same database, different schema/table names in Django schema
I'm trying to figure out the best way to create a Django schema that can dynamically switch between schema with similar structure in the same database (i.e. similar table names, with an appended suffix) so that I can build a graphene application and change the suffix based on my query. For example, if I have a book table: class Book(models.Model): class Meta: db_table = "book_{suffix}" ... I'd want to switch the database connection's schema and set the suffix before any queries are executed. I've not seen an example of how to best handle that. -
Changing foreign key based on varying input
I've built a review tool for various systems so that managers can review their employees current access to those systems. It runs on a campaign by campaign basis where the team who manages this access selects a specific system when kicking off the campaign. I have a review model that relates to the campaign, the manager doing the review, the employee being reviewed, as well as the employee's account being reviewed. However, I currently have to hard code the foreign keys like so acsAcct = models.ForeignKey('acsUser', null=True, blank=True, on_delete=models.CASCADE) iseAcct = models.ForeignKey('iseUser', null=True, blank=True, on_delete_models.CASCADE) ... This creates an issue when I try to dynamically create review instances with my createReview class method. Currently I have to append the account to the review later by checking the campaign's system and then going to the appropriate model and finding the user's account. I'd muc rather be able to do that when I go to create the review. Essentially I would like to do something like: systemAcct = models.ForeignKey(?, null=True, blank=True, on_delete=models.CASCADE) # Then my create method @classmethod def createReview(cls, **kwargs): review = cls.objects.get_or_create( campaign = kwargs['campaign'], manager = kwargs['manager'], employeeReviewed = kwargs['employeeReviewed'], reviewer = kwargs['reviewer'], systemAcct = kwargs['systemAcct'], ) I want … -
How to add multiple filters when using Django Rest framework search_filter
I'm currently trying to create a fullstack website using django for the backend. One of the features I'm building is a search function. To do that, I used the built in django-rest SearchFilter, as well as the built in OrderingFilter so users can toggle how results are ordered. However, I also want users to be able to filter their results further, such as selecting a specific year, or a specific name, from a drowdown menu. So essentially, I want to be able to use a search filter and still specify another field that has to match exactly. For example, lets say the users searched for "Cat" and the results were as follows: Name: Cat1 Description: A happy cat Year: 2017 Name: Cat2 Description: A sad cat Year: 2017 Name: Lion Description: A large cat Year: 2018 Name: Lion Description: A large cat Year: 2019 All of these results show up because they contain "cat" in either the name or description fields. But then, I want the user to be able to specify a year via a dropdown menu. So the menu would have 2017, 2018 and 2019 as options, and after selecting 2017, the results would be like this: Name: … -
Django def list API join two table drom DB
I am trying to use the def list function Django from these two which I have tables Batch and BatchYield the table of Batch look like batch_id | batch_status | `````````|```````````````| 11 | completed | and the table of BatchYield look like id | grade_a_produce | grade_b_produce | grade_c_rejection | harvest_date | batch_id | ```|`````````````````|`````````````````|```````````````````|``````````````|``````````| 23 | 100 | 120 | 212 | 22-02-12 | 11 | 25 | 110 | 122 | 242 | 21-01-14 | 11 | So I wrote a def list function in Django in which I have joined these two table with this code def list(self, request, *args, **kwargs): try: for data in request.data: batch_id = data.get('batch_id') all_batchyield = BatchYield.objects.filter(batch_id=batch_id).values('grade_a_produce', 'id', 'grade_b_produce', 'grade_c_rejection', 'harvest_date', 'batch_id') if all_batchyield.count == 0: return Response({"response": "Data not Found"}, status=status.HTTP_200_OK) all_batchyield_df = pd.DataFrame(all_batchyield) all_batchyield_df = all_batchyield_df.replace({np.nan: None}) all_completed_batchs = Batch.objects.filter(id=batch_id).values('batch_status', 'id') completed_batch_df = pd.DataFrame(all_completed_batchs) completed_batch_df = completed_batch_df.replace({np.nan: None}) completed_batch_df.rename(columns={'id': 'batch_id'}, inplace=True) final = pd.merge(completed_batch_df, all_batchyield_df, on='batch_id') final = final.drop('batch_id', axis=1) except Exception as e: return Response({"response": str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response(final.to_dict('record'), status=status.HTTP_200_OK) From this code I got the and output which look like this [ { "batch_status": "completed", "grade_a_produce": 100.0, "id": 23, "grade_b_produce": 120.0, "grade_c_rejection": 212.0, "harvest_date": "2022-02-12T00:00:00Z" }, { "batch_status": … -
Django Not Recognizing Valid SuperUser
I am writing an app called product using django and I created a superuser for it, but it won't recognize the newly created super user. It will recognize the super user from another app I created, and that app and all it's related file are resting in a different directory all together. I've Made sure that both users that I added had the correct flags checked Here's what the settings.py looks like """ Django settings for inventory_app project. Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-qoi+29i4s@c@gw)6uoy!xja!6q)=1g=s05yja$mrlwlo_ht%vd' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'productapp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'inventory_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
RuntimeError: no running event loop Djnago runworker
I am deploying my Django app on AWS Ec2 with Apache. I have Asgi and WSGI. I wanna run: sudo daphne MyProject.asgi:channel_layer --port 80 --bind 0.0.0.0 -v2 sudo python manage.py runworker -v2 But when I run the worker I am getting Running worker for channels ['channels'] Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/lib/python3.8/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/lib/python3.8/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3.8/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python3.8/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/ubuntu/.local/lib/python3.8/site-packages/channels/management/commands/runworker.py", line 46, in handle worker.run() File "/usr/lib/python3.8/asgiref/server.py", line 59, in run event_loop = get_running_loop() RuntimeError: no running event loop I found this solution: Daphne + Channel v3 Deployment, RuntimeError: no running event loop but I already have asgiref==3.3.4 1-I found this one on github: https://github.com/django/asgiref/issues/278 but did not really understand how should I solve it. 2-I also did not really understand what should I do in Apache to filter the websocket request from the Normal request. If anyone has the same problem and know how to do it I would really appreciate it. Cause I don't have any Idea how to … -
Get primary key of specific object from list of objects in Django
I am trying to get the specific pk of the selected object when the user accepts a delivery. My problem is that I'm getting only the first object's pk in the list every time. I want to get the pk of the selected object. views: @login_required(login_url="/signin/?next=/driver/") def deliveries_available_page(request): deliveries = Delivery.objects.filter( status_of_delivery__in=[Delivery.DELIVERY_POSTED] ) #When driver accept delivery then status of delivery changes to delivering if request.method == 'POST': delivery = get_object_or_404(Delivery, pk=request.POST.get('receipt_number')) if delivery: delivery.status_of_delivery = Delivery.DELIVERY_DELIVERING delivery.driver = request.user.driver messages.success(request, 'Delivery Accepted') delivery.save() return redirect(reverse('driver:deliveries_available')) return render(request, 'driver/deliveries_available.html', { "GOOGLE_API_MAP": settings.GOOGLE_API_MAP, "del": deliveries }) HTML: <div class="d-flex flex-column h-100" style="padding-bottom: 50px"> <div id="map"></div> {% if del %} {% for d in del %} <div class="card" id="delivery-popup"> <div class="card-body p-2"> <div class="details"> <div class="p-2"> <strong id="address"></strong> <div> <strong id="show-info"></strong> </div> <div> <strong id="show-distance"></strong> <strong id="show-duration"></strong> </div> <div> <strong id="show-price"></strong> <strong id="show-id"></strong> </div> <div> <form method="POST"> {% csrf_token %} <button type="submit" class="btn btn-primary" name="accept">Accept</button> <input type="hidden" value="{{ d.receipt_number }}" name="receipt_number"> </form> </div> {% if messages %} {% for m in messages %} {% if m.tags %} <script>alert("{{ m }}")</script> {% endif %} {% endfor %} {% endif %} </div> </div> </div> </div> {% endfor %} {% endif %} I need the … -
How can django post multiple values at once?
If you create a code like above, create a value in index.html, and press the button to print only one value. How can I solve this problem? if request.method == 'POST': post = Post() post.yyyy = request.POST['yyyy'] post.mm = request.POST['mm'] post.dd = request.POST['dd'] post.cookname = request.POST['cookname'] post.save() global post_list post_list = { 'yyyy':post.yyyy, 'mm':post.mm, 'dd':post.dd, 'cookname':post.cookname } return redirect('index') else: post = Post.objects.all() return render(request, 'dncapp/index.html', {'post':post})``` -
Getting all objects of a model with ForeignKey field results in slow and a lot of query calls
When using the ModelChoiceField I am passing all the objects via brand = forms.ModelChoiceField(queryset=MobileModel.objects.all()) The model is as follows: class MobileModel(models.Model): brand = models.ForeignKey(MobileBrand, on_delete=models.PROTECT, blank=True, null=True) .... When checking with the debugger I see SQL query is called for every mobile model rows for getting the brand. Which for large records ends up with huge SQL queries. How to solve it and reduce the foreign key SQL queries. -
Django - Use field value as param in KeyTextTransform
Trying to use KeyTextTransform to grab a number from a json field. Only problem is, the target number is nested under a user_id. In order to grab the number, I need to dynamically grab the user_id, and use the user_id to key into the target dictionary. So my question - How can I pass the value of a field into KeyTextTransform? book \ .annotate(buyer_id=KeyTextTransform('selected_user', 'sale')) \ .annotate(price=KeyTextTransform(F('buyer_id'), 'sale')) # does not work