Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django search function that calls other views return ValueError
I created a view function to capture all search queries and then treat each depending on the type of search. In first step, I tried to pass all queries to another view function to see if this approach works: in main app urls.py from searchapp.views import search urlpatterns += [ path('search', search) ] in views.py for searchapp def search(request): if request.method == 'GET': return other_view_function(request, query=request.GET.get('q')) else: return HttpResponseNotFound('Search query is not provided.') However, I get value error no matter I include q in the call or not: The view searchapp.views.search didn't return an HttpResponse object. It returned None instead. It's probably an obvious syntax error that I can't see! -
Keeping value selected after another form search
I am having a problem with keeping last selected value in my form. On my page I have got 2 forms, one is made for filtering results that are inside a specific category and the other one is having a function of changing the category. My template looks like that: <form method="GET" action="{% url 'core:category_search' category.id %}"> <h5>Search</h5> <div class="form-row"> <div class="form-group col-8"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="q" placeholder="Brand.." value="{{request.GET.q}}"> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> <h5>Price from</h5> <div class="form-row"> <div class="form-group col-5"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="price_from" placeholder="Price from" value="{{request.GET.price_from}}"> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> <h5>Price to</h5> <div class="form-row"> <div class="form-group col-5"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="price_to" placeholder="Price to" value="{{request.GET.price_to}}"> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> <div class="form-row "> <div class="form-group col-5"> <label for="category">Brand</label> <select id="bra" class="form-control" name="bra"> <option value="" {% if not request.GET.bra %} selected {% endif %}>Choose...</option> {% for bra in brand %} <option value="{{ bra.pk }}" {% if request.GET.bra == bra.pk|slugify %} selected {% endif %}> {{ bra }}</option> {% endfor %} … -
how to print images in html from python(Django)
hi please anyone to help me out with this, the code i have here is taking screenshots and saving it in my media folder so i want to print the pictures out in my html page but it's giving me issues, i think i'm missing a lot this is my python code that is taking the screenshots from django.http import HttpResponse import time,random,pyautogui from django.db import models import sys,os from shots.models import pictures from shots.forms.forms import DocumentForm from django.conf import settings def button(request): return render(request,'index.html') def output(request): while True: myScreenshot = pyautogui.screenshot() name = random.randrange(1,1000) full_name = str(name) + ".jpg" filepath = settings.MEDIA_ROOT + '\shots' full_path = filepath + full_name saver = myScreenshot.save(full_path) # generate a random time between 120 and 300 sec random_time = random.randrange(3,6) # wait between 120 and 300 seconds (or between 2 and 5 minutes) time.sleep(random_time) myScreenshots2 = [] myScreenshots2.append(saver) # return (myScreenshots2) return HttpResponse(request,'task.html',saver) def stopshot(request): os.system("pause")``` -
TypeError: __init__() missing 1 required positional argument: 'on_delete' how can i solve this
Python 3.8.1 django version 3.0.3 when i am run this code i am getting this error TypeError: __init__() missing 1 required positional argument: 'on_delete' Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User) #additional profile_site = models.URLField(blank = True) profile_pic = models.ImageField(upload_to = 'profile_pics', blank = True) def __str__(self): return self.user.username forms.py from django import forms from django.contrib.auth.models import User from basic_app.models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput()) class meta(): model = User fields = ('username', 'email', 'password') class UserProfileInfo(forms.ModelForm): class meta(): model = UserProfileInfo fields = ('profile_site', 'profile_pic') -
Make Migrations on Django
I have a Django model which looks like this class RedUsers(BaseModel): user_email = models.EmailField(null=True, blank=True) user_name = models.CharField(max_length=30, null=True, blank=True) red_id = models.CharField(max_length=30, null=True, blank=True) active = models.BooleanField(default=False) def __str__(self): return self.user_email class Meta: verbose_name_plural = "Red Users" I want to add a new field activation_key = models.CharField(max_length=40, null=True, blank=True) I already have lots of data in this model and I can't drop the table, so I need to make migration manually. I have tried adding the model from my 0001_initial.py file without luck class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name='RedUsers', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('user_email', models.EmailField(blank=True, max_length=254, null=True)), ('user_name', models.CharField(blank=True, max_length=30, null=True)), ('red_id', models.CharField(blank=True, max_length=30, null=True)), ('active', models.BooleanField(default=False)), ], options={ 'verbose_name_plural': 'RED Users', }, ), migrations.AddField( model_name='redusers', name='activation_key', field=models.CharField(blank=True, max_length=40, null=True, verbose_name='activation key'), ), ] When I run python manage.py migrate It says Your models have changes that are not yet reflected in a migration, and so won't be applied. I don't know what else to do -
Is django-cors-headers necessary when operating on a subdomain?
I plan to run Django as an API with django-rest-framework. This API will power a Vue.js web app hosted on a separate platform. If I configure the API to run on api.example.com and the web app to run on www.example.com, is django-cors-headers required for the API to process requests from the frontend? Also, how does this work with cookies? I'd prefer to authenticate via http-only cookies, with no localstorage of tokens. -
Issue with Django Admin and autocomplete (Select2) filter with reverse foreignkey
I am working on Django 2.2.10 and Python 3.5. I wanted to use feature that was introduced in Django 2, that is to use Select2 to filter lists from a different model that has reverse relation to the model I am listing, which is displayed as Inline in Django Admin. Let me explain. I have two models like this: models.py class Books(models.Model): name = models.CharField(max_length=40) pages = models.PositiveSmallIntegerField(default=0) class Members(models.Model): member_name = models.CharField(max_length=40) member_years = models.PositiveSmallIntegerField(default=0) class BorrowedBooks(models.Model): book = models.ForeignKey(Books, on_delete=models.CASCADE) member = models.ForeignKey(Members, on_delete=models.CASCADE) date_borrowed = models.DateField() date_returned = models.DateField() admin.py class BorrowedBooksInline(admin.TabularInline) model = BorrowedBooks extra = 0 fields = ['book', 'member', 'date_borrowed', 'date_returned'] search_field = ['book'] class BooksAdmin(admin.ModelAdmin): model = Books list_display = ['name', 'pages'] class MembersAdmin(admin.ModelAdmin): model = Members inlines = [BorrowedBooksInline, ] list_display = ['member_name', 'member_years'] autocomplete_fields = ['borrowedbooksinline__book'] search_field = ['member_name', 'member_years'] I haven't copied everything because it would be too much. Basically, what I would like to do is to be able to filter members that borrowed book at certain point in time, but the two models are not linked directly but through third model. At this time everything runs perfectly, but no filter is shown. Any suggestions? -
I just want to know why is python the best option for large websites (Django) [closed]
I want to create a website in which there will be the functionality like: Blog Q & A Dealing with users For developers News And lot of other things. So I just want to know is python (Django) the best option with respect to speed, development. -
Django unittest on_delete CASCADE
I am writing tests for a Django application. Currently, to test for the cascade deletion, I create instances, delete the parent and assert the child is deleted as well. Is there a better method to do this, for example retrieve the parameters passed to the ForeignKeyField of the model using _meta.get_field ? -
How to load json api data in django admin model?
i am trying to load data from json file in django model i tried but it could not load all data in my django admin model and here is my code that i tried so far and here my json file from i want to store data in django model http://www.mocky.io/v2/5e5bce20300000745ef9f2bb. i want to load all data in my django admin model from json file . class CronaVirus(models.Model): timestamp = models.DateTimeField(auto_now_add=True) currentConfirmedCount = models.IntegerField( blank=True, null=True, help_text="Number of current remaining confirmed patients ") confirmCount = models.IntegerField( blank=True, null=True, help_text="Number of confirmed patients ") suspectedCount = models.IntegerField( blank=True, null=True, help_text="Number of suspected patients ") curedCount = models.IntegerField( blank=True, null=True, help_text="Number of cured patients ") deadCount = models.IntegerField( blank=True, null=True, help_text="Number of dead patients ") seriousCount = models.IntegerField( blank=True, null=True, help_text="Number of serious patients ") currentConfirmedIncr = models.IntegerField( blank=True, null=True, help_text="Number of current remaining confirmed patients (increased from yesterday)") confirmIncr = models.IntegerField( blank=True, null=True, help_text="Number of confirmed patients (increased from yesterday)") suspectedIncr = models.IntegerField( blank=True, null=True, help_text="Number of suspected infection (increased from yesterday)") curedIncr = models.IntegerField( blank=True, null=True, help_text="Number of cured patients (increased from yesterday)") seriousIncr = models.IntegerField( blank=True, null=True, help_text="Number of critically ill (increased from yesterday)") deadIncr = models.IntegerField( blank=True, null=True, … -
QuerySet, Object has no attribute 'zipCode' - Django
Below is my code, which receiving an error 'QuerySet' object has no attribute 'zipCode' def feeds_view(request): profile = Profile.objects.filter(id=request.COOKIES['id']) zipCode = profile.zipCode when changing code to below receiving 'UserRegistration' object is not iterable: def feeds_view(request): profile = Profile.objects.get(id=request.COOKIES['id']) zipCode = profile.zipCode content = { 'user': user } return render(request, 'pages/feeds.html', content) HTML Code: <input type="text" name="feededBy" id="feededBy" value="{{user.displayName}}" hidden> <input type="email" name="byEmailID" id="byEmailID" value="{{user.emailID}}" hidden> -
Django Sqlite reducing disk operations
I am working on an embedded application. The device I am using is running a django webserver. Data is constantly being POSTed to resources on the Django server, at a rate of about 4Hz. My main concern is wear on the disk, after a couple years of operation this will become a problem. Does anyone know if it is possible to somehow reduce the amount django writes to the disk? Currently my solution is to look at the "high frequency" posts and modify them so that they are only written to the database after some time. Ideally I would like the entire application to never write to the database unless triggered. The database is SQlite. -
How to use a style attribute within a {% static %} tag?
This is html line which throws an error in VScode: style="{% static 'background-image:url(images/home_slider.jpg)' %}" } expected at-rule or selector expected Do not use empty rulesets how to resolve it? -
Preventing password box auto select
i am learning django and have built a very basic profile form, i am experiencing a strange issue during page load. The profile page has a password change form which is at the bottom of the page and when loading the browser auto navigates to this form and enters the first input field of the form? Has anyone experienced this and if so how do i prevent this from occurring? Form on load: <div class="col-lg-4"> <div class="block"> <!-- Table Styles Title --> <div class="block-title"> <h2><strong>Change Password</strong></h2> </div> <p>Change your password here!</p <form action="/profile/change_password/" method="post" class="form-horizontal"> <input type="hidden" name="csrfmiddlewaretoken" value="Azuwo63bFBZyum9WJSwwp8gwNcdBKw0cvURhLHoZcVDTsq7ecAJArZTYFE0dHleB"> <div class="col-xs-12"> <div id="div_id_old_password" class="form-group"> <label for="id_old_password" class=" requiredField"> Old password<span class="asteriskField">*</span> </label> <div class=""> <input type="password" name="old_password" autocomplete="current-password" autofocus class="textinput textInput form-control" required id="id_old_password"> </div> </div> <div id="div_id_new_password1" class="form-group"> <label for="id_new_password1" class=" requiredField"> New password<span class="asteriskField">*</span> </label> <div class=""> <input type="password" name="new_password1" autocomplete="new-password" class="textinput textInput form-control" required id="id_new_password1"> <small id="hint_id_new_password1" class="form-text text-muted"><ul><li>Your password can’t be too similar to your other personal information.</li><li>Your password must contain at least 8 characters.</li><li>Your password can’t be a commonly used password.</li><li>Your password can’t be entirely numeric.</li></ul></small> </div> </div> <div id="div_id_new_password2" class="form-group"> <label for="id_new_password2" class=" requiredField"> New password confirmation<span class="asteriskField">*</span> </label> <div class=""> <input type="password" name="new_password2" … -
Django: Sliding image from Database
How to make image slider for 3 images condition is it should take images from Databasen in Django3. ? -
Accessing users Download folder in python
I have lunched a simple video downloader app in django with apache2 server.I tried access users local download directory with Path = os.path.expanduser("~") + "/Downloads/".But whenever someone tries to download video its downloading inside servers folder i.e /home/SERVER USER NAME/Download but not users download directory.How could i make it download inside users local Download directory? -
Django Heroku - ImportError after uploading
I successfully uploaded my Django app to Heroku, but when I open my app, I got ImportError which says: Your WhiteNoise configuration is incompatible with WhiteNoise v4.0 This can be fixed by following the upgrade instructions at: http://whitenoise.evans.io/en/stable/changelog.html#v4-0 And later: Error during template rendering. In template /app/templates/base.html In base.html file I have: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="{% static 'css/home.css' %}"> ... And error points at line with css/home.css In my settings.py I have: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')] django_heroku.settings(locals()) STATICFILES_STORAGE = 'whitenoise.django.CompressedManifestStaticFilesStorage' During uploading to Heroku I set config to: DISABLE_COLLECTSTATIC=1 Does anybody know why I have this error after uploading and open app? -
Acessing currently logged in user in class based view
i'm trying to sort some model-data inside a class based view by the currently logged in user. How do i do that? I tried the following, but it didnt work: class ChatOverView(ListView): def get_queryset(self): return [Message.objects.filter(sender=self.request.user), Message.objects.filter(receiver=self.request.user)] model = {"received": get_queryset()[0], "sent": get_queryset()[1]} template_name = "chat/home-chat.html" Im getting the following error message: TypeError: get_queryset() missing 1 required positional argument: 'self' Thanks for Your Help! -
Ajax convert html to pdf
i have been using a package called xhtml2pdf. So far everything has been good and the package is really easy to use if i do not need the data to be defined by the user end. The problem arises when i give the users the ability to choose what will be rendered in the pdf. The user gets to choose from a table , by clicking onto the button associated with that object. I will then store that object ID in an array , which will then be sent via AJAX to my render view so that the appropriate query can be passed into the context. Sounds simple , and im sure there's a solution out there, just none that i know of ! Here is my javascript. To keep the code short , im not going to show the script that i use to prepare the array that im sending into the view. function ajaxsender(clicked_id){ var a = clicked_id $.ajax({ url : "{% url 'bom-ajax'%}", method : "POST", data : { 'csrfmiddlewaretoken' : "{{ csrf_token }}", 'arr[]' : arr , 'pk' : a }, success : function(result) { console.log(result); } })}; This is the view that im using to … -
adding active class in django according to anchor in url
I want to create one page site with navbar links which redirect to some part of the page. How add class "active" to a link if url is based on anchor (#)? <div class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li {% if request.path == "/" %} class="active"{% endif %}> <a href="{% url "index" %}">Main pge</a> </li> <li {% if 'about_us' in request.path %} class="active"{% endif %}> <a href="#about_us">About us</a> </li> <li><a href="#services">Services</a></li> <li><a href="#contacts">Contacts</a></li> </ul> </div> -
Whats the url to access static images on my heroku app
Here is my urls.py urlpatterns = [ path("", hello.views.index, name="index"), path("donate/", hello.views.donate, name="donate"), path("account/", hello.views.account, name="account"), path("random-tweet/", hello.views.randomtweet, name="random-tweet"), path("random-account/", hello.views.randomaccount, name="random-account"), path("db/", hello.views.db, name="db"), path("admin/", admin.site.urls), re_path(r'^celery-progress/', include('celery_progress.urls')) ] I'm trying to access an image file on my heroku app via url, something like http://www.rndtwitr.herokuapp.com/ChaosStar.png Even though i have copied the image to the 'root' directory(i.e. the directory index.html is in) it is still not allowing me to access the image. Maybe I am misunderstanding how heroku directory structure works. Where to copy image files to on my heroku app and what is the url to access it?? -
Do i need to add 'rest_framework.authtoken' in installed app when using JWT
I'm new to django restframeworks, That is why I'm asking this question. Do i need to to add restframework.authtoken app in installed app when using JWT token. I don't think so. But still I'm confused. -
Integrating Microsoft Office365 with Django Rest Framework
I am currently trying to consume the Microsoft Office365 API and Expose it via DRF to my frontend. I want to be able to: Give Role/Permissions to authenticated Users based off of Django already existing roles and Permission Expose the APIs to my Angular frontend for authentication. How do i save authenticated users to the Database and give them the requisite permission so they authenticate having the given permission the next time they login? -
How do I fix psycopg2 error while performing python manage.py migrate?
I'm trying to run python manage.py migrate on Mac OS X 10.8 but this error keeps coming up Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/newowner/Desktop/Development/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/newowner/Desktop/Development/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/Users/newowner/Desktop/Development/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/newowner/Desktop/Development/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/newowner/Desktop/Development/venv/lib/python3.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/newowner/Desktop/Development/venv/lib/python3.7/site-packages/django/contrib/postgres/apps.py", line 1, in <module> from psycopg2.extras import ( File "/Users/newowner/Desktop/Development/venv/lib/python3.7/site-packages/psycopg2/__init__.py", line 50, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Users/newowner/Desktop/Development/venv/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so, 2): Symbol not found: ___strlcpy_chk Referenced from: /Users/newowner/Desktop/Development/venv/lib/python3.7/site-packages/psycopg2/.dylibs/libpq.5.10.dylib Expected in: /usr/lib/libSystem.B.dylib in /Users/newowner/Desktop/Development/venv/lib/python3.7/site-packages/psycopg2/.dylibs/libpq.5.10.dylib I have psycopg2 (version==2.7.7) installed. I already tried the solution here sudo mv /usr/lib/libpq.5.dylib /usr/lib/libpq.5.dylib.old sudo ln -s /Library/PostgreSQL/9.4/lib/libpq.5.dylib /usr/lib After I did that, I restarted my PC and tried python manage.py migrate again, but … -
Access Website in venv from other PC in same network
i created a venv in python with my django project PC with venv: ipv4 = 192.168.1.69 is listening to name http://site.license:8000 and working hosts config: # localhost name resolution is handled within DNS itself. # 127.0.0.1 localhost # ::1 localhost 127.0.0.1 site.license Other PC: hosts config # localhost name resolution is handled within DNS itself. # 127.0.0.1 localhost # ::1 localhost 192.168.1.69 site.license Problem is that i can't acces the webstite from "Other PC".. unfortunately i can ping site.license and it gets resolved to 192.168.1.69, so it has a connection