Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I deployed my django app successfully without any error but when I went to the website, I saw application error, I don't understand
I deployed my django app successfully without any error but when I went to the website, I saw application error, I don't understand. There's no error message on my console, I don't even know what to do or how to debug the problem. I used this heroku logs --tail --app -code to find the code below but i can't make any sense from it. Please I need your to help solve this problem. 2020-11-19T21:35:35.731246+00:00 heroku[web.1]: State changed from crashed to starting 2020-11-19T21:35:46.000000+00:00 app[api]: Build succeeded 2020-11-19T21:35:52.203195+00:00 heroku[web.1]: Starting process with command `gunicorn startingOver.wsgi --log-file` 2020-11-19T21:35:55.795727+00:00 app[web.1]: usage: gunicorn [OPTIONS] [APP_MODULE] 2020-11-19T21:35:55.795976+00:00 app[web.1]: gunicorn: error: argument --error-logfile/--log-file: expected one argument 2020-11-19T21:35:55.876242+00:00 heroku[web.1]: Process exited with status 2 2020-11-19T21:35:55.926887+00:00 heroku[web.1]: State changed from starting to crashed 2020-11-19T21:36:26.125774+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sover.herokuapp.com request_id=7afeb4a7-f1a4-4579-a2a2-84856e17aa89 fwd="129.205.124.165" dyno= connect= service= status=503 bytes= protocol=https 2020-11-19T21:36:27.625586+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sover.herokuapp.com request_id=a0a558ad-fba2-40b6-8cc7-8a6fd2f25eb1 fwd="129.205.124.165" dyno= connect= service= status=503 bytes= protocol=https 2020-11-19T21:37:39.186291+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sover.herokuapp.com request_id=afd20739-1ee9-4593-9a58-260e1bf653d7 fwd="129.205.124.165" dyno= connect= service= status=503 bytes= protocol=https 2020-11-19T21:37:39.848587+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sover.herokuapp.com request_id=eeeaa0d2-49ef-4dbe-9062-81203f672fe5 fwd="129.205.124.165" dyno= connect= service= status=503 bytes= protocol=https 2020-11-19T21:37:46.266626+00:00 heroku[web.1]: State changed from crashed to starting … -
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty :import model
CODE: https://github.com/Strzelba2/STOCK/blob/main/STOCK/WIG/WIG_scrap.py When i try import my model to WIG_scrap.py from .models import CompanyData , Quotes I get the error : django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty but without importing the model, everything works fine. Can someone please explain to me why this is happening -
'tuple' object has no attribute 'ordered' on UpdateView
It gives me this error and for the life of me i cannot understand why: I have a form extended from django-allauth SignupForm... class LearnerSignupForm(SignupForm): first_name = forms.CharField(max_length=40, required=True) last_name = forms.CharField(max_length=40, required=True) The form is called in the allauth signup view... class LearnerSignupView(SignupView): form_class = LearnerSignupForm success_url = reverse_lazy('users:redirect_profile_mixin') The view redirects to a mixin(that extends RedirectView that gets the autheticated user from the request and redirects the connection to an UpdateView passing the parameter user.id.. class LearnerUpdateView(UpdateView): model = User form_class = UserForm formset_Class = LearnerFormSet template_name = "formset_edit_learner.html" success_url = "home" def get_context_data(self, **kwargs): context = super(LearnerUpdateView, self).get_context_data(**kwargs) qs = Learner.objects.get_or_create(user=self.request.user) formset = LearnerFormSet(queryset=qs) context["learner_formset"] = formset return context And then finally to the UpdateView. And it's at this point that i get the error 'tuple' object has no attribute 'ordered' and Exception Location: C:\Users\aless.virtualenvs\hs_03-LQeWV4ia\lib\site-packages\django\forms\models.py, line 639, in get_queryset I know that i'm probably doing something really stupid but i just can't see it. I thank in advance whoever can offer some advice! -
Django Postgresql reset pk/id field
I am using Django with Postgresql. With sqlite, when I delete all the objects, and insert new ones, pk is reset to 1. However, with Postgresql, pk keeps adding up. I came across to this post (1). The accepted answer calls for: python manage.py sqlsequencereset myapp1 myapp2 myapp3| psql My app is products. But I don't know what to write on the right side of the pipe. Here is what I tried: # products is my app name python manage.py sqlsequencereset products The following message appeared: BEGIN; SELECT setval(pg_get_serial_sequence('"products_category"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "products_category"; SELECT setval(pg_get_serial_sequence('"products_product_categories"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "products_product_categories"; SELECT setval(pg_get_serial_sequence('"products_product"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "products_product"; COMMIT; I then tried: python manage.py sqlsequencereset products | psql Here is the error message: -bash: psql: command not found Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> BrokenPipeError: [Errno 32] Broken pipe What should I put after the | ? -
Add rows in many-to-many injected table
Is it possible to insert some data in a injected table (auto created by Django to handle many to many relationship)? I've searched to this question for about 5 hours, and i've found no answer. -
Using historical exchange rates in django money to convert money based on a user inputted date
I am building a personal finance Django app and have been using django-money to automatically convert values based on the current exchange rate using convert_money(). I would like to add a feature where the values are converted based on the exchange rate of a user-specified date, instead of always using the current rate. Is there a way to customize convert_money() to convert based off of an inputted date instead of just the current rate of your last update_rates()? -
How to make Django tries multiple realms in Keycloak using openid connect?
Synopsis We have a web app that allows internal users and external users to login, we would like to split the 2 groups of users in Keycloak with different realms, for instance, internal realm and external realm. Our ideal authentication method is OpenID Connect. Problem Most Django OIDC libraries allows to specify one OIDC client configuration in Django settings. However given how OIDC works one client configuration only works with one realm, because a client is configured inside a realm. I have come across this library django-keycloak which seems to be able to configure client configurations in a database and I need to implement my own middleware to dynamically route the request to a corresponding realm, see this pdf on page 12. Unfortunately this library has not been updated for 2 years and seems not maintained anymore. Question Is there an up-to-date library that has similar functionality in django-keycloak? (I will raise an issue in the repo to enquire the project status) Apart from the multi-client configuration approach, is there a better alternative? -
How do I set the width of a HTML element with a Django variable?
Right now, I have a dictionary, where I have each element and the width of it stored. I'm passing that with Django to an HTML template, where I'm rendering each of the dict objects with a for loop. However, I need to be able to set the width of a 'div' using what is in the Django template. So basically, if I have "100%" in the dict, then I want the corresponding div to also have a width of 100%. The code I tried is below, but it isn't working, and in the console, it says "invalid property value". Python code: dict={"key": "100%", "key2": "90%"} return render(request, "website/updates.html", { "dict": dict }) website/updates.html {% for item, width in dict.items %} <div style="width: {{width}}"> Other irrelevant code here </div> {% endfor %} -
Django authenticate keeps returning None
I'm using Django 3.1.8 with the django debug toolbar on. The "authenticate()" function from django.contrib.auth keeps returning "None" for an unknown reason. I have created a superuser and the login was perfectly working before I installed the debug toolbar. Any advice ? My views.py : def login(request): if request.method == 'GET': return render(request, 'website/login.html') elif request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None : django_login(request, user) return HttpResponseRedirect(reverse("website-home")) else: return HttpResponseRedirect(reverse("website-about")) ` -
Is it possibl to use one broker for two django project?
I have two project with two celery ,but i used one Redis broker ,does it have problem?i think it has problem,because i have problem in run task,and sometimes tasks do not run. -
django text area tag: input cursor does not begin at the start
I created a text area tag , and for some reason the cursor starts at the top middle instead of the top left(which is the standard). I want the input cursor to start at the very beginning of the box. Any help would be helpful :) -
assertRedirect not working. Getting 302 != 201 error
I have two tests: def test_view_exists_at_desired_location(self): note_id = 1 login = self.client.login(username='Name', password='password') response = self.client.get(f'/{ note_id }/edit/') self.assertEqual(response.status_code, 200) def test_view_redirects_if_not_logged_in(self): note_id = 1 response = self.client.get(f'/{ note_id }/edit/') self.assertRedirects(response, f'/accounts/login/?next=/{ note_id }/edit/') in my urls.py I have: urlpatterns = [ ... path('<int:note_id>/edit/', login_required(views.edit), name='edit'), ] The first test, test_view_exists_at_desired_location runs fine, ensuring that a Note with note_id=1 exists. However, the other test fails and tells me: Traceback (most recent call last): File "/home/MyName/Documents/Projects/ProjectName/notes/tests/test_views.py", line 119, in test_view_redirects_if_not_logged_in self.assertEqual(response.status_code, 201) AssertionError: 302 != 201 When I visit /1/edit/ while not logged in on my browser I am redirected to /accounts/login/?next=/1/edit/. I don't think it matters, but here is view.edit: def edit(request, note_id): note = get_object_or_404(Note, pk=note_id) if request.POST: form = NoteForm(request.POST) if form.is_valid(): date = datetime.date.today() title = form.cleaned_data['title'] body = form.cleaned_data['body'] is_private = form.cleaned_data['is_private'] note.title = title note.body = body note.is_private = is_private note.edit_date = date note.save() return HttpResponseRedirect(reverse('notes:mynotes')) # get or any other method. Return create page else: form = NoteForm(instance=note) return render(request, "notes/editor.html", {'form': form, 'note_id': note_id}) -
Django sessions - reliability issues - must keep logging in
I have 2 reliability issue with Django sessions. The goal I am trying to achieve is if I use the account at least once a month, I don't even have to log in. 1. The quantity of sessions I am working on the website, I am the only one using it, and Django keeps creating sessions. I have 30 sessions for just myself today (I cleaned out all the sessions at the start of the day). 2. I have to keep logging in I find every now and then I have to log in again (e.g. come back the next day), or after a reboot. My Current Setup: # Set to 1 months of inactivity SESSION_COOKIE_AGE = 31 * 24 * 3600 # After every request store SESSION_SAVE_EVERY_REQUEST = True SESSION_ENGINE = 'django.contrib.sessions.backends.db' # This is the default I used to use cached DB session engine, but with SESSION_SAVE_EVERY_REQUEST i figure its pointless, as it will be a miss every time. I also thought the default DB session engine maybe more reliable (maybe be more reliable or might just be grasping at straws). For the messages storage I use Session storage. I used to use the default FallbackStorage but figure … -
Consuming JSON API data with Django
From a Django app, I am able to consume data from a separate Restful API, but what about filtering? Below returns all books and its data. But what if I want to grab only books by an author, date, etc.? I want to pass an author's name parameter, e.g. .../authors-name or /?author=name and return only those in the json response. Is this possible? views.py def get_books(request): response = requests.get('http://localhost:8090/book/list/').json() return render(request, 'books.html', {'response':response}) So is there a way to filter like a model object? -
How to POST nested Data that contains a File with Django Rest Framework?
I've been trying to post a nested object with one file and some data via django drf for a few days now. The goal is to create a story together with some images, one of these images being the title image of the story. Basically, I am able to post the story successfully with postman (see picture below). However, when I use my react js frontend for sending, I am not able to create the form data in a way that Django understands it. Django always returns the error story_media field is required. I suppose this is because Django does not understand the incoming data correctly. class Story (models.Model): title = models.CharField(max_length=100,blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) class Story_Media (models.Model): story = models.ForeignKey(Story,on_delete=models.CASCADE, null=True, related_name = 'story_media', related_query_name = 'story_media') file = models.FileField(upload_to='story_media/', null=True) isTitlePicture = models.BooleanField(blank=False, null=True) # Story Story Media Serializer class Story_Media_Serializer (serializers.ModelSerializer): class Meta: model = Story_Media fields = ('id','file','isTitlePicture',) # Story Serializer class StoryCreateUpdateSerializer (serializers.ModelSerializer): story_media = Story_Media_Serializer(many=True) class Meta: model = Story fields = ('title','story_media',) def create(self, validated_data): current_user = self.context["request"].user story_media = validated_data.pop('story_media') story_instance = Story.objects.create(author=current_user, **validated_data) for story_media_data in story_media: Story_Media.objects.create(**story_media_data, story=story_instance) # Story Create View Set class StoryCreateUpdateViewSet(viewsets.ModelViewSet): serializer_class = StoryCreateUpdateSerializer … -
Django elasticsearch dsl completion field issue
I am trying to implement search suggestions using django-elasticsearch-dsl-drf for streets. This is documents.py: class StreetDocument(Document): id = fields.IntegerField() name_ru = StringField( fields={ 'raw': KeywordField(), 'suggest': fields.CompletionField(), } ) ... # same for name_uz and name_oz tags_ru = fields.CompletionField() ... # same for tags_uz and tags_oz class Django: model = Street fields = ( 'code', 'street_type' ) in views.py I have this: from django_elasticsearch_dsl_drf.constants import SUGGESTER_COMPLETION from django_elasticsearch_dsl_drf.filter_backends import SuggesterFilterBackend from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet class SuggestionListAPI(DocumentViewSet): document = StreetDocument serializer_class = StreetDocumentSerializer filter_backends = [ CompoundSearchFilterBackend, SuggesterFilterBackend, ] search_fields = ( 'code', 'name_ru', 'name_uz', 'name_oz', 'tags_ru', 'tags_uz', 'tags_oz' ) suggester_fields = { 'name_ru_suggest': { 'field': 'name_ru.suggest', 'suggesters': [ SUGGESTER_COMPLETION, ], }, ... # same for name_uz and name_oz 'tags_ru': { 'field': 'tags_ru', 'suggesters': [ SUGGESTER_COMPLETION, ], }, ... # same for tags_uz and tags_oz } Request to /suggestions?name_ru_suggest__completion=tolstoy does nothing, just receiving all streets unfiltered. Request to /suggestions?search=tolstoy works great, but I need autocompletion. Where did I go wrong? And that will be great if it's possible to use two fields for suggestion at once. Thanks for your time and help. -
I have question about views in django.how i can show several forms in django one by one?
Hi there I do have a problem.in registraion form i wnat to send a code to email of user and make him insert it in next form to sign up. i know i can make a field in user model for the code but i dont wanna do that i want to show the next form in same view and validate the code.is it safe for speed of a website and security? is it a right way to do it if not is another way to do it? thanks for your time i have tried this view but its lots of mess and does not work """ def code_checker(request,email): code=randrange(1000,10000) send_mail("",f"{code}","AH Book Store",[email],fail_silently=False) return(code) def email_register_view(request): if(request.method=="POST"): form=EmailRegisterForm(data=request.POST) if(form.is_valid()): email=form.cleaned_data["email"] code=code_checker(request,email) if(request.method=="POST"): code_form=EmailCodeRegisterForm(data=request.POST) if(code_form.is_valid()): cd=code_form.cleaned_data if(code==cd["code"]): messgaes.success(request,"User Created") else: code_form=EmailCodeRegi.sterForm() return(render(request,"accounts/EmailRegisterForm.html",{"code_form":code_form})) else: form=EmailRegisterForm() return(render(request,"accounts/EmailRegisterForm.html",{"form":form,"code_form":None})) """ -
Two different indexes on Django: One is properly connecting to the CSS but the other one isn't, despite same paths
I'm relatively a beginner in Django and I'm trying to set a website I made to simulate a store. I have two different HTML files: one being a practice store I made (mainly to try out how the cart function worked) and a polished version of the same store. Both are in the same directory. The main issue is one of them isn't changing when I make modifications to the CSS files while the other one is perfectly. Here's a snippet of the code for reference: This is the non-working HTML: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="shortcut icon" type="image/x-icon" href=" {% static 'App/assets/images/favicon.ico' %} "> <meta name="description" content=""> <meta name="author" content=""> <title>Title</title> <script src=" {% static 'App/assets/vendor/home-banner/jquery.min.js' %} "></script> <!-- main css --> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> #### File in question <link rel="stylesheet" href=" {% static 'App/assets/css/home-1.css' %} "> <link rel="stylesheet" href=" {% static 'App/assets/vendor/revolution/vendor/revslider/css/settings.css' %} "> <link rel="stylesheet" href=" {% static 'App/assets/vendor/revolution/responsiveslides.css' %} "> <link rel="stylesheet" href=" {% static 'App/assets/vendor/side-menu/side-menu.css' %} "> <link rel="stylesheet" href=" {% static 'App/assets/vendor/side-menu/jquery.mCustomScrollbar.min.css' %} "> This is the working HTML: {% load static %} <html> <head> … -
Detail views fail to find post url after adding one to many fk relationship from "PostFile" to "Post"
After changing admin.py (previous code commented): # admin.site.register(Post) class PostFileAdmin(admin.StackedInline): model = PostFile @admin.register(Post) class PostAdmin(admin.ModelAdmin): inlines = [PostFileAdmin] @admin.register(PostFile) class PostFileAdmin(admin.ModelAdmin): pass And adding PostFile to models.py: class Post(models.Model): slug = models.SlugField(max_length=200, unique_for_date="date_posted") content = RichTextField() date_posted = models.DateTimeField(default=timezone.now) ... def get_absolute_url(self): return reverse("news:news-detail", args=[self.date_posted.year, self.date_posted.month, self.date_posted.day, self.slug]) class PostFile(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) post_file = models.FileField(upload_to="files/news", null=True, blank=True) Also, views.py: class PostListView(ListView): model = Post template_name = "news/news_home.html" context_object_name = "posts" ordering = ["-pk"] paginate_by = 2 def news_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status="published", date_posted__year=year, date_posted__month=month, date_posted__day=day) return render(request, "news/news_detail.html", {"post": post,}) When I create new post in Django admin, and then try to go to its absolute_url to see detailed view, it raises 404. I checked, using shell, absolute_url is good and all objects are created properly, but for some reason post's URL is broken. Any idea how to solve this? -
How do I use button on card to change a session value?
I am making a menu that goes through a few different steps. Select the grade, then select the textbook, then select the lesson. I want to display the textbooks as cards with buttons that will bring the user to a view of all the lessons associated with that textbook. I've used session to go from the grade to the textbook, but I'm not sure how to go from the textbook to the lessons. I think the way of getting there is to have the button change the session value to that textbook, and bring me to the view that will filter the lessons by that textbook, but I'm not sure how to do that. Any suggestions would be welcome! -
how to import python file from another directory
I am working on a django rest framework and can't import .py files from another directory. I have __init__.py files included in the directory -
invalidImageFormatError Exception The source file does not appear to be an image
So I am using fallback default image to avoid 500 error and it is not successful. I keep getting the same error "InvalidImageFormatError: The source file does not appear to be an image". In my case I try to thumbnail an image that does not exist. But it is assumed that if the image does not exist it should use the one that is in default as fallback. Any ideas? Someone who has happened in the same way and found a solution? In my case this is my code {% oscar_thumbnail child_image.original|default:'image/default.png' "450x450" format="WEBP" padding=True as thumb_child %} I am migrating from sorl-thumbnails which comes by default with django_oscar for easy_thumbnails. The tag OSCAR_THUMBNAIL is used by django_oscar and oscar replaces it with the thumbnailer that is in settings in this case easy_thumbnails. I have debugged the code, and it is entering the easy_thumb classes well ... and the parameters are arriving correctly. The thing is, it doesn't make me fallback when the image it's trying to process doesn't exist. I have a database with products that have associated images, many of these do not exist in my local environment, because in production they are in s3, and I do … -
How to add new pages existing django app through admin page?
I have an existing Django app. What is the best way to add new pages to it through the admin page, without actually coding every time. I want to add static pages, with URLs through the admin page. Add new page with new URLs Add through admin page, not through coding every time. One time code to handle this. Is there a way out? -
Data accessing : Django forms vs request.POST method
Can someone please explain me why is highly recommended to use Django forms to get an html object instead of direct accessing from request.POST or request.GET? -
Django:Widgets not being picked for filter with relation fields
I have the below set up for models program, courses and providers. class Program(models.Model): subtitle = models.TextField( null=True, blank=True) courses = models.ManyToManyField(Course, related_name='course_bundle') class Course(models.Model): provider = provider = models.ForeignKey( Provider, **and more **) Below is my filter for the same where I want the provider to be a multiselect as every program has multiple courses. However, looks like it does not pick the widget defined in the filter but reads directly from Meta and shows. It neither changes the label or style or anything. class ProgramFilter(django_filters.FilterSet): subtitle = django_filters.CharFilter(lookup_expr='icontains', label="Keywords", widget = forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Search for specialities', 'label': 'Keywords', })) courses__provider = forms.ModelMultipleChoiceField(label='Providers',queryset=Provider.objects.all(), to_field_name='courses__provider', required=False, widget=forms.CheckboxSelectMultiple(attrs={ 'class':'form-control', 'label':'Providers' }),) status = django_filters.ChoiceFilter(choices=Program.STATUS,empty_label="All") class Meta: model = Program fields = ['subtitle','cost' ,'duration','popularity','status','courses__provider'] How should we define the widget for filters with relation based properties like courses__provider.It ignores the code outside of meta completely for courses__provider but works for subtitle.