Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
DjangoCMS - Admin Account Details
I took a break from working on a website I am currently building however I cannot for the life of me remember the admin account details.. I thought I could just create a new superuser however it appears the users for DjangoCMS and Django Admin may be different.. Does anyone know of a way to either reset the password or create a new user explicitly for DjangoCMS? I have attempted python3 manage.py createsuperuser however the user account created doesn't seem to work. Any help would be appreciated! There is very little on google about DjangoCMS.. -
How to update the value of nested dictionary and avoid bidding
When i update the value given specific keys in a nested dictionary, i seem to be binding the dictionnary to the value. This is a problem when i loop through a list of values as only the last value is saved. Instead i would like to only update the value given the relevant keys. In the code below, the last element of the list list will replace the value for all the dates for a given column_header: new_calendar = init_calendar(year,month,column_headers) for element in list: new_calendar[element.date][element.column_headers] = element init_calendar creates a nested dictionary where all dates for a given month have the dictionary {column_header1:None, column_header2: None, ...}. The for loop is meant to overrides the None value with an instance of object Element for a given date and column_header. list is a queryset of elements of class models.Element How could i update the new_calendar so that for a given instance element of the Element object, new_calendar[element.date][element.column_header] is updated with element ? Thank you -
Django filter many to many list of objects that contains all the items of a list
Models.py class Track(models.Model): title = models.CharField(max_length=300,null=True, blank=True) artists = models.ManyToManyField(Artist, related_name='track_related') artist_list = [mila, fuad, habib] I have to filter all the track that's artists contain all the artist from artist_list Mila, Fuad, and Habib I tried Track.objects.filter(artists__in=artist_list).annotate(num_artist=Count('artists')).filter(num_artist=len(artist_list)) But its not woking and also i think my logic isnt fully correct.