Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to change errors in Django rest framework like PK to ID
{ "status": 400, "errors": [ "designation Invalid pk "2" - object does not exist.", "provincedetails Invalid pk "10" - object does not exist." ] } I know why this errors is throwing because relation object is not exist so.. But I want to customize this error like to remove PK and add ID, is that possible to do? -
Show and hide elements in different tabs with JQuery
There are a few similar questions but not one that quite answers mine. I have a page with several different tabs, and a Django form with different filters as fields which is used in the template. The form fields 'west_region' and 'east_region' have different choices. I want to show a different filter depending on which tab is open. Can I use JQuery and the hash value to do this? This is my music.html template: {% block page-content %} <div class="card mb-4"> <div class="card-block"> <form class="ui-filter"> <div class="ui-filter--fields"> <!-- West region filter --> <div class="ui-filter--field" id="west-region"> <label for="supplier_elec">Region:</label> <div class="form-full-width">{{ form.west_region }}</div> </div> <!-- East region filter --> <div class="ui-filter--field" id="east-region"> <label for="supplier_gas">Region:</label> <div class="form-full-width">{{ form.east_region }}</div> </div> </div> <div class="ui-filter--submit"> <button class="btn btn-primary btn-block" type="submit">Apply Filters</button> </div> </form> </div> </div> <div class="row"> <div class="col"> <div class="tab-content content py-4"> <div class="tab-pane active container-fluid" id="jazz" role="tabpanel"> <div class="row align-items-center"> <div class="col-sm-8 col-xl-10 col-12"> <h1>Jazz</h1> </div> </div> <h2>Songs</h2> {% include 'jazz.html' %} </div> <div class="tab-pane container-fluid" id="rock" role="tabpanel"> <div class="row align-items-center"> <div class="col-sm-8 col-xl-10 col-12"> <h1>Rock</h1> </div> </div> <h2>Songs</h2> {% include 'rock.html' %} </div> </div> </div> </div> {% endblock %} {% block extrascripts %} <script> $('#music-genre a').click(function(e) { e.preventDefault(); $(this).tab('show'); }); $("ul.nav-tabs > … -
Python: CalledProcessError, command returned non-zero exit status 1
I am getting this error Command '['settings.PDF_TO_TEXT', '-layout', 'absolute_file_path', '-']' returned non-zero exit status 1. here is what I want to achieve. def get_queries(filename, num_queries=3): scored_chunks = [] absolute_file_path = os.path.join(settings.MEDIA_ROOT, filename) # pdf_to_text_output = subprocess.check_output([settings.PDF_TO_TEXT, "-layout", absolute_file_path, "-"], shell=true) pdf_to_text_output = subprocess.check_output(['settings.PDF_TO_TEXT', "-layout", 'absolute_file_path', "-"], shell=True) try: text = pdf_to_text_output.decode('utf-8') except UnicodeDecodeError: text = pdf_to_text_output.decode('ISO-8859-1') ....... I am new to Django and python, I have tried many solutions but nothing is working for me. because I don't know how it works. here is the full traceback. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/index/ Django Version: 3.1.2 Python Version: 3.7.4 Traceback (most recent call last): File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Farhana Noureen\plagtrap\main\views.py", line 302, in post results = process_homepage_trial(request) File "C:\Users\Farhana Noureen\plagtrap\main\services.py", line 435, in process_homepage_trial queries = pdf.get_queries(filename) File "C:\Users\Farhana Noureen\plagtrap\util\getqueriespertype\pdf.py", line 18, in get_queries pdf_to_text_output = subprocess.check_output(['settings.PDF_TO_TEXT', "-layout", 'absolute_file_path', "-"], shell=True) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 395, in check_output **kwargs).stdout File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 487, … -
Render React Static files with django
Hope you all are doing well I am trying to connect my react frontend to my django REST-API, which doesn't seem to go well at the moment, in the react development server the application is working quite well but as in terms while exporting its static files to django things seem to crash at the point. The following process was followed to achieve the goal run npm run build command to get the build directory within the react app. Copied and pasted the build/static directory to my BASE_DIR Changed my settings.py for the django project to the following STATIC_URL = '/static/' STATICFILE_DIRS=[ os.path.join(BASE_DIR,'static') ] STATIC_ROOT= os.path.join(BASE_DIR,'static-root') and then finally running the command python manage.py collectstatic which copied over 160 files into my static-root directory. This is what my project structure looks like the collectstatic command doesn't seem to copy my react static files in spite the fact that I have mentioned that static directory which contains the react files. Which is the reason that I cannot access my react static files, any help on how to render the react files django or mistakes in my strategy while development would be highly appreciated. -
Download Uploaded Files in Django Admin Action
I am trying to create an admin action in django to download the selected files uploaded by the users. I can view the uploaded file one by one and use the save link as for saving the file/images. But I want to download more than one by selecting and save them to a zip folder for download in one go. I use this download users' pdf in django as reference and created the below code. I was able to download a zip file but when i opened it,it says the zip file is not valid. I believe there is something wrong with querying the file url/writing it to the zip folder. Please assist. import tempfile import zipfile def downloadPic(self, request, queryset): with tempfile.SpooledTemporaryFile() as tmp: with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as archive: for index, item in enumerate(queryset): projectUrl = str(item.file.url) + '' fileNameInZip = '%s.zip' % index archive.writestr(fileNameInZip, projectUrl) tmp.seek(0) response = HttpResponse(tmp.read(), content_type='application/x-zip-compressed') response['Content-Disposition'] = 'attachment; filename="pictures.zip"' return response -
Bootstrap4 HTML page is too big on mobile
I'm a relative noob with bootstrap and css. I've rebuilt this site from the ground up a couple times in the last couple of weeks to try and sort the spacing etc and currently I have the problem that the main section is slightly too big for a mobile screen in the x dimension and can be scrolled, which is obviously unwanted behaviour. I've tried so many configurations and am so confused as to where this apparent right margin is coming from. (The content fills the screen until you scroll leaving a significant sliver of background body colour. I've tried debugging by setting the background colour of different elements and the margin shows black with the body background, but white with main, i.e is between the body and the main. I have tried doing this in my css: html { overflow-y: scroll; overflow-x: hidden; // this solves the problem on a small browser window but not on mobile device. margin: 0; padding: 0; } body { margin: 0; padding: 0; } main { margin: 0; padding: 0; background-color: #000; // this is what i was referring to that leaves a white margin after scrolling if this color is in the … -
If date not in queryset add default value
Im integrating django with chartjs. I use classbasedview like below. class SingleTagChartJSONView(BaseLineOptionsChartView): def get_context_data(self, **kwargs): context = super(BaseLineChartView, self).get_context_data(**kwargs) date_year = int(str(context["year"])) date_month = int(str(context["month"])) specific_date = datetime(date_year, date_month, 1) obj_tags = mitop_tags.objects.filter( tag_publish_date__year=specific_date.year, tag_publish_date__month=specific_date.month, post_tag_single=str(context['tag'])).extra( {'day' : "date(tag_publish_date)"} ).values('day').annotate( tag_occur=Count('post_tag_single')) I get obj_tags output like this: {'day': datetime.date(2020, 10, 16), 'tag_occur': 3} {'day': datetime.date(2020, 10, 17), 'tag_occur': 3} {'day': datetime.date(2020, 10, 18), 'tag_occur': 1} {'day': datetime.date(2020, 10, 19), 'tag_occur': 2} {'day': datetime.date(2020, 10, 20), 'tag_occur': 1} {'day': datetime.date(2020, 10, 22), 'tag_occur': 6} {'day': datetime.date(2020, 10, 23), 'tag_occur': 8} {'day': datetime.date(2020, 10, 24), 'tag_occur': 8} {'day': datetime.date(2020, 10, 26), 'tag_occur': 8} {'day': datetime.date(2020, 10, 27), 'tag_occur': 6} {'day': datetime.date(2020, 10, 28), 'tag_occur': 6} {'day': datetime.date(2020, 10, 30), 'tag_occur': 3} {'day': datetime.date(2020, 10, 31), 'tag_occur': 7} I want to add default value for not existing date (record) in queryset. {'day': datetime.date(2020, 10, 1), 'tag_occur': 0} In that case from 1-15 then missing 25 and 29. Desired output {'day': datetime.date(2020, 10, 1), 'tag_occur': 0} {'day': datetime.date(2020, 10, 2), 'tag_occur': 0} {'day': datetime.date(2020, 10, 3), 'tag_occur': 0} {'day': datetime.date(2020, 10, 4), 'tag_occur': 0} {'day': datetime.date(2020, 10, 5), 'tag_occur': 0} {'day': datetime.date(2020, 10, 6), 'tag_occur': 0} {'day': datetime.date(2020, 10, 7), 'tag_occur': 0} {'day': datetime.date(2020, … -
For some migrations, why `sqlmigrate` shows empty, or the same SQL both directions?
I'm working on upgrading a legacy project, currently still on Python 2.7.18 as the highest Python-2 before upgrade to 3. After upgrading Django from 1.8.13 to 1.11.29, the project requires some database changes (unapplied migrations), and I'm using command python manage.py sqlmigrate to review the SQL statements. I have some questions, and any inputs will be highly appreciated: Some migrations, e.g. 0002_logentry_remove_auto_add below, SQL only contains comment, I'm wondering why. (venv) [ebackenduser@setsv EBACKEND]$ python manage.py sqlmigrate admin 0002_logentry_remove_auto_add BEGIN; -- -- Alter field action_time on logentry -- COMMIT; For migration 0002_auto_20160226_1747, SQL is the same for both forward and backward (--backwards) directions, and I'm also wondering 1) why, and 2) whether this should be a concern. Just want to be cautious with the production database, and thank you for your pointers. (venv) [ebackenduser@setsv EBACKEND]$ python manage.py sqlmigrate authtoken 0002_auto_20160226_1747 BEGIN; -- -- Change Meta options on token -- -- -- Alter field created on token -- -- -- Alter field key on token -- -- -- Alter field user on token -- ALTER TABLE `authtoken_token` DROP FOREIGN KEY `authtoken_token_user_id_535fb363_fk_auth_user_id`; ALTER TABLE `authtoken_token` ADD CONSTRAINT `authtoken_token_user_id_35299eff_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); COMMIT; (venv) [ebackenduser@setsv EBACKEND]$ python manage.py sqlmigrate --backwards authtoken … -
Django queryset in multiple tables
I have this kind of query using PostgreSQL: SELECT tbl_project_lu.project_id, tbl_project_lu.house_id, tbl_project_lu.project_name AS project, tbl_house_lu.house_name, tbl_project_lu.description, tbl_house_mbr.person_id FROM ((tbl_house_lu INNER JOIN tbl_house_mbr ON tbl_house_lu.house_id = tbl_house_mbr.house_id) INNER JOIN tbl_project_lu ON tbl_house_lu.house_id = tbl_project_lu.house_id) INNER JOIN tbl_proj_mbr ON (tbl_project_lu.project_id = tbl_proj_mbr.project_id) AND (tbl_house_mbr.house_mbr_id = tbl_proj_mbr.house_mbr_id) WHERE person_id = 'foo'; What is the best way to use this kind of query in django? Can Django ORM handle this kind of query or do I have to use stored proc for this? -
Getting error after changed sqlite to mysql, table doesn't exist?
i've finished developing a django project and wanted to change sqlite3 to MySql for a better database option. I tried in an empty project to change database, it worked like a charm. But now i changed db of my project and when i try to do python manage.py makemigrations it returns; django.db.utils.ProgrammingError: (1146, "Table 'tvekstra-django-tracker.tvchannels_channels' doesn't exist") Any help is appreciated, thanks. -
How to get access to authenticated, logged in user in vue.js and django rest framework
I want to get access to authenticated, currently logged in user, eg. to username and id, and to put it in to the form by default when I'm using POST method. My login component: import axios from 'axios'; export default { name: 'LoginForm', components: { }, data(){ return{ username: '', password: '', token: localStorage.getItem('user-token') || null, } }, methods: { login(){ axios.post('http://127.0.0.1:8000/auth/',{ username: this.username, password: this.password, }) .then(resp => { this.token = resp.data.token; localStorage.setItem('user-token', resp.data.token) this.$router.push(this.$route.query.redirect || '/') }) .catch(err => { localStorage.removeItem('user-token') }) } } } </script> Could you help me? -
Setting up Domain on DigitalOcean to Django & Nginx
Finishing up site migration, I've been able to get it running on the droplet IP I've also checked if IP propagation is complete and I've added the domain to digitalocean When I try the domain I get This site can’t be reached. I've tried to set up the nginx file to match this server { listen 80; server_name http://safariguides.org 162.243.173.84 safariguides.org; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/webapps/kpsga; } location /media/ { root /home/sammy/webapps/kpsga; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and in the settings file DEBUG = True ALLOWED_HOSTS = [ 'http://safariguides.org', 'http://162.243.173.84/', '*' ] finally adding the * for maximum matches. checking for errors in nginx logs shows this sammy@kpsga:~/webapps/kpsga/kpsga$ sudo tail -F /var/log/nginx/error.log 2020/11/03 06:55:50 [warn] 70740#70740: server name "http://safariguides.org" has suspicious symbols in /etc/nginx/sites-enabled/kpsga:3 2020/11/03 07:00:36 [alert] 70778#70778: *14 open socket #16 left in connection 9 2020/11/03 07:00:36 [alert] 70778#70778: *15 open socket #17 left in connection 10 2020/11/03 07:00:36 [alert] 70778#70778: aborting 2020/11/03 07:00:36 [warn] 70858#70858: server name "http://safariguides.org" has suspicious symbols in /etc/nginx/sites-enabled/kpsga:3 2020/11/03 07:00:36 [warn] 70869#70869: server name "http://safariguides.org" has suspicious symbols in /etc/nginx/sites-enabled/kpsga:3 2020/11/03 07:04:34 [warn] 70893#70893: server name "http://safariguides.org" has suspicious … -
access database from dajngo views class
when I run my server,(in my website) in this case I get Error that is table not found. when I call this function in another class(not in views) it works! How can I solve this problem? `def calculate(request): vt =sql.connect('../db.sqlite3') imlec = vt.cursor() imlec.execute("SELECT pain from kaktüs_kaktüs WHERE id = (SELECT MAX (id) FROM kaktüs_kaktüs)") idsa = imlec.fetchone() for i in idsa: i image_a = Image.open(str(i)) image_a_array = np.array(image_a) print("1.resim Array") print("*************************************************************************") print(image_a_array) imlec.execute("SELECT pain_two FROM kaktüs_kaktüs WHERE id = (SELECT MAX (id) FROM kaktüs_kaktüs)") idsb = imlec.fetchone() for i in idsb: i image_b = Image.open(str(i)) image_b_array = np.array(image_b) print("2.resim Array") print("*************************************************************************") print(image_b_array) imlec.execute("SELECT pain_three FROM kaktüs_kaktüs WHERE id = (SELECT MAX (id) FROM kaktüs_kaktüs)") idsc = imlec.fetchone() for i in idsc: i image_c = Image.open(str(i)) image_c_array = np.array(image_c) print("3.resim Array") print("*************************************************************************") print(image_c_array) imlec.execute("SELECT pain_four FROM kaktüs_kaktüs WHERE id = (SELECT MAX (id) FROM kaktüs_kaktüs)") idsd = imlec.fetchone() for i in idsd: i image_d = Image.open(str(i)) image_d_array = np.array(image_d) print("4.resim Array") print("*************************************************************************") print(image_d_array) return render(request,"anasayfa.html")` -
Which field in Django model to choose for a file downloaded via API endpoint?
I am using Django 2.2 LTS I have a function that will download a file from endpoint def download_as_file(url: str, auth=(), file_path="", attempts=2): """Downloads a URL content into a file (with large file support by streaming) :param url: URL to download :param auth: tuple containing credentials to access the url :param file_path: Local file name to contain the data downloaded :param attempts: Number of attempts :return: New file path. Empty string if the download failed """ if not file_path: file_path = os.path.realpath(os.path.basename(url)) logger.info(f"Downloading {url} content to {file_path}") url_sections = urlparse(url) if not url_sections.scheme: logger.debug("The given url is missing a scheme. Adding http scheme") url = f"https://{url}" logger.debug(f"New url: {url}") for attempt in range(1, attempts + 1): try: if attempt > 1: time.sleep(10) # 10 seconds wait time between downloads with requests.get(url, auth=auth, stream=True) as response: response.raise_for_status() with open(file_path, "wb") as out_file: for chunk in response.iter_content(chunk_size=1024 * 1024): # 1MB chunks out_file.write(chunk) logger.info("Download finished successfully") return (response, file_path) except Exception as ex: logger.error(f"Attempt #{attempt} failed with error: {ex}") return None I also intend to have a Django model to store metadata associated with that downloaded file. class DownloadedFile(models.Model): # other fields but i skipped most of them here local_copy = models.FileField(upload_to="downloads/") … -
Custom user creation form always invalid in Django
I am working on building a new Django Website and am trying to make an abstract base class and using forms to fill it out. I thought I was doing it correctly, but whenever I try to fill out the form it is always invalid. I am wondering if anyone can help me with this problem. All of the other help I find online does not help me. Here is my code. Thanks My forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Profile class CustomUserCreationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def __init__(self, regLinkModel): super(CustomUserCreationForm, self).__init__() self.linkInfo = regLinkModel def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['fname'] user.last_name = self.cleaned_data['lname'] user.password1 = self.cleaned_data['password1'] user.password2 = self.cleaned_data['password2'] if commit: user.save() return user My Models.py class MyAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password): if not email: raise ValueError("User needs email address") if not username: raise ValueError("User needs username") if not first_name: raise ValueError("User needs first name") if not last_name: raise ValueError("User needs last name") user = self.model( email=self.normalize_email(email), password = password, username =username, first_name = … -
I was trying to run django qcluster in my local machine and getting this error - Any help would be really appreciated
I'm doing this to run the DjangoQ - This is my Q_CLUSTER config inside my settigns.py file - Q_CLUSTER = { 'name': 'default_orm', 'compress': True, 'save_limit': 0, 'orm': 'default' } python manage.py qcluster File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/multiprocessing/reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) AttributeError: Can't pickle local object 'BaseDatabaseCache.__init__.<locals>.CacheEntry' -
TypeError: create_user() missing 3 required positional arguments(when createsuperuser)
I get this error when trying to create superuser: TypeError: create_user() missing 3 required positional arguments: 'first_name', 'last_name', and 'role' Is this the proper way to create it? I want to create superuser without username, just with email, and user can login only with their email addresses, and now when I create superuser it wants email, how I wanted, but gives me the error too. class MyAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, role, password=None, **extra_fields): if not email: raise ValueError("Users must have an email address") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, role=role, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password ) user.is_admin = True user.is_employee = True user.is_headofdepartment = True user.is_reception = True user.is_patient = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractUser): ADMIN = 1 RECEPTION = 2 HEADOFDEPARTMENT = 3 EMPLOYEE = 4 PATIENT = 5 NOTACTIVE = 6 ROLE_CHOICES = ( (ADMIN, 'Admin'), (RECEPTION, 'Reception'), (HEADOFDEPARTMENT, 'HeadOfDepartment'), (EMPLOYEE, 'Employee'), (PATIENT, 'Patient'), (NOTACTIVE, 'NotActive'), ) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, blank=True, default=True, null=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) is_headofdepartment = models.BooleanField(default=False) is_reception = models.BooleanField(default=False) is_patient … -
get current domain name in settings.py file
I am running a multisite project with various tenant domains. In my settings.py file, I have a variable name called TENANT_DOMAIN that I would want to set the current tenant domain name before the settings file is run. How do I go about this? -
Django reset password using phone number or email
I am creating a mobile app with django and drf. I am giving users the option to register using phone number or email. For email I can obviously use the built in PasswordResetView however I have no idea how to reset password using the phone number. Here is my User model class User(AbstractBaseUser): email = models.EmailField( null=True, blank=True, verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name='username', max_length=100, unique=True) phone_number = PhoneField( max_length=10, blank=True, null=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'username' objects = UserManager() -
Deploying Django application on LAN
I have a Django application that I want to deploy on LAN for use/production. I need a help how to deploy it on Windows Server (Step by step). -
in python how to access half iterate forloop value outside without if condition
i am iterating a large number of list like 100,000 data. I want to know how much iteration is completed outside of the loop. I don't want to use if condition. if condition increases execution time. def callme(): for data in range(100000): # i want to return 'data' after every 5 seconds. # without if condition return data -
how i can solve these error on django runserver
Whenever i want to run a server of django these error message shows in my VS code (django) PS C:\python\New folder\django\To_Do> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "c:\python\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\python\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\python\New folder\django\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\python\New folder\django\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run -
python django: How to fix error saying: AttributeError at / 'Home' object has no attribute 'get'
i'm trying to create two pages for my website in django. I get an Error: AttributeError at /'Home' object has no attribute 'get' The above 'Home' is a class in my models but I do not know why it says 'Home object no attribute get' when I have called Home.objects.all() in my views.py My models: from django.db import models class Product(models.Model): name = models.CharField(max_length=20) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Home(models.Model): heading = models.CharField(max_length=10) words = models.CharField(max_length=10000) My views: from django.http import HttpResponse from django.shortcuts render from .models import Product, Home def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) def home(request): home_obj = Home.objects.all() return render(request, 'home.html', {'Home': home_obj}) My app urls: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('fruits/', views.index), path('', views.Home), ] index.html: {% extends 'base.html' %} {% block content %} <div class="row"> {% for product in products %} <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{ product.image_url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">₹ {{ product.price }}</p> <a href="#" class="btn btn-primary">add to cart</a> </div> </div> </div> {% endfor %} </div> {% endblock %} home.html: <h2>{{ home_obj.heading }}</h2> <p>{{ home_obj.words }}</p> … -
How to search for objects in the Django User model
I have a Profile model: from django.contrib.auth.models import User class Profile(models.Model): first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=100, blank=True) And a search contacts view: class SearchContactsView(ListView): model = Profile template_name = 'users/contact_search.html' context_object_name = 'qs' def get_queryset(self): q1 = self.request.GET.get('contact_name') q2 = self.request.GET.get('contact_location') if q1 or q2: return Profile.objects.filter(Q(first_name__icontains=q1) | Q(last_name__icontains=q1), location__icontains=q2) return Profile.objects.all() It is working fine but I would like to be able to search for contacts via the user field as well. Does anyone know a way to do that? -
What command do we use to create a folder in pycharm?
I was coding in python. I typed this code python3 manage.py startapp products in order to create a folder, and I tried to find the folder, but I did not see nothing appeared. May someone help me to fix it please?