Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Clean method not picking up the submitted file
General file processing in my form works fine (on save/edit). But I cannot get file information when I access the file in the clean/validation method. Can you please help :) forms.py class BatchForm(ModelForm): csv_file = FileField(label='CSV File') class Meta: model = Batch fields = ('project', 'name', 'csv_file', 'filename') def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(BatchForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() csv_file = cleaned_data.get("csv_file", False) print("file: ", csv_file) # csv_file prints None I tried printing csv_file but I got None as output My template: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_table }} </table> </form> My view: def create_batch(request): form = BatchForm(request.POST or None, request=request.FILES) if form.is_valid(): form.save_batch(request=request, create_batch_flag=True) return redirect('list_batch_url') return render(request, template_name, {'form': form}) -
How to run background process code using django?
First time I worked django-background-task package. I tried to see the documentation and create a sample background task file. it's working fine. but schedule time and repeat time is not working I set interval time=10 seconds. but it runs every second how to fix it. I tried many ways still not getting a solution or any other alternate package use to perform background process My Code from django.shortcuts import render from django.http import HttpResponse from background_task import background # Create your views here. @background(schedule=5) def hello(): print("Hello World!") def index(request): hello(repeat=10) return HttpResponse('<h1>Hello World</h1>') In documentation given, we can override the schedule timing. How it works schedule=5 seconds and repeate=10 seconds anyone can explain how it works. how to fix this issue. -
Django development server command
I am little confuse about django developement server.Here question is if my project running based on gunicorn and ngnix in production environment. Should my local development need nginx for serving static files? if yes then what command should i use instead of Python manage.py runserver. Help me get out of it. -
How to run management command from django view.py
I want to run my custom command from django view which create new user. Here is my command python manage.py tenant_command createsuperuser --schema=schema_name Here schema name my be change Above command is same as python manage.py createsuperuser Here i didn't know how to pass username, email and password and confirm password any suggestion would be appreciated -
Django NoReverseMatch error in RedirectView
I have been attempting to make a follow feature for my site, however I am consistently getting stuck on errors. Here is the UserProfileInfo model slug = models.SlugField(unique=True,allow_unicode=True) # ... other fields def get_absolute_url(self): kwargs = { 'slug':self.user.username, } return reverse('mainapp:view_profile_with_pk',kwargs=kwargs) # return reverse('mainapp:post_list') def save(self, *args, **kwargs): self.slug = slugify(self.user.username) super().save(*args, **kwargs) Here is my view class AddFriendRedirect(RedirectView): def get_redirect_url(self,*args,**kwargs): slug = self.kwargs.get("slug") obj = get_object_or_404(UserProfileInfo,slug=slug) # user_profile = User.objects.get(username=username) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated: if user in obj.friends.all(): obj.friends.remove(user) else: obj.friends.add(user) return url_ Here is my urls.py path('profile/<str:slug>/add/',views.AddFriendRedirect.as_view(),name='add_friend'), And finally here is my HTML <a id="new-post" href="{% url 'mainapp:add_friend' slug=username %}"> <button id=""> Connect </button> And here is my error NoReverseMatch at /mainapp/profile/don0024/add/ Reverse for 'view_profile_with_pk' with keyword arguments '{'slug': 'don0024'}' not found. 1 pattern(s) tried: ['mainapp/profile/(?P[^/]+)/$'] And the full traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/mainapp/profile/don0024/add/ Traceback: File "C:\Users\User.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\User.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "C:\Users\User.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\views\generic\base.py" in get 188. url = self.get_redirect_url(*args, **kwargs) File "C:\Users\User\interests-site\interests\mainapp\views.py" … -
How to test EmailMessage .send() with backend modified by EmailBackend
How to test emails send via EmailMessage .send() when email backend is set by EmailBackend object? As the backend is modified inside this function mail.outbox does not store any outgoing emails. What would be the most Django way of approaching this? function in question: def send_email_to_users(email_message_obj): recipients = [user.email for user in email_message_obj.addressees.all()] ap = Admin_Profile.objects.get(id=1) backend = EmailBackend( host=ap.email_host, port=ap.email_port, username=ap.email_host_user, password=ap.email_host_password, use_tls=ap.email_use_tls, fail_silently=False) email = EmailMessage( subject=email_message_obj.title, body=email_message_obj.body, from_email=email_message_obj.email_from, to=recipients, connection=backend) email.send() test: class Testsend_email_to_users(TestCase): def setUp(self): User.objects.create_superuser( username='admin', email='jlennon@beatles.com', password='glassonion') @override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend') def test_one_email(self): '''should send one email''' Admin_Profile.objects.create( user=User.objects.all().first(), email_host=settings.TEST_EMAIL_HOST, email_port=settings.TEST_EMAIL_PORT, email_host_user=settings.TEST_EMAIL_HOST_USER, email_host_password=settings.TEST_EMAIL_HOST_PASSWORD, email_use_tls=True, ) u1 = mixer.blend(User, email=settings.ADMIN_EMAIL) email_message = Email_Message.objects.create( title='test title', body='test body', email_from=settings.TEST_EMAIL_HOST_USER, ) email_message.addressees.add(u1) send_email_to_users(email_message) # should send one email self.assertEqual(len(mail.outbox), 1) result of the test: > self.assertEqual(len(mail.outbox), 1) E AssertionError: 0 != 1 models.py: class Admin_Profile(models.Model): ... email_host = models.CharField(max_length=100, blank=True) email_port = models.IntegerField(null=True, blank=True) email_host_user = models.EmailField( max_length=70, null=True, blank=True) email_host_password = models.CharField(max_length=100, blank=True) email_use_tls = models.BooleanField(null=True, blank=True) class Email_Message(models.Model): title = models.CharField(max_length=78) body = models.TextField() email_from = models.EmailField() addressees = models.ManyToManyField(settings.AUTH_USER_MODEL) timestamp = models.DateTimeField(auto_now_add=True) ... Notes: send_email_to_users is functional and sends 'real' emails; test_settings.py contains: all other tests that use django.core.mail.send_mail pass the tests and are captured in mail.outbox; … -
What is good architecture for Django with a lot of table?
What is good architecture for Django with more than 60 table (Restful) is good to have an app as api and for each table has sub app in main app or not? -
django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known
My GitLabCI: stages: - test # jobs test_django: stage: test image: python:3.6 # this pulls the standard python 3.6 docker image services: - postgres:9.5 # this pulls a docker image with pgsql on it variables: # env vars made available to the script below CI_DEBUG_TRACE: "false" # set to false to reduce the debug output from the CI jobs POSTGRES_DB: "project_ci_test" POSTGRES_USER: "postgres" POSTGRES_PASSWORD: "" DATABASE_NAME: "$POSTGRES_DB" DATABASE_HOST: "postgres" # magically finds the service above DATABASE_USER: "postgres" DATABASE_PASSWORD: "" DJANGO_SECRET_KEY: "somerandombogusstringtokeepdjangohappyandstartingproperly" script: - apt-get update -qy - apt-get install -y python3-pip wkhtmltopdf xvfb # extra packages used for pdf rendering in the tests - pip install -r requirements.txt - pep8 . --filename=*.py --ignore=E128,E265,E501 --repeat - python manage.py migrate - python manage.py test But now i'm getting error while running migrations. GitlabCi Error: self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known ERROR: Job failed: exit code 1 Hello, guys could you please help me. what is wrong with my settings, it was working a few month ago but not it's not working. … -
Django Twilio API Custom Body Form
Using the code below, what is the best way to create a custom "body" for sending an SMS message using the Twilio API? to = '+11111111111' client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) response = client.messages.create( body='Hello, testing Twilio in Django', to=to, from_=settings.TWILIO_PHONE_NUMBER) -
Django : Invalid Token in cryptography.fernet
I am running a website using Django . Below is the error: raise InvalidSignature("Signature did not match digest.") cryptography.exceptions.InvalidSignature: Signature did not match digest During handling of the above exception, another exception occurred: raise InvalidToken cryptography.fernet.InvalidToken Below is the package: def _verify_signature(self, data): h = HMAC(self._signing_key, hashes.SHA256(), backend=self._backend) h.update(data[:-32]) try: h.verify(data[-32:]) except InvalidSignature: raise InvalidToken hmac.py: def verify(self, signature): digest = self.finalize() if not constant_time.bytes_eq(digest, signature): raise InvalidSignature("Signature did not match digest.") What is the one i am missing? -
Global Exception Handling in Django-rest-framework
Is there a way to handle all the exceptions globally without using try-except block in django rest framework. I want to convert html error page that django is throwing to a customised json object response. -
AbstractUser Signup
Hello I am trying to extend Django User model using Abstract User but I get OperationalError when signing up My Profile model: class Profile(AbstractUser): email = models.EmailField(max_length=150) bio = models.TextField() university = models.CharField(max_length=30) def __str__(self): return self.username CREATED = 0 ACTIVE = 1 BANNED = 2 KICKED = 3 UPGRADE = 4 STS = ( (CREATED, 'Just Created'), (ACTIVE, 'Activated'), (BANNED, 'Disabled'), (KICKED, 'Disabled'), (UPGRADE, 'Active'), ) status = models.IntegerField(choices=STS, default=CREATED, blank=True, null=True) My Signup form: class SignUpForm(UserCreationForm): username = forms.CharField( label='', max_length=30, min_length=5, required=True, widget=forms.TextInput( attrs={ "placeholder": "Username", "class": "form-control" } ) ) first_name = forms.CharField( label='', max_length=50, min_length=2, required=True, widget=forms.TextInput( attrs={ "placeholder": "First name", "class": "form-control" } ) ) last_name = forms.CharField( label='', max_length=50, min_length=2, required=True, widget=forms.TextInput( attrs={ "placeholder": "Last name", "class": "form-control" } ) ) university = forms.CharField( label='', max_length=50, min_length=2, required=False, widget=forms.TextInput( attrs={ "placeholder": "University", "class": "form-control" } ) ) email = forms.EmailField( label='', max_length=255, required=True, widget=forms.EmailInput( attrs={ "placeholder": "Email", "class": "form-control" } ) ) password1 = forms.CharField( label='', max_length=30, min_length=8, required=True, widget=forms.PasswordInput( attrs={ "placeholder": "Password", "class": "form-control" } ) ) password2 = forms.CharField( label='', max_length=30, min_length=8, required=True, widget=forms.PasswordInput( attrs={ "placeholder": "Confirm Password", "class": "form-control" } ) ) class Meta: model = Profile fields = ('username', … -
How do I make a 404 error route to a Wagtail page?
When a 404 error is thrown in a project that uses Wagtail, I'd like to have the site redirect to a page in the CMS. How do I do this? I know Wagtail has a redirects feature, but that doesn't seem to do what I want; if I were to use that I'd need to have some kind of wildcard selector that would be superseded by more specific redirects. I searched around the issues but this was as close as I found. But that seems to be more related to admin 404s if I'm reading it right. -
how to deal with the order of input elements with the same name?
guys. I am new in using Django. In short, I want to collect data provided by users. For instance, I want to collect the scores of many subjects. Basically, I will design a div element containing two input element with these two name: subject_name and score. This design works fine if user upload a score at each post-request. Whatif a user want to upload many scores at one post-request? How can I support this operation? Assumes there is a add-button to add a new div element which contains the two same input elements. After user click the submit-button, the variable request.POST in Django will contain two lists which represents the subject and the score respectively. However, the order of the values inside these two list is not guaranteed, which is bad in accuracy. Any ideas? Thanks for your sharing. -
How to create a Doughnut chart in django admin interface using foreign key field data?
I am working on creating a Django admin interface, wherein i am plotting in three doughnut charts to visualize the data but out of three charts only one charts is working correctly. What i think the problem is that the other two charts are using the data of foreign key field and i am not sure how to make the call for the data. Following is my model.py, admin.py and template for creating the interface. Kindly help me to modify the code for the charts, the help will be highly appreciated. models.py admin.py Part Of Template -
Django Default HomePage Not Found
I have a Django project, and working correctly, but not display default home page. I know that, you have to add a url pattern to display , but this is not exactly what am I asking. Normally, if you create a Django project, Django will serve you a default web page something like that And you can change it by adding a url pattern for '/' in 'project.urls' like that : urlpatterns = [ ... url(r'^$', wellcomeView, name='wellcomeView'), ... ] But normally , Django must show this default home page while you don't change anything in url patterns or settings. So this is my question : I didn't change anything in settings or urls , but after a migration , it stopped to show default page. What thing can caused this ? This is my scenario : 1- I created a Django 2.2.7 project (Everything is ok) 2- Crated apps, models. But now views 3- Migrations, created db, test models. Still there is not any views, but shows default home page. 4- Changing models, again and again, and migrating every time. (But still no views , and not changing settings or urls, only looking up in default admin page. Also … -
How do I get rid of extra zeroes in django DecimalField?
I am using a DecimalField in my model as I need quite a few decimal places for some of the values. But for some of the values I don't need as many zeroes. The problem is in the same field I will have some values that are 0.76 and other values that are 0.0001548337258. Unfortunately FloatField is not accurate enough for my needs. But when I use: class Part(models.Model): dec_number = models.DecimalField(max_digits=19, decimal_places=15) I unfortunately get the same amount of empty 0's on my 0.76. I would like the output when I call that field to be 0.76 in that location, and 0.00000037. Currently my output is: 0.760000000000000 0.000154833725800 I am trying to get my output to be: 0.76 0.0001548337258 Is there a way to remedy this? -
Django rest api delete, returns 404 not found
I have this api, that's not deleting the items by id. Here is the model: class Contact(models.Model): pass user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.CASCADE, verbose_name=_('User'), related_name="user") #uid = models.CharField(max_length=150, null=False, default=get_id, unique=True, editable=False) contact = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.CASCADE, verbose_name=_('Contact'), related_name="contact") created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) is_contact = models.BooleanField(default=False) objects = ContactManager() def __str__(self): return self.user.username and the serializers.py class ContactSerializer(ModelSerializer): class Meta: model = Contact fields = [ 'user', 'contact', 'is_contact', ] and Views.py class ContactDeleteAPIView(DestroyAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializer lookup_field = 'id' permission_classes = [IsOwnerOrReadOnly] And urls.py: path('<int:id>/delete', ContactDeleteAPIView.as_view(), name='delete-contact'), This just returns 404 not found when I try to do a delete action. What am I missing? -
With django-filter, is there a quick way to support all possible lookups for fields?
django-filter allows you to easily declare filterable fields of a model. For example, class UserFilter(django_filters.FilterSet): class Meta: model = User fields = ['username'] provides an exact lookup for the username field which is equivalent to this... class UserFilter(django_filters.FilterSet): class Meta: model = User fields = { 'username': ['exact'] } I'm looking for a way support all possible lookup filters given the field so that I don't have to do this: class UserFilter(django_filters.FilterSet): class Meta: model = User fields = { "username": ["exact", "iexact", "contains", "icontains", "startswith", ..., etc.] } -
list index out of range when upgrating python/django
fa = Fa.objects.filter(fa_name = tag)[0] It was working in python 2.7 and django 1.8 but now that I migrated to django 2.2 and python 3.6 its not working -
How to show query values in url lile webpage/?q='A'&q='B'.....&q='N' using a single input in html form
I am trying to create a url like this: web.com/?q='A'&q='B'.....&q='N' where N is the number of user created list of values using an html form. <input type="text" name="q" multiple> <input type="submit" value="Show" > It shows ?q=A%2C+B in the url if the input is 'A', 'B'. I am using Django in the backend and using `query = request.GET.getlist('q') to get the list of values. I guess I can do q[] to get an array if I know the number of list of values of user created list, but that is unknown and variable. Is there an elegant way of doing this just using html? I have searched for various SO questions like these: How to Submit Multiple Values in a single HTML Form? Pass Javascript Array -> PHP But these are not exactly what I want. I guess I can create a form which would accept a csv file and then then get processed in Django to get the url I want, but I am just curious if I can do it just by using html (and if necessary JavaScript). Thanks in advance. -
Heroku Scheduler Fails: Apps Aren't Loaded Yet
Im trying to set up Heroku Scheduler on my Django ASGI application instance, but am running into a pesky exception. Im running Django Channels via Daphne on this server. 2020-02-27T01:32:54.607743+00:00 app[scheduler.4282]: Traceback (most recent call last): 2020-02-27T01:32:54.607779+00:00 app[scheduler.4282]: File "api/push_notifications/run.py", line 1, in <module> 2020-02-27T01:32:54.607883+00:00 app[scheduler.4282]: from api.push_notifications.stream import * 2020-02-27T01:32:54.607884+00:00 app[scheduler.4282]: File "/app/api/push_notifications/stream.py", line 1, in <module> 2020-02-27T01:32:54.608022+00:00 app[scheduler.4282]: from .helpers.persist import * 2020-02-27T01:32:54.608025+00:00 app[scheduler.4282]: File "/app/api/push_notifications/helpers/persist.py", line 1, in <module> 2020-02-27T01:32:54.608174+00:00 app[scheduler.4282]: from api.serializers import PushNotificationSerializer 2020-02-27T01:32:54.608174+00:00 app[scheduler.4282]: File "/app/api/serializers.py", line 2, in <module> 2020-02-27T01:32:54.608282+00:00 app[scheduler.4282]: from api.models import * 2020-02-27T01:32:54.608282+00:00 app[scheduler.4282]: File "/app/api/models.py", line 4, in <module> 2020-02-27T01:32:54.608381+00:00 app[scheduler.4282]: from django.contrib.auth.models import User 2020-02-27T01:32:54.608383+00:00 app[scheduler.4282]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> 2020-02-27T01:32:54.608485+00:00 app[scheduler.4282]: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager 2020-02-27T01:32:54.608486+00:00 app[scheduler.4282]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module> 2020-02-27T01:32:54.608604+00:00 app[scheduler.4282]: class AbstractBaseUser(models.Model): 2020-02-27T01:32:54.608604+00:00 app[scheduler.4282]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 100, in __new__ 2020-02-27T01:32:54.608726+00:00 app[scheduler.4282]: app_config = apps.get_containing_app_config(module) 2020-02-27T01:32:54.608727+00:00 app[scheduler.4282]: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 244, in get_containing_app_config 2020-02-27T01:32:54.608893+00:00 app[scheduler.4282]: self.check_apps_ready() 2020-02-27T01:32:54.608893+00:00 app[scheduler.4282]: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 127, in check_apps_ready 2020-02-27T01:32:54.609020+00:00 app[scheduler.4282]: raise AppRegistryNotReady("Apps aren't loaded yet.") 2020-02-27T01:32:54.609030+00:00 app[scheduler.4282]: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. 2020-02-27T01:32:54.750918+00:00 heroku[scheduler.4282]: State changed from up to complete 2020-02-27T01:32:54.732106+00:00 heroku[scheduler.4282]: Process exited with status 1 Ive tried adding django.setup() at the … -
In Django REST Framework, how to serialize the results of calling a given method on each member of a queryset?
I want to make a ListAPIView which looks up a queryset, calls a method on each member of that queryset, and then serializes the results with many=True. I can see several ways of doing this. Is there a convention? Iterate over the source queryset in the ListAPIView, calling the method on each object, and putting the results in a list. Then serialize that list. Wrap the source queryset to produce another queryset which calls the method when appropriate. This sounds like the sort of thing which would be built in, but I can't find it in the Django docs. Get the serializer to call the method as appropriate. This also seems like it would be built in, but I can't find it in the Django REST Framework docs. -
I want to call get_queryset on an object twice with in a view template. How should I do it?
I am trying to build a web app that helps studying languages. On the index page(home page), I want to show 2 sections: "Latest vocabulary" and "Random vocabulary". Hence, I want to filter the Spanish vocabulary list using two filters separately. First one is to arrange them according to date of being added to the database, and the other is to randomize and draw 20 random words. I found the get_queryset() is a way to do the 1st filtering, and I found another way to randomize from stackoverflow as well. But the problem is, get_queryset() returns the result to context_object_name, and I suppose there can only exist one context_object_name. So I don't know how to fetch the random_spanish_list and display it. Here is the code for the index page. {% if latest_spanish_list %} <div class="flexcontainer"> <div class="sectiontitle">Latest vocabulary </div> {% for spanish in latest_spanish_list %} <div class="card"> <div class="cardinner" onclick="this.classList.toggle('flipped');"> <div class="cardfront"> <a href="{% url 'geniusdennis:detail' spanish.id %}">{{ spanish.word_esp }}</a> <form action="/deleteword/{{spanish.id}}/" method="post">{% csrf_token %} <input type="submit" value="Delete"/> </form> </div> {% for english in spanish.english_set.all %} <div class="cardback"> <p>{{ english.word_eng}}</p> </div> {% endfor %} </div> </div> {% endfor %} </div> {% else %} <p>No Spanish words are available.</p> {% endif … -
sending notification to selected user in Django
I am working on a part of a project that when I create a group for a project and once I submit the form (where I can pick certain users to be in the group in the form), the users who I selected in the form will receive any type of notification. The idea I am having now is when the selected users log in, their web pages will receive the notification that they are selected to the group. I have looked at Django's message frameworks however, it seems like they don't have the information that I am looking for. Can anyone please give me suggestion on where to start and what should I look at? I am an extreme noob in Django so please help !