Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Storing string instead of dictionary object in (djongo)mongodb table while using jsonfield to store dynamic dict data
I am getting payload which included key like { "id": UUID, "phone_number": "+141 98324 2434", "organization": "xyz", "property":{ "name": "abc", "email": "xyz", "address": { "street": "6th St", "city": "San Francisco", "state": "CA", "postalCode": "94103", "country": "USA" }, "age":14, } } my model looks like this: from jsonfield import JSONField organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) phone_number = models.CharField(max_length=16, unique=True, db_index=True) tags = models.TextField(blank=True, null=True) property = JSONField(default={}, blank=True, null=True) Now while storing property(its dynamic) in my djongo DB, i want it to save as object(dict) data type so that later i can query using customer.object.filter(property__age=14). Right now its getting stored as string hence i m not able to query my property field. here is some what is looks like in mongodb. id: UUID phone_numer: "xyz" organization: "xyz" property:"{"name":"abc","age":14}" How should i store property as object in mongodb? -
How do i group by month with other annotated fields?
I have a model like this: class Diary(models.Model): name = models.CharField() gender = models.CharField() date = models.DateField() happy = models.BooleanField() and in the views, i want to group the Diary by month. and i also want to annotate the diary by feelings, so if happy=False, i want to return it as Sad, if happy=True then i want to return Happy. but if there both happy=False and happy=True in the queryset after i group by date, i want to return the feelings as Sad. i tried to annotate like this: queryset = Diary.objects.all() queryset = queryset.values('date') queryset = queryset.annotate(feelings=Case(When(happy=True, then=Value(""))), default=Value("Sad")) but in the same month, if i have both Sad and Happy feelings, i get two rows like this: { "date": "2020-08-20", "feelings": "Happy" }, { "date": "2020-08-20", "feelings": "Sad" } is there a way to group it by month and annotate the feelings as Sad if there is at least one queryset that have happy=False? sorry i'm rather new to Django, thanks in advance! -
How to remove unactivated reservation in Django?
I am creating a web app where people can book a football court, the user select the day and the hour, and insert his email and phone number to book the football court. I don't ask for a sign up, but the user receive an email with an "activation" link to confirm the reservation. I would write a method or something that every X minutes check for the unactive reservations and delete them if the time has expired. How can I do it in Django? -
How to build a multi step form in Django within a unique view passing data between steps?
I need a multi step form in Django for whom next step make use of some previous step fields data. Also hitting "previous" button need to bring back form data enterred in previous step by user. Current implementation is made of a unique view with a counter (named "step") grabbed from URL, 3 forms and HTML templates (one per visual step). I came with the following code so far but steps after first one don't render properly. 1 ) First step (edition) Show all editable fields to user 2 ) Second step (verification) Let user verify some fields (2 of 3), showing them as read only. Previous button will let user edit form data in previous step 3 ) Third step (verification & edition) Let user verify other field (1 of 3) and uncheck some values if needed. Previous button will let user verify other fields 3 ) Fourth step (no user interaction) No visual here, data will be processed in the "backend" urls.py path('multipage_form/<int:step>/', views.multipage_form, name='multipage_form') forms.py # First form step (initial) class Form_0(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subject'] = forms.CharField(label='Subject',required=True,widget=forms.TextInput(attrs={ 'class': 'form-control' })) self.fields['message'] = forms.CharField(label='Message',required=False,widget=forms.Textarea(attrs={ 'class': 'form-control' })) self.fields['recipients'] = forms.ModelMultipleChoiceField(queryset=Contacts.objects.none(),required=True,widget=forms.SelectMultiple(attrs={ 'class': 'form-control' })) def … -
Unable to connect with Postgresql in apache2
This is the error I'm getting when I try to run my django application on localhost: File "/home/hussam7102/JobPortal/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Then I checked the log file and it shows "Permission Denied" errors: 2020-08-26 06:54:16.573 UTC [28369] LOG: received smart shutdown request 2020-08-26 06:54:16.579 UTC [28369] LOG: worker process: logical replication launcher (PID 28385) exited with exit code 1 2020-08-26 06:54:16.579 UTC [28380] LOG: shutting down 2020-08-26 06:54:16.587 UTC [28369] LOG: database system is shut down pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission denied pg_ctl: could not access directory "/var/lib/postgresql/10/main": Permission … -
ModelForm Editfield without own html template
I want to create a ModelForm to update a certain Modelfield, but I do not need a new template for this, I want it to be integrated into an already existing template with other functionality. How can I do this? All documentation & tutorials I found show how to do something like this and then render a new template in a views method. Any help is appreciated! -
My Webpage has different views in same browser but another computer with same inches
Hello I just deployed my Django project and everthing is fine but after I opened my webpage with my second computer I sav that the webpage has another look. I just thought it is because my second computer is old but my friend has the same ugly look. I just wondered why this happened because we both used chrome and our computers are 16 inch. So it should be the same. The main reason why I am asking because on the ugly view the fonts are so big that a part of my jumbotron does not fit in the webpage so I cannot read it. Also my footer at the bottom and navbar on the top are real big. I will post my html and the pictures so you can understan what I am saying Thank you very much. Note: For the homepage I have a base.html with the navbar and a homepage.html base.html <!DOCTYPE html> {% load static %} {% load crispy_forms_tags %} <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css2?family=Architects+Daughter&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <meta charset="utf-8"> <title></title> </head> <body style="background-color:#FF9900;;"> <nav … -
How to set up a scheduler and background task with Django and Heroku?
I'm following the guides found here: https://devcenter.heroku.com/articles/clock-processes-python and https://devcenter.heroku.com/articles/python-rq What I'm trying to build is a function to send out emails every X days. Essentially, I need to create a clock process and then set up a scheduler to perform the clock process, but not sure how that works in practice. From the first link, the clock process looks like this: from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('cron', day_of_week='mon-fri', hour=17) def scheduled_job(): print('This job is run every weekday at 5pm.') sched.start() Where in the background task part (https://devcenter.heroku.com/articles/python-rq) should the scheduled_job function be called? I got these two loose docs but not sure how to tie them together -
Django 3.0.8 Test Cases Failing
This is my first time posting here, so I apologize if I make a mistake when asking my question or include too much detail. I'm quite new to Django, and I'm trying to follow a Simple is Better than Complex tutorial. Specifically, I just completed Part 4. I encounter the following 4 failures when I run tests: $ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). .............................FFF.F.................................. ====================================================================== FAIL: test_contains_form (accounts.tests.test_view_password_reset.PasswordResetTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\admin\Desktop\Development\Django\myproject\myproject\accounts\tests\tes t_view_password_reset.py", line 30, in test_contains_form self.assertIsInstance(form, PasswordResetForm) AssertionError: None is not an instance of <class 'django.contrib.auth.forms.PasswordRes etForm'> ====================================================================== FAIL: test_csrf (accounts.tests.test_view_password_reset.PasswordResetTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\admin\Desktop\Development\Django\myproject\myproject\accounts\tests\tes t_view_password_reset.py", line 26, in test_csrf self.assertContains(self.response, 'csrfmiddlewaretoken') File "C:\Users\admin\Desktop\Development\Django\myproject\venv\lib\site-packages\djang o\test\testcases.py", line 454, in assertContains self.assertTrue(real_count != 0, msg_prefix + "Couldn't find %s in response" % text_ repr) AssertionError: False is not true : Couldn't find 'csrfmiddlewaretoken' in response ====================================================================== FAIL: test_form_inputs (accounts.tests.test_view_password_reset.PasswordResetTests) The view must contain two inputs: csrf and email ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\admin\Desktop\Development\Django\myproject\myproject\accounts\tests\tes t_view_password_reset.py", line 36, in test_form_inputs self.assertContains(self.response, '<input', 2) File "C:\Users\admin\Desktop\Development\Django\myproject\venv\lib\site-packages\djang o\test\testcases.py", line 449, in assertContains self.assertEqual( AssertionError: 0 != 2 : Found 0 instances of … -
How to write a test for a custom action on a viewset in Django Rest Framework
I am new to Django, and Django Rest Framework. I would like to know how to go about testing custom actions. For example, assume we have the following code from the DRF tutorials class UserViewSet(viewsets.ModelViewSet): """ A viewset that provides the standard actions """ queryset = User.objects.all() serializer_class = UserSerializer @action(detail=True, methods=['post', 'put']) def set_password(self, request, pk=None): user = self.get_object() serializer = PasswordSerializer(data=request.data) if serializer.is_valid(): user.set_password(serializer.data['password']) user.save() return Response({'status': 'password set'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How would I go about calling this view in a test in DRF. def test_password_set(self): user = User.objects.create(name="Joe") factory = APIRequestFactory() request_url = f'users/{user.id}/set_password/' request = factory.post(request_url) view = UserViewSet.as_view({'put': 'update'}) response = view(request) self.assertEqual(response.status_code, 200) That code gives me the error below AssertionError: 405 != 200 which means that the given method is not allowed. Could anyone help me figure out what the error could be? -
Dynamic file upload with datetime folder structure
New to Django. I want to upload my files to /uploads/YYYY/MM/DD folder. What I try is as follows, a function to generate default value of the folder; and in the file field, I try to set that value to upload_to parameter. Makemigrations works fine, when I run: python3 manage.py migrate The mistake I get is as follows. The method has those arguments? image_upload_folder() missing 2 required positional arguments: 'instance' and 'filename' Here's my code: # generates folder name depending on the date: def create_image_upload_folder(): now = datetime.datetime.now() image_date_folder = now.strftime("%Y/%m/%d") return image_date_folder def image_upload_folder(instance, filename): ROOT_DIR = os.path.dirname(os.path.abspath(__name__)) return ROOT_DIR + '/uploads/' + instance.folder class FileSystem(models.Model): folder = models.CharField(max_length=255, blank=False, null=False, default=create_image_upload_folder) file = models.FileField(blank=False, null=False, upload_to=image_upload_folder) ... -
Django Rest Framework Throttle doesn't work instantly on production
I have an issue with throttling user requests to a certain endpoint. I set the limit for them to make only one request/hour and it works okay locally. However on production, the request may take a bit to return a response and in that case, if the users make any new requests during the processing time, it will pass, until the first request returns a response. Any help or pointers? -
IP address for django-axes logins does not show
I have django-axes running with my Django app and so far everything works fine, however, in the django-axes admin section, the IP addresses do not seem to work. It just shows a "-". Is there perhaps a setting I should configure for django-axes to enable this or is it one of my Django project settings that prevent this? Maybe one of these: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_BROWSER_XSS_FILTER = True SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 2592000 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_REFERRER_POLICY = 'same-origin' SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True X_FRAME_OPTIONS = 'DENY' -
How can I run create-react-app project made react with django template at the same route?
I trying to split react web project with django template. But, this project is so big, and I want to divide it gradually. So my question is, is it possible to run react web made with django template and project newly created with create-react-app in the same route? If possible, how can I separate and running? In my common sense, I can't think of a solution. Sorry for the insufficient question. -
Django adding hour and minute from form
It is possible to add hour, minute and second from admin dashboard, but now I want to add it to my template. models.py: class Document(models.Model): date = models.DateTimeField() forms.py: class CreateDocumentForm(ModelForm): ... class Meta: model = ComplaintDocument fields = '__all__' widgets = { 'date': DateTimeInput(attrs={'type': 'date'}), } -
Django. how to assign the right variable to pre populating the form
I am trying to pre populate the form to the edit entry, but I am having a problem to assign the right variable. I did a test using just a text to populate it, and it works. But could somebody give a hint in how to do it retrieving the content and title from util.save_entry(title,content). My test: def edit_entry(request): title = 'title' content = 'content' if request.method == "GET": form = EditEntryForm(initial={'title': title, 'content': content}) return render(request, "encyclopedia/edit.html", { "form": form }) -
How can I query embedded records in a Djongo ArrayField?
I'm using Django 3.0.6 with Django Rest Framework 3.11.1. I'm connecting to a MongoDB database using the djongo connector. One of my models has an ArrayField that contains embedded records. I would like to know how I can retrieve these embedded fields using a django query. Each Person can have many different sub records. Here is a sample model to illustrate what I'm working on Models: from djongo import models class SubRecords(models.Model): status = models.CharField(max_length=20) startTime = models.CharField(max_length=20) identifier = models.CharField(max_length=20) job_title = models.CharField(max_length=20) class Meta: abstract = True class Person(models.Model): _id = ObjectIdField() workplace = models.CharField(max_length=120) subject = models.CharField(max_length=120) records = models.ArrayField(model_container=SubRecords) I would like to query the Person model and get all Person.records objects and Person.records objects that match some criteria I have tried to do this >>> Person.objects.filter(records__exact={'job_title': 'HR'}) Now the problem I'm facing is that the result isn't limited to subrecords where the job title is HR, instead if a Person object contains a sub record that matches the criteria, the whole Person object and associated sub records are returned. I want to be able to get a list of all the subrecords and only the subrecords that match the criteria I specify. How can I … -
How do I combine two arrays in for loop fashion so the 3 items of one list appear then 1 item of the other list appears, in python (django)
I'm building a social media site with events and posts and I want the user feed to have new events advertised every 4 posts. So basically the feed would look like: Post 1, Post 2, Post 3, Event 1, Post 4, Post 5, Post 6, Event 2, ... Do I do this in the template or view? And how do I do it? -
MultiValueDictKeyError at /new_search/realme-xt-pearl-blue-64-gb/p/i/realme-xt
I want to capture the url parameters to views.How can I do it? views.py def new_search(request,linkadd,text): serch = request.GET['linkadd'] link = request.GET['text'] html {% for post in product_names %} <a id="link" href="{% url 'new_search' linkadd=post.1 text=post.0 %}" value="{{ post.0 }}">{{ post.0 }}</p> {% endfor %} urls.py urlpatterns = [ url(r'^new_search(?P<linkadd>)/(?P<text>)',views.new_search,name='new_search'), ] I want to get link and text from the url "120.0.0.0:8000/1232-23232-32-2323sdsjdhjas/redmi" assume :1232-23232-32-2323sdsjdhjas as link and redmi as text but I get the error like this please suggest me how to do it MultiValueDictKeyError at /new_search/realme-xt-pearl-blue-64-gb/p/itm731360fdbd273?pid=MOBFJYBE9FHXFEFJ&lid=LSTMOBFJYBE9FHXFEFJNVQVIV&marketplace=FLIPKART&srno=s_1_1&otracker=search&fm=organic&iid=a64429b9-99a5-405b-8edb-9d94934fb991.MOBFJYBE9FHXFEFJ.SEARCH&ssid=iprr3ut7io0000001598430215812&qH=23f6a0071022557e/Realme XT (Pearl Blue, 64 GB) Please help me..Thanks in advance!! -
Redirect using next in django even after taking multiple attempts to login
I am having this login view: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": email=request.POST['email'] password=request.POST['password'] user=auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) next_page = request.POST['next'] if next_page != '': return redirect(next_page) else: return redirect('/') else: messages.info(request,"Email Password didn't match") return redirect('login') else: return render(request,"login.html") In this if a user comes to a page where login is required then he is redirected to login page and when he logs in successfully he is redirected to the page where he came from. But the problem arises when the user does not login in first attempt(enters wrong email or password) then the login page reloads and then if he logs in successfully he isnt redirected to the page where he came from. How can I work this out so that no matter the number of attempts the user takes to login he is redirected to the same page from where he came from. -
Dont work command 'django-admin.py startproject blog .'. IDE just show script and nothing happens
I try to create new django project in Pycharm IDE. After correct installing Django i try to do this command in terminal "django-admin.py startproject blog .", but IDE show me this script in new window and nothing happening. How can i fix this? enter image description here -
Is foreign key reference is necessary when using schemas for data isolation?
I am doing some research on data isolation strategies for a SaaS project. I am using Django with PostgreSQL. I have three options, separate database for each tenant, the separate schema for each tenant, foreign key reference of each tenant in every table. 2nd approach suits best for my requirements. My question is that, if I create a separate schema for every tenant, how secure is that? Should I still add a foreign key reference in every major entity and add filtration logic to the application layer? Any suggestions on improving the overall design are also welcome. -
NoReverseMatch Reverse for 'teacher_edit' with no arguments not found. 1 pattern(s) tried
my part of code of html link is: <button type="submit" name="btnedit" id="rpt_teacher_btnedit_0" class="btn btn-secondary btn-sm" onclick="window.location.href='{% url 'institute_module:teacher_edit' teacher.id %}'" /><i class="fa fa-edit"> Edit</i></button> view.py def teacher_edit(request, tch_id): teacher_details = TEACHER.objects.get(id=tch_id) return render(request, 'institute/teacher_edit.html') urls.py path('Institute/Teacher_Reg/edit/<int:tch_id>', views.teacher_edit, name='teacher_edit'), -
How to debug django in spyder
I have a django project which I would like to start in debug mode so I can use breakpoints in spyder to see what is happening. However I do not know how to start the manage.py runserver in debug mode in spyder. Unfortunately I am stuck with spyder for this (unfortunate because I know how to do it in vs code). Can anybody help me? -
Django Annotation with Sum(Case(When))) returning wrong values
In a Django 1.9 app, I need to annotate a queryset in order to get a number of related entities without querying the DB multiple times. The problem is that with such an old version of Django, the filtering function on Count with related entities is not available and I need to use Sum(Case(When))) to be able to filter. I have a job model that can have multiple matches and multiple fits. Here is the code about the annotation part. unchecked_fits = Count('fits', distinct=True) nb_matches_proposition = Sum(Case(When(matches__current_status=MATCH_PP_STATUS, then=1), default=0, output_field=IntegerField()), distinct=True) nb_matches_preselection = Sum(Case(When(matches__current_status=MATCH_PRESELECTION_STATUS, then=1), default=0, output_field=IntegerField()), distinct=True) nb_matches_valides = Sum(Case(When(matches__current_status=MATCH_VALIDES_STATUS, then=1), default=0, output_field=IntegerField()), distinct=True) nb_matches_entretiens = Sum(Case(When(matches__current_status=MATCH_ENTRETIENS_STATUS, then=1), default=0, output_field=IntegerField()), distinct=True) jobs = Job.objects.filter( job_team_owner=user, current_status__in=active_statuses, open_to_suggestion=False ).annotate( # unchecked_fits = unchecked_fits, nb_matches_proposition = nb_matches_proposition, nb_matches_preselection = nb_matches_preselection, nb_matches_valides = nb_matches_valides, nb_matches_entretiens = nb_matches_entretiens, ).order_by('-date_created').select_related('company') The numbers returned by the annotated fields are correct when I comment the unchecked_fits annotated field but they give me much too high values when I uncomment it. Strangely enough, I noticed that all the nb_matches_xxx fields get multiplied by the value of unchecked_fits when I uncomment. I guess there's just something wrong with my syntax but I do no get it... Any help …