Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write test case for a Django model which has all the fields as foreignkey in DRF?
I have a model which has all the fields as a foreign key to other models. How can we create test case in Django rest framework in that case?? I have a model as follows: class Example(models.Model): package = models.ForeignKey( Destination, related_name="packages", on_delete=models.CASCADE ) user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name="user_packages", ) tour = models.ForeignKey( Tours, on_delete=models.CASCADE, null=True, related_name="tour_packages", ) In a model, when there is just one field in a Django model, it can be done in the following way: class NewsLetter(models.Model): NewsLetterID = models.AutoField(primary_key=True) Email = models.CharField(max_length=255) Connected = models.BooleanField(default=False) UserID = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table = 'NewsLetter' @classmethod def setUpTestData(cls): #Set up non-modified objects used by all test methods user = User.objects.create(<fill params here>) NewsLetter.objects.create(NewsLetterID=1, Email='test@test.com', Connected=False,UserID=user) So even if I have created all the objects for all the foreign-key fields just like this example, the thing is, for the related field models, they themselves have foreign key fields. How can we approach this?? For example in my Example model, the Destination model is itself related to other foreign key fields. So how to create unit test for create api for this Example model?? -
How to filter django queryset based on hours range?
class MyModelSerializer(serailizers.ModelSerializer): hour = serializers.SerializerMethodField() def get_hour(self, obj): created_at = obj.created_at # datetime now = datetime.now() return (now - datetime).total_seconds() // 3600 class Meta: model = MyModel fields = "__all__" In the api there are 3 static filter parameters: filter list upto 3 hr filter list between 3 to 12hr filter list above 12 hr How can I filter below api based on the hour that has been calulated in the above serializer ? For example if I filter by upto3 then the list should return all the objects having hr less or equal to 3. The below way returns if the hours matches the exact value only. @api_view(["GET"]) def get_list(request): qs = MyModel.objects.all() hr = request.GET.get("hr") if hr: hr = int(hr) frm = now() - timedelta(hours=hr+1) to = now() - timedelta(hours=hr) qs = qs.filter(created_at__range=(frm, to)) return MyModelSerializer(qs, many=True).data -
Read tables in Remote mysql database with Django SSH tunnel
I Stuck with it. I have access to remote MySQL database using ssh tunnel with IP, Port, ssh username, ssh password and using database credential with Server Host,Port, DB Name, user and password. I can access to this MySQL remote database in DBeaver and Putty using ssh tunnel and database credential In my Django application, in settings.py ssh_tunnel = SSHTunnelForwarder( (sshIpAdd, sshPort), ssh_username=sshUser, ssh_password=sshPass, ssh_proxy_enabled=True, # ssh_config_file=None, remote_bind_address=('127.0.0.1', 3306), ) ssh_tunnel.start() print(ssh_tunnel.local_bind_port) con=mysql.connector.connect(database=dbName, host='localhost', user=dbUser, password=dbPass, auth_plugin='mysql_native_password', charset='utf8', port=ssh_tunnel.local_bind_port) if con!=None: print("Connected to Mysql Remote Database") else: print("Sql Not Connected") it produce successfull output, and display Connected to Mysql Remote Database (py39) X:>python manage.py runserver 65116 Connected to Mysql Remote Database 65122 Connected to Mysql Remote Database Performing system checks... System check identified no issues (0 silenced). July 20, 2022 - 12:55:06 Django version 3.2.9, using settings 'test.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. When I run Command 'python manage.py inspectdb --database=remote_db' it successfully created model structure from remote database. The problem is when I access remote database in DATABASES with multiple database, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': defaultDBName, 'USER': 'postgres', 'PASSWORD': defaultDBPass, 'HOST': 'localhost', 'PORT': '5432', }, 'remote_db': { 'ENGINE': 'django.db.backends.mysql', 'HOST': … -
Where is my cache and how to keep it in Redis?
Django==4.0.6 django-cachalot==2.5.1 I use django-cachalot. settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, 'TIMEOUT': None, } } I warm the cache up. As you can see, there is something in the cache. But to the best of my ability I can see that Redis is empty. Could you help me understand where is my cache now? It is stored somewhere, but I can't understand where it is. And I seem to have made a blunder here, I have to correct it and keep the cache in Redis. Could you help me? -
How to make Dynamic page for Shopping CRUD
I am making a shopping CRUD and dynamically displaying data. When I press on category '9-6wear' ,I get clothes belonging only to the 9-6wear category ,the issue is that when I press on other categories(as shown in image below) ,I end up with clothes belonging to 9-6wear as well. If I try using the 'id', the issue would be is that I would end up with only 1 product in category below are the codes that I have used function def category(request): prod = Products.objects.filter(isactive=True) return render(request,'polls/category.html',{'products':prod}) def shoppingpage(request): cat = Category.objects.filter(isactive=True) subcat = SUBCategories.objects.filter(isactive=True) # category= CategorySerializer(cat,many=True) # subcategory = SUBCategoriesSerializer(subcat,many=True) hm = {'category':cat,'subcategory':subcat} return render(request,'polls/shoppingpage.html',hm) url path('shoppingpage/',views.shoppingpage,name="shoppingpage"), path('category/',views.category,name="category"), shoppingpage.html {% for result in category %} <div class="col-md-3"> <div class="lynessa-listitem style-01"> <div class="listitem-inner"> <a href="{% url 'polls:category' %}" target="_self"> <h4 class="title">{{result.category_name}}</h4> </a> {% for ans in result.subcategories_set.all %} <ul class="listitem-list"> <li> <a href="/kurta" target="_self">{{ans.sub_categories_name}}</a> </li> </ul> {% endfor %} </div> </div> </div> {% endfor %} help is greatly appreciated, thanks! -
Not able to connect to test database
I was trying to create some dummy data for testing using faker. My tests cases runs and passed successfully as we can see in the ss below, but the database table for Author Model is empty. I assume this might be because of database connection failure or some code error? What should be the right approach for such cases? Any solutions? My settings.py DATABASES={ 'default':{ 'ENGINE':'django.db.backends.postgresql', 'NAME':'postgres', 'USER':'postgres', 'PASSWORD':'welcome4321', 'HOST':'localhost', 'PORT':'5432', } } My factory.py named as factoryboy.py import factory from django.contrib.auth.models import User from faker import Faker from polls.models import Author fake = Faker() class AuthorFactory(factory.django.DjangoModelFactory): class Meta: model = Author name=fake.name() My model.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) class Author(models.Model): name=models.CharField(max_length=200) class Account: def __init__(self, username, email, date_joined): self.username = username self.email = email self.date_joined = date_joined def __str__(self): return '%s (%s)' % (self.username, self.email) my Conftest.py import pytest from pytest_factoryboy import register from factoryboy import AuthorFactory register(AuthorFactory) My test_ex5.py from argparse import Action from collections import UserDict from unittest.mock import Base from django.conf import UserSettingsHolder import pytest from sqlalchemy import create_engine from polls.models import Author from sqlalchemy.orm … -
ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. DJANGO_SETTINGS_MODULE or call settings.configure()
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I'm new to django, writing a blog for myself. I have created a blog app, written on models.py. Here my code:enter code here from django.db import models # Create your models here. class Post(models.Model): title= models.CharField(max_length=100) body= models.TextField() date= models.DateTimeField(auto_now_add=True) -
Vue not displaying results from Django Rest API data
I am working on a brand new project using Vue and Django Rest Framework. I got the API set up and I am getting the data back as needed. However, I am having an issue with the v-for loop displaying the results. Any reasons or ideas on why I am not getting the results displayed? Here is vue.js code (GetTasks.vue) <template> <div class="tasks"> <BaseNavbar /> </div> <div v-for="tasks in APIData" :key="tasks.id" class="container"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">{{tasks.task}}</h5> <p class="card-text">{{tasks.details}}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> </template> <script> import { getAPI } from '../axios-api' import BaseNavbar from '../components/BaseNavbar.vue' export default { name: 'GetTasks', data () { return { APIData: [] } }, components: { BaseNavbar, }, created () { getAPI.get('/tasks/',) .then(response => { console.log('Task API has recieved data') this.APIData = response.APIData }) .catch(err => { console.log(err) }) } } </script> Django model class Tasks(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=200) details = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) -
How can I solve this path error in project 'not a valid python path'
Hi guys I tried recently to create a new django project. So I run 'pipenv install django'. And this was the error I had. File "C:\Users\KONLAN\AppData\Local\Programs\Python\Python310\Lib\site-packages\pipenv\vendor\pythonfinder\models\python.py", line 379, in getattribute instance_dict = self.parse_executable(executable) File "C:\Users\KONLAN\AppData\Local\Programs\Python\Python310\Lib\site-packages\pipenv\vendor\pythonfinder\models\python.py", line 624, in parse_executable raise ValueError("Not a valid python path: %r" % path) ValueError: Not a valid python path: 'C:/Users/KONLAN/Downloads/Anaconda/python.exe' HOW CAN I SOLVE THIS? -
how to get a good job as a web developer
I graduated a tech school with a Web developer certificate in 2017. I had been doing data analytics using mainly SQL before that. I really enjoy coding the SQL reports, and I enjoy Python as a language. Now I do eCommerce selling tools, and it is kind of a drag. I am not sure what to learn, or where to focus my efforts to earn the most money. Running out of time. I would like to read some suggestions on finding work, or what to learn to find work. Certifications in SQL? Django? -
Why is there no existing virtual environment in setting up Django?
I successfully installed Django but when I type the command pipenv shell I get an error /usr/bin/python3: No module named pipenv.pew so when i also type the command pipenv --venv it says: No virtualenv has been created for this project yet! I'd appreciate your help, thank you! -
Django Javascript preselected value from database
I have a series of drop downs that are dependent upon the one above it. Starting with 'state' then pulls a list of all cities for that state and then all schools in that city. I am trying to find a way that when a user wants to update this information that it will pull the current information from the database and then have that value preselected from the list. Currently it just shows the 'Choose a state' the whole time until selected. If the user is from Maine, I want that to be selected already. Also, if possibly, how to make this an if statement. That if the user's state is null, then 'Choose state' is displayed and if not null, display current state. Thank you very much for the help! views.py def get_json_state_data(request): qs_val_unsorted = list(States.objects.values()) qs_val = sorted(qs_val_unsorted, key=lambda d: d['name']) return JsonResponse({'data':qs_val}) display.html <div class="ui fluid search selection dropdown" id='states_dropdown'> <input type="hidden" name="state"> <i class="dropdown icon"></i> <div class="default text" id="state_text">Choose a state</div> <div class="menu" id='state_data_box'> </div> </div> main.js $.ajax({ type: 'GET', url: '/register/states-json/', success: function(response){ const states_data = response.data states_data.map(item=>{ const option = document.createElement('div') option.textContent = item.name option.setAttribute('class', 'item') option.setAttribute('data_value', item.name) statesDataBox.appendChild(option) }) }, error: function(error){ … -
Set Cache in Django, but a data must dynamically
I have an issue, i want to save data to cache so when i need to get data i dont need it to get from database. But there is a data i need to get from database no matter what which is stock. Illustration i need to save to cache from db: ProductDetails:{ 'product_name': ...., 'categories':...., etc } but the stock product which i need to get is from the same db,i try to use multiple loop like this: ''' products = queryset() cache_key =f'test_detail_{parameter}' information = {} details = [] if not cache.get(cache_key): for product in products: information[product_id] = { 'product_name': product.name, 'date_input': product.date, 'weight':product.weight } cache.set(cache_key, information, duration) information = cache.get(cache_key) for key, value in information.items(): information[key][stock] = numpy.sum([x.stock for x in products if key == x.id ]) details.append(information[key]) return details ''' is there any method more efficient and effective using only 1 Queryset because i'm using 2 Queryset (the first time is when i get the data to set cache, the second time is when i get the stock data)? Thankss -
My VS Code shows false syntax error when I import while writing code for my Django project
My VS Code shows false syntax errors and underlines 'from __ import __ ' types of lines when I import something after writing a few lines of code. I'm doing a Django project and this keeps happening so much. It works after I close and re-open VS Code but that's hectic. I don't know what's causing it or how I can solve it. -
How Do I Get Django Poll Votes In Percentage Format?
I used the tutorial to create a polling app...and I've been expanding on it...I've got it working...but I can't figure out how to turn the votes into percentages... I have tried to do something like... def percentage(self): return 100 * (self.votes) / (self.survey) But this isn't working... My models look like... class Choice(models.Model): choice = models.TextField(max_length=264,blank=True,null=True,unique=False) survey = models.ForeignKey("Survey",on_delete=models.CASCADE,related_name="choice_survey") votes = models.IntegerField(default=0) class Survey(models.Model): survey_name = models.CharField(max_length=255,blank=True,null=True,unique=False) survey_type = models.CharField(choices=STATUS_CHOICES8,blank=True,max_length=300) I've seen examples of annotate and I've played with them as well. Do I need to keep track of the total number of votes as an attribute? The other examples I've seen are all foreignkey. I can totally get the number of votes by getting the integerfield. I just can't seem to figure out how to convert this into a percentage. Thanks in advance for any suggestions. -
mySQL - Web application only with private users
I am attempting to make a web app, where there is a login system and then once you have logged in you can add things to your personal list. I'm new to mySQL and website creation, so I'm a little confused on how to do this. I need a user database: users id username name email password 1 john123 john john@gmail.com password 2 jenna23 jenna jenna@gmail.com password3 But I also need a database the hold the data of the users. John's data looks like this: item-name type image cat animal cat.jpg cheeto food cheeto.jpg But Jenna's data looks like: item-name type image dog animal dog.jpg grapes food grapes.jpg I don't plan on the users being able to share data with each other like a blog post type system at least at this point. Right now I just want users to be use this site as a way to store their personal items. Should each user have their own table? Or should I just put all of their data in one database, but couldn't that mess up somehow? -
Scrapy ImportError: cannot import name 'HTTPClientFactory' from 'twisted.web.client' (unknown location)
Previously when I run this command in VSCode terminal, i didnt get any error. scrapy crawl ma -a start_at=1 -a end_and=2 -a quick_crawl=false But now, i don't know why it get this error 2022-07-20 10:10:14 [log.log_scrapy_info] INFO : Scrapy 2.2.1 started (bot: regulation_crawler) 2022-07-20 10:10:14 [log.log_scrapy_info] INFO : Versions: lxml 4.9.1.0, libxml2 2.9.14, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 22.4.0, Python 3.8.10 (default, Jun 22 2022, 20:18:18) - [GCC 9.4.0], pyOpenSSL 22.0.0 (OpenSSL 3.0.5 5 Jul 2022), cryptography 37.0.4, Platform Linux-5.15.0-41-generic-x86_64-with-glibc2.29 2022-07-20 10:10:14 [log.log_scrapy_info] DEBUG : Using reactor: twisted.internet.epollreactor.EPollReactor 2022-07-20 10:10:14 [crawler.__init__] INFO : Overridden settings: {'AUTOTHROTTLE_DEBUG': True, 'AUTOTHROTTLE_ENABLED': True, 'BOT_NAME': 'regulation_crawler', 'DOWNLOAD_DELAY': 0.5, 'FEED_EXPORT_INDENT': 4, 'LOG_FILE': '', 'LOG_FORMAT': '%(asctime)s [%(module)s.%(funcName)s] %(levelname)s : ' '%(message)s', 'LOG_LEVEL': 10, 'NEWSPIDER_MODULE': 'regulation_crawler.crawler.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['regulation_crawler.crawler.spiders'], 'USER_AGENT': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) ' 'Gecko/20100101 Firefox/84.0'} 2022-07-20 10:10:14 [telnet.__init__] INFO : Telnet Password: 42678d057d4fa701 2022-07-20 10:10:14 [warnings._showwarnmsg] WARNING : /home/fhadli/.cache/pypoetry/virtualenvs/regulation-crawler-_1wB9V_j-py3.8/lib/python3.8/site-packages/scrapy/extensions/feedexport.py:210: ScrapyDeprecationWarning: The `FEED_URI` and `FEED_FORMAT` settings have been deprecated in favor of the `FEEDS` setting. Please see the `FEEDS` setting docs for more details exporter = cls(crawler) 2022-07-20 10:10:14 [middleware.from_settings] INFO : Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.memusage.MemoryUsage', 'scrapy.extensions.feedexport.FeedExporter', 'scrapy.extensions.logstats.LogStats', 'scrapy.extensions.throttle.AutoThrottle', 'regulation_crawler.crawler.extensions.statsd.CrawlerStatsdExporterExtension'] 2022-07-20 10:10:14 [__init__._load_handler] ERROR : Loading "scrapy.core.downloader.handlers.http.HTTPDownloadHandler" for scheme "http" Traceback … -
How to save form instance created using sessionwizard class in django?
I want to save the created objects, but I can't get it to work. I can successfully fill out the form and submit it, but no data is saved in the database. Any suggestions as to what I'm doing incorrectly? I tried using form_data[0].save but it threw 'dict' object has no attribute 'save' views from django.shortcuts import render from formtools.wizard.views import SessionWizardView from django.core.files.storage import FileSystemStorage from .forms import ( WithdrawForm1, WithdrawForm2, ) from django.conf import settings import os class WithdrawWizard(SessionWizardView): template_name = 'withdraw.html' form_list = [WithdrawForm1, WithdrawForm2] file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'media_root')) def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] return render(self.request, 'done.html', {'data': form_data}) Template {% load i18n %} {% block head %} {{ wizard.form.media }} {% endblock %} {% block content %} <div class="row d-flex justify-content-center" style="height: 50vh;"> <div class="col-md-6"> <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post" enctype=multipart/form-data>{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" type="submit" value="{{ … -
Div Columns not aligning correctly in Django/Python
I'm following along a tutorial and, unfortunately, his code editor automatically indented everything when he copied/pasted a new <div> (Sigh) (In the second pic I cut off the top where it has LOGO in the top right on accident in the screenshot) This is what it currently looks like This is what it should look like Room.html File {% extends 'main.html' %} {% block content%} <div class="room-container"> <div> <style> .room-container( display: grid; grid-template-columns: 3fr 1fr; ) </style> <div class="room-container"> <div> <h1>{{room.name}}</h1> <p>{{room.description}}</p> <div class="comment-wrapper"> <h3> Conversations </h3> <hr> {% for message in room_messages %} <div> <a href="{% url 'delete-message' message.id %}">Delete</a> <small>@{{message.user}} {{message.created|timesince}} ago </small> <p>{{message.body}}</p> <hr> </div> {% endfor %} </div> <div> {% if request.user.is_authenticated %} <div class="comment-for"> <form method="POST" action=""> {% csrf_token %} <input type="text" name="body" placeholder="Comment here.." /> </form> </div> </div> </div> {% endif %} <div> <h3>Participants</h3> <hr> {% for user in participants %} <div> <p>@{{user.username}}</p> </div> {% endfor %} </div> </div> {% endblock %} Main.html file <!DOCTYPE html> <html> <head> <meta charset='utf-9'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>StudyBud</title> <meta name='viewport' content='width=device-width, initial-scale=1'> </head> <body> {% include 'navbar.html' %} {% if messages %} <ul class="messages"> {% for message in messages %} <li></li>{{ message }}</li> {% endfor %} </ul> {% … -
Not able to delete whole object from CART model in django
Using ajax I am sending a post to delete a cart item but for some reason it delete's product quantity from and the object there with foreign key due to which it sends an error because I am using property to return total cost. Here is my model and code. Error that I am getting unsupported operand type(s) for *: 'NoneType' and 'int' ''' class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) product_quantity = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) @property def total_cost(self): return self.product_quantity * self.product.product_price ''' Here is my views.py ''' def removeitemfromcart(request): if request.method == "POST": product_id = int(request.POST.get('product_id')) if Cart.objects.filter(user=request.user, product_id=product_id): cartitem = Cart.objects.get(product_id=product_id, user=request.user) cartitem.delete() return JsonResponse({'status': 'Deleted Successfully'}) return redirect('/') ''' Here is the object that got deleted Cart item that I tried to delete -
Django and Querysets redundancy - Making more efficient?
So I've been working on this piece of code and since I only have the view to play with, I was wondering if there are inputs to making this more efficient (specially the user_total_xx parts). Background: I have already accomplished this using raw SQL queries but I'm trying to convert it, trying to make it efficient and learning along the way. Would love some experts to chime in since I'm very new to this. @action(detail=True, methods=['GET'], url_path='', url_name='') def reporting(self, request, *args, **kwargs): request_body = json.loads(request.body) user_id = request_body['user_id'] start = request_body['start'] end = request_body['end'] vendor_name = request_body['vendor_name'] org_id=request_body['org_id'] billing_frequency = request_body['billing_frequency'] c1=Q(user=user_id) c2=Q(vendor__name=vendor_name) c3=Q(id=org_id) c4=Q(billing_frequency=billing_frequency) all_reports = Task.objects.filter(start__gte=start, start__lte=end) #all tasks within given dates if not user_id: if not vendor_name: if not billing_frequency: query = all_reports.values() user_total_bill = all_reports.annotate(b_tot=Sum(F('hours') * F('bill_rate'))).aggregate(total=Sum('b_tot')).values() user_total_pay = all_reports.annotate(p_tot=Sum(F('hours') * F('pay_rate'))).aggregate(total=Sum('p_tot')).values() return JsonResponse(list(chain(query, user_total_bill, user_total_pay)), safe=False) #all user data else: vendors = Vendor.objects.filter(c4).values('name', 'billing_frequency') vendor_user=Vendor.objects.filter(c4).values_list('id') #vendor id's for given billing freq query = all_reports.filter(vendor_id__in=vendor_user).values() #user data user_total_bill = query.annotate(b_tot=Sum(F('hours') * F('bill_rate'))).aggregate(total=Sum('b_tot')).values() user_total_pay = query.annotate(p_tot=Sum(F('hours') * F('pay_rate'))).aggregate(total=Sum('p_tot')).values() return JsonResponse(list(chain(vendors, query, user_total_bill, user_total_pay)), safe=False) else: # vendor_user=Vendor.objects.filter(c2).values_list('id') #vendor info # query = Task.objects.filter(vendor_id__in=vendor_user).values() vendors = Vendor.objects.all().values('name', 'billing_frequency') query = all_reports.filter(c2).values() user_total_bill = query.annotate(b_tot=Sum(F('hours') * F('bill_rate'))).aggregate(total=Sum('b_tot')).values() user_total_pay … -
My action button is causing 404 not found
Here is my Base.html <div class="container"> <div class="center"> <form action='simple_test'> <button id="simple_test" class="button-3d"> Generate</button> </form> </div> </div> Here is my View.py from django.http import HttpResponse from django.shortcuts import render from datetime import datetime from django.template import loader from django.core.files import File from .unun import some_func import random import os def index(request): strinput = {} glued, oldgued = some_func() strinput['IntPassHMTL'] = 433 strinput['StrPassHMTL'] = glued strinput['BeforeGlued'] = oldgued return render(request,'index.html', strinput ) def simple_test(request): strinput = {} # glued, oldgued = some_func() strinput['IntPassHMTL'] = 433 strinput['StrPassHMTL'] = "glued" strinput['BeforeGlued'] = "oldgued" print("Words?") return HttpResponse("This is a fake 404!") Here is my urls.py urlpatterns = [ path('admin/', admin.site.urls), print("simple_test", views.simple_test), path('', views.index, name="index"), ] First of all please do not downvote because I am trying to learn and I understand many people have asked the same or similar questions however, I still have so much to learn and I tried to apply these solutions to my codes and they still do not work right for me not sure what I am missing, and that is why I am here, please help me. -
Django Queryset + looking for all objects that have ALL values in an array in a many-to-many relationship
I am hard coding it here, but in reality this array can have between 1 and 99 values looking_for = ['blue', 'red', 'green'] objects = MyObj.objects.filter(colors__name__in=looking_for) will give me all the objects that have ONE of the colors in ['blue', 'red', 'green'] But I want the objects that have ALL the colors objects with the names mentioned in the array. I want AND not OR. Could not find how to do that. any ideas? -
Django admin edit only field?
I have a model that I only want to use one row of its table. So, on admin, I would like to remove the list and add pages, and only edit the existing object. The model is this: from django.db import models class BannerImg(models.Model): img = models.ImageField(upload_to="banners") banner = models.ForeignKey("app.Model", verbose_name=(""), on_delete=models.CASCADE) class Banner(models.Model): pass Basically, the Banner(pk=1) will be loaded by the frontend to display a landing page hero slider. I want multiple images, but also want them to be on the same admin form, so one could order, add or remove images from the same place. Of course having to Banner objects, wouldn't make sense in this case. I can use inline fields to do the form, but how can I achieve the pages functionality (going directly to edit)? Thanks! -
test return redirect("account_login") in django use pytest
i using pytest and coverage for testing django project But I don't know how to test the else block that has return redirect("account_login") and fix the red part that says coverage. In your opinion, how can I write a test for that else piece and fix the red part that says coverage? views.py @verified_email_required def profile_view(request, username): # We check if the user is logged in? if request.user.is_authenticated: try: profiles = Profile.objects.all()[:4] # get user profile by username profile = Profile.objects.get(user__username__iexact=username) user = User.objects.get(username=username) user_following = following(user) user_followers = followers(user) logged_in_user_following = following(request.user) logged_in_user_followers = followers(request.user) # if user not found raise 404 error except ObjectDoesNotExist: raise Http404 # context data context = { "user": user, "profile": profile, "profiles": profiles, "following": user_following, "followers": user_followers, } return render(request, "user_profile/profile.html", context) # if a user is not login in redirecting to login page else: return redirect("account_login") test_view.py @pytest.mark.django_db class TestProfileView: @pytest.fixture def user(self): user, created = User.objects.get_or_create( # created user username="test_username", first_name="test_first_name", last_name="test_last_name", email="test@test.com", is_active=True, is_superuser=False, ) ( user_email_address, created, ) = EmailAddress.objects.get_or_create( # user email confirmation email=user.email, user=user ) user_email_address.verified = True user_email_address.primary = True user_email_address.save() return user def test_profile_view_when_user_is_authenticated_return_correct_profile( self, user, client ): client.force_login(user) # user logged in response = …