Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why django tearDown does not delete the test data after exception in tests?
I created an exception in the test function but after this exception, tearDown did not delete data from the database. def test_duty_sync_data_daily(self): duties, device_id = factory_boy_create_fake_data() url_duty = reverse('habit:duty-sync-data') response_duty = self.user.post( url_duty, data=duties, HTTP_USER_AGENT='Mozilla/5.0' ) self.assertEqual(response_duty.status_code, status.HTTP_200_OK) raise Exception -
Elastic Beans + Django. Switch HTTP to HTTPS using Load Balancer
Dear Stackoverflow community. This question has been asked before, but my question is little bit different. So I am using Elasticbeanstalk to deploy my Django Backend and RDS for database (PostgreSQL). EB generated a link for my backend --> http://XXXXX.region.elasticbeans.com. The issue is that when I send a request from the frontend side (HTTPS), it gives a "Blocked loading mixed active content" error, which comes from HTTPS to HTTP request. As far as I am concerned I have to change configuration of the Load Balancer of my EC2 instance and add redirection. In order to successfully do that I am required to have a SSL certificate. However, when I use ACM (Certificate Manager) in order to generate one using the exact same link for the backend, it automatically rejects my request. So my question is that what is the exact process of obtaining the SSL cert. for the default EB link, or maybe there are easier ways to redirect HTTP to HTTPS from the AWS console? Regards. -
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` DRF
I am receiving the error Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> In Django DRF, in my query i am trying to get the count of all related items to one specific item the views.py @api_view(['GET']) def getVesselInfo(request): vessels = (Vessel.objects.annotate( Count('vessel_components', distinct=True))) vSerializer = VesselSerializer(vessels, many=True) return Response(vSerializer.data,) models.py: class Vessel(models.Model): name = models.CharField(max_length=255) imo = models.CharField(max_length=255) def __str__(self): return self.name class Component(MP_Node): name = models.CharField(max_length=255, blank=True, null=True) manufacturer = models.CharField(max_length=200, blank=True, null=True) model = models.CharField(max_length=200, blank=True, null=True) type = models.CharField(max_length=200, blank=True, null=True) remarks = models.TextField(blank=True, null=True) vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_components') def __str__(self): return self.name -
How to extract desired value from queryset value of dict type using annotate d in Django
[views.py] from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') histories = History.objects.filter(summary__icontains='teacher', date__gte=from_date, date__lte=to_date).order_by('date').annotate(teacher=F('summary')).values('study_name', 'teacher', 'date') return render(request, 'charts.html', { 'histories': histories, 'from_date': from_date, 'to_date': to_date }) The History model has summary and create_date fields. To check the type of the field value in the template, make and check get_type template tag and the summary field was a dict type. I don't need the entire summary field value, I just want to extract the teacher value and store it in a temporary field called 'teacher' using annotate. entire summary field value is: {'field_summary': {'recruiting': 'None -> Yes', 'teacher': 'None -> Halen', 'subject': None -> 'science'}, 'file_summary': {}} So the result I want is: [charts.html] {{ histories }} [display] <QuerySet [{'study_name': 'math', 'create_date': datetime.datetime(2022, 1, 4, 0, 24, 33, 357339, tzinfo=<UTC>), 'teacher': 'None -> Halen'}, {'study_name': 'science', 'create_date': datetime.datetime(2022, 3, 2, 10, 10, 33, 733339, tzinfo=<UTC>), 'teacher': 'None -> Kevin'}, {'study_name': 'music', 'create_date': datetime.datetime(2022, 2, 10, 3, 11, 33, 738452, tzinfo=<UTC>), 'teacher': 'Mark'}]> I want to get the queryset value in dict format by utilizing annotate in django's views.py. -
Custom permissions in django isn't working
I want to add custom permissions: Only admin and owner of the object can modify the object All registered users can view the objects My solution: SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') class IsApplicationAdmin(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated: if request.user.is_superuser or request.user.user_type == "Admin": return True if request.method in SAFE_METHODS: return True def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True return obj.user_name == request.user # owner can modify the object PROBLEM -- for PATCH request (partial update) http://127.0.0.1:8000/api/admin_panel/users/2/ I have this error { "detail": "You do not have permission to perform this action." } I was debugging the code and see debugging log only in has_permission (no logs in has_object_permission) What should I fix? I was reading https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions and the table said that PATH request relates to object permissions -
How do I test for str equality using factory_boy faker method?
I have two factory classes, the other is linked to the one through foreign key relationships, and was kinda hoping to achieve some similarities with the attributes. To start with, the model looks something like this: class Track(models.Model): response = models.ForeignKey('Response') def __str__(self): return str(self.response) class Response(models.Model): title = models.CharField(max_length=640) def __str__(self): return self.title I should be able to access these classes as I have done below r = Response(title='foo') r.save() t = Track(response=r) t.save() # with this I wanted to test that str(t) == t.response The factory classes look like this: class ResponseFactory(factory.django.DjangoModelFactory): class Meta: model = Response title = factory.Faker('text') class TrackFactory(factory.django.DjangoModelFactory): class Meta: model = Track response = factory.SubFactory(ResponseFactory) Below is how I have accessed these factory classes to test for str equality track = TrackFactory() # generates random string e.g `foo` a = str(track) # == foo b = track.response # == foo # however I get an assertion error with the statement below assert a == b Could you point out where I've gone wrong, thank you. -
Django Password reset view with reactjs
I am a total Django-React fresher. I want to use Django's PasswordResetView Functionality in my Django API with Reactjs as frontend. The Existing functionality is implemented in auth_view which is using templates. Can anybody guide me on how to use it with my custom API? -
I am getting an error message that password does not match in django forms
I am creating a "UsercreationForm" in django. When I saved the form, it didn't create any entry in database then I debug it and found an error message that Password fields does not match I don't know what I did wrong. Please help me figure it out. Here is my forms.py from django import forms from accounts.models import Customer, User from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError from datetime import datetime class UserSignup(UserCreationForm): class Meta: model = User fields = ("username","first_name", "last_name", "email") username = forms.CharField(label="Username", required=True) first_name= forms.CharField(label="First Name", required=True) last_name=forms.CharField(label="Last Name", required=False) email =forms.EmailField(label="Email", required=False) password1 = forms.CharField(label="Password", required=True) password2 = forms.CharField(label="Confirm Password", required=True) def username_clean(self): username = self.cleaned_data['username'].lower() new = User.objects.filter(username = username) if new.count(): raise ValidationError("User Already Exist") return username def email_clean(self): email = self.cleaned_data['email'].lower() new = User.objects.filter(email=email) if new.count(): raise ValidationError(" Email Already Exist") return email def clean_password2(self): password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 != password2: raise ValidationError("Password don't match") return password2 def save(self, commit = True): user = User.objects.create_user( self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1'], last_login= datetime.now() ) return user class AddDetails(forms.ModelForm): class Meta: model = Customer fields = ("age", "phone") age = forms.IntegerField(label="Age", required=True) phone = forms.CharField(label="Mobile Number", required=True) Here is my views.py … -
How to post using reverse in test Django
I have a test, where I try to update my post. In detailview I use pk for each posts. How to send correctly pk in test? I try this but get an error. test: def test_if_user_can_update_news(self): self.client.login(username='test1', password='test1') news = News.objects.get(title='Test news') self.client.post(reverse('update_news', kwargs={ 'pk': news.pk, 'title': 'Updated news'})) self.assertTrue(News.objects.filter(title='Updated news').exists()) error: django.urls.exceptions.NoReverseMatch: Reverse for 'update_news' with keyword arguments '{'pk': 1, 'title': 'Updated news'}' not found. 1 pattern(s) tried: ['news/update_news/(?P<pk>[0-9]+)/\\Z'] -
How to get a download option of dynamic table in Django Database ( each time we will have different tables in Database)
I have tables in Django Data Base with name TBL_Result_1_1, TBL_Result_1_2 etc. Image of All tables in Django Backend I want to provide a download option in agnular frontend to download all TBL_Result.. tables provided these tables name are not permanent, more tables will add with name TBL_Result.. in django database. I have used models.py for static tables in django, but these tabbles are dynamic. Will not able to add models.py each time for each table. -
Month on month values in django query
I have an annotation like this: which displays the month wise count of a field bar = Foo.objects.annotate( item_count=Count('item') ).order_by('-item_month', '-item_year') and this produces output like this: html render I would like to show the change in item_count when compared with the previous month item_count for each month (except the first month). How could I achieve this using annotations or do I need to use pandas? Thanks -
How to perform n time or query using ORM?
I have an array of values values['value1','value2'....n] I want to perform the following query res = TheModel.objects.filter(key=values[0] or key = values[1] or key = values[2]...n) Here the problem is array size may be different every time. How can I achieve this? -
403 forbidden for presigned_url upload
I have 403 error when uploading presigned url At first, I exec s3.generate_presigned_post in local temp = s3.generate_presigned_post( "my-resource-bucket-v","test" ) and get the url and fields {'url': 'https://my-resource-bucket-v.s3.amazonaws.com/', 'fields': {'key': 'test', 'AWSAccessKeyId': 'AKIAZ3YPMLASV6736UA4', 'policy': 'eyJleHBpcmF0aW9uIjogIjIwMjItMDUtMDlUMDY6MDU6MTNaIiwgImNvbmRpdGlvbnMiOiBbeyJidWNrZXQiOiAic2kyLXMzLXNidS1qb2ItaHVudGluZy1keC10b2t5by1qeGMtc3RhdGljLXJlc291cmNlLXYifSwgeyJrZXkiOiAidGVzdCJ9XX0=', 'signature': 'F7E074YWIVwy4ZL2zXSv8YVTbyE='}}" then I try this to upload curl -v -X POST \ -F key="{'key': 'test', 'AWSAccessKeyId': 'AKIAZ3YPMLASV6736UA4', 'policy': 'eyJleHBpcmF0aW9uIjogIjIwMjItMDUtMDlUMDY6MTE6MjhaIiwgImNvbmRpdGlvbnMiOiBbeyJidWNrZXQiOiAic2kyLXMzLXNidS1qb2ItaHVudGluZy1keC10b2t5by1qeGMtc3RhdGljLXJlc291cmNlLXYifSwgeyJrZXkiOiAidGVzdCJ9XX0=', 'signature': 'GNUthYj0cec9uIQjeJsuap7OTfk='}" \ -F policy="{'key': 'test', 'AWSAccessKeyId': 'AKIAZ3YPMLASV6736UA4', 'policy': 'eyJleHBpcmF0aW9uIjogIjIwMjItMDUtMDlUMDY6MTE6MjhaIiwgImNvbmRpdGlvbnMiOiBbeyJidWNrZXQiOiAic2kyLXMzLXNidS1qb2ItaHVudGluZy1keC10b2t5by1qeGMtc3RhdGljLXJlc291cmNlLXYifSwgeyJrZXkiOiAidGVzdCJ9XX0=', 'signature': 'GNUthYj0cec9uIQjeJsuap7OTfk='}" \ -F file=myimage.png https://my-resource-bucket-v/ It returns like this. I think bucket policy of S3 is not relevant with presigned_url, So,, where the permission error occurs?? Note: Unnecessary use of -X or --request, POST is already inferred. * Trying 52.219.196.109:443... * Connected to my-resource-bucket-v.s3.amazonaws.com (52.219.196.109) port 443 (#0) * ALPN, offering h2 * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: /etc/ssl/cert.pem * CApath: none * TLSv1.2 (OUT), TLS handshake, Client hello (1): * TLSv1.2 (IN), TLS handshake, Server hello (2): * TLSv1.2 (IN), TLS handshake, Certificate (11): * TLSv1.2 (IN), TLS handshake, Server key exchange (12): * TLSv1.2 (IN), TLS handshake, Server finished (14): * TLSv1.2 (OUT), TLS handshake, Client key exchange (16): * TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1): * TLSv1.2 (OUT), TLS handshake, Finished (20): … -
Is it able to delete the file after I send files in Django
from django.http import FileResponse def send_file: #some processes response = FileResponse(open(file_name, 'rb'),as_attachment=True) return response I want to delete the file after my web app send it, but my server on Heroku only have 512M . So I can't use too much memory. How can I do that? Many thanks -
Need to Override the save method to save it as base64 from Image field Django
models.py def upload_org_logo(instance, filename): ts = calendar.timegm(time.gmtime()) filepath = f"org_logo/{ts}" if instance: filepath = f"org_logo/{instance.org_id}/{instance.org_name}" base, extension = os.path.splitext(filename.lower()) return filepath class Organisation(models.Model): """ Organisation model """ org_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) org_name = models.CharField(unique=True,max_length=100) org_code = models.CharField(unique=True,max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, default='blank.jpg', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) org_logo_b64 = models.BinaryField(blank=True, null=True) def save(self, *args, **kwargs): if self.org_logo: logo = open(self.org_logo.url, "rb") print(logo) self.org_logo_b64 = base64.b64encode(logo.read()) super(Image, self).save(*args, **kwargs) When I tried to Post, it is throwing me an error as FileNotFoundError at /admin/onboarding/organisation/7577ef5f-356c-4cbd-8ef6-e906382447ff/change/ [Errno 2] No such file or directory: '/media/white-logo.png' Request Method: POST Request URL: http://127.0.0.1:8000/admin/onboarding/organisation/7577ef5f-356c-4cbd-8ef6-e906382447ff/change/ Django Version: 3.2.12 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: '/media/white-logo.png' Exception Location: F:\PM-Onboarding-Service\Onboarding-Service\microservices\onboarding\models.py, line 244, in save I tried the method based on this answer django admin: save image like base64. My settings for Media is: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Can anyone please help me to save the image as base64 in the database by override the save method for the imagefield? -
I can't create super user
I am building my website with Django. I need to create a super user but there is a huge error after I enter the user, mail, password. Without a super user, I will not be able to continue developing the project, therefore, I ask for help. Error: Traceback (most recent call last): File "/home/runner/laba/venv/lib/python3.8/site-packages/django/contrib/auth/password_validation.py", line 210, in __init__ with gzip.open(password_list_path, 'rt', encoding='utf-8') as f: File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/gzip.py", line 58, in open binary_file = GzipFile(filename, gz_mode, compresslevel) File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/gzip.py", line 173, in __init__ fileobj = self.myfileobj = builtins.open(filename, mode or 'rb') FileNotFoundError: [Errno 2] No such file or directory: '/home/runner/.cache/pip/pool/d4/1e/2a/common-passwords.txt.gz' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/runner/laba/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 157, in handle validate_password(password2, self.UserModel(**fake_user_data)) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/contrib/auth/password_validation.py", line 44, in validate_password password_validators = get_default_password_validators() File "/home/runner/laba/venv/lib/python3.8/site-packages/django/contrib/auth/password_validation.py", line 19, in get_default_password_validators return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) File "/home/runner/laba/venv/lib/python3.8/site-packages/django/contrib/auth/password_validation.py", line 30, in get_password_validators validators.append(klass(**validator.get('OPTIONS', {}))) … -
Django ORM Query to show pending payments
Please guide me. I have below models under which a Student can enroll for a course which has a fees specified for it. Against that enrollment a student can make part payments. I am unable to create a query which will show me list of students with courses enrolled and total payment made for that enrollment. class Course(models.Model): name = models.CharField(max_length=100) school = models.ForeignKey(School, on_delete=models.CASCADE) student_class = models.IntegerField(verbose_name="Class", help_text="Class", choices= STUDENT_CLASS) fee = models.IntegerField() created_on = models.DateField(auto_now_add=True) class Enrollment(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) created_on = models.DateField(auto_now_add=True) class Payment(models.Model): PAYMENT_CHOICES = [ ('CAS', 'Cash'), ('CHQ','Cheque'), ] enrollment = models.ForeignKey(Enrollment, on_delete=models.CASCADE) amount = models.IntegerField() mode = models.CharField(max_length=3, choices=PAYMENT_CHOICES) payment_date = models.DateField(auto_now_add=True) -
Failed to pass html input to django
I'm trying to pass date input to django python script in order to retrieve the data based on it. Here is my code. view def daily_usage_report(request): if request.method == 'POST': request_date = request.POST.get('request_date') else: request_date = date.today() print(request_date) ... html <form method="post" action="#"> <input type="date" name="request_date" id="request_date"> <button class="btn btn-primary"><a href="{% url 'daily_usage_report' %}" style="color: white;">Daily Usage Report</a></button> </form> I tried to fill the form with random date, but it keeps printing today date. -
Replace Keyword Argument With Variable in Django Model Filtering
I am performing filtering on a django model based on the data supplied by user in an input form. I don't want to hard-code values and so I would love to loop through the entire query parameters in request.POST and then filter by the key and value. Here is a sample from my code class QueryView(View): def post(self, request, *args, **kwargs): params = request.POST if params: for key in params: queryset = MyModel.objects.filter(key=params[key]) return MyResponse I can't get things to work as key must be a field in MyModel, is there a better way of achieving this same goal. -
How to get value of json field in django views.py
[views.py] from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') histories = History.objects.filter(content__icontains='teacher', date__gte=from_date, date__lte=to_date).order_by('date') for h in histories: histories = History.objects.annotate(teacher=json.loads(h.summary)).values('study_name', 'teacher', 'date') I am trying to print the 'study_name', 'summary', and 'date' fields of the History model that satisfy the period set in Django views.py . The summary field uses json.loads as the json type, but the following error occurs. QuerySet.annotate() received non-expression(s): {'field_summary': {'recruiting': 'None -> Yes', 'teacher': 'None -> Halen', 'subject': 'None -> 'science'}, 'file_summary': {}}. How to get the teacher value of field_summary? -
Werkzeug server is shutting down in Django application
after updating the Werkzeug version from 2.0.3 to 2.1.0, I keep getting errors every time I run the server, and here is the error log: Exception happened during processing of request from ('127.0.0.1', 44612) Traceback (most recent call last): File "/usr/lib/python3.8/socketserver.py", line 683, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.8/socketserver.py", line 747, in __init__ self.handle() File "/home/oladhari/.virtualenvs/reachat/lib/python3.8/site-packages/werkzeug/serving.py", line 363, in handle super().handle() File "/usr/lib/python3.8/http/server.py", line 427, in handle self.handle_one_request() File "/usr/lib/python3.8/http/server.py", line 415, in handle_one_request method() File "/home/oladhari/.virtualenvs/reachat/lib/python3.8/site-packages/werkzeug/serving.py", line 243, in run_wsgi self.environ = environ = self.make_environ() File "/home/oladhari/.virtualenvs/reachat/lib/python3.8/site-packages/django_extensions/management/commands/runserver_plus.py", line 326, in make_environ del environ['werkzeug.server.shutdown'] KeyError: 'werkzeug.server.shutdown' this exception keep appearing while incrementing by 2 ( ('127.0.0.1', 44612) -> ('127.0.0.1', 44628) and the server crash checking the changes log, I have found this detail: Remove previously deprecated code. #2276 Remove the non-standard shutdown function from the WSGI environ when running the development server. See the docs for alternatives. here is the link to the changes log it asks to check the documentation for alternatives but can not find any please let me know how I would resolve this error, thank you NB: my python version is 3.8 -
Django Rest Framework API with Primary Key Related Field serializer says that field is required even when it is included
I have an API with Django Rest Framework and one of my Serializers looks like this: class InputtedWaittimeSerializer(serializers.ModelSerializer): restaurant = serializers.PrimaryKeyRelatedField(many=False, queryset=Restaurant.objects.all(), read_only = False) reporting_user = serializers.PrimaryKeyRelatedField(many=False, queryset=AppUser.objects.all(), read_only = False) class Meta: model = InputtedWaittime fields = ['id', 'restaurant', 'wait_length', 'reporting_user', 'accuracy', 'point_value', 'post_time', 'arrival_time', 'seated_time'] depth = 1 read_only_fields = ('id','accuracy','point_value','post_time') Restaurant and AppUser are both different models, and the Serializer model (InputtedWaittime) has fields that are foreign keys to the first two models. I added a PrimaryKeyRelatedField for each of these foreign key relations so that the API would only show their primary keys. So, a GET request to this API looks like this: { "id": 1, "restaurant": 1, "wait_length": 22, "reporting_user": 1, "accuracy": 1.0, "point_value": 10, "post_time": "2022-05-08T23:39:11.414114Z", "arrival_time": "2022-05-08T23:39:05Z", "seated_time": null } Where reporting_user and restaurant just have the primary keys to their entries in the other models. However, I have run into a problem when I try to POST data to this API. When I send data in with just the primary keys for the foreign key fields, the API just returns this response: {"restaurant":["This field is required."],"reporting_user":["This field is required."]}% I used this command to POST data to this API: curl -X … -
PayPal Advanced Credit Card Payments - paypal.HostedFields.isEligible() returns False
I'm trying to integrate PayPal's advanced credit card payments into my web app but the below code always returns false. paypal.HostedFields.isEligible() I've checked the account settings about 100 times. I've enabled all credit card payments, created sandbox businesses accounts and etc. still getting the same error. FYI.. paypal.Buttons works without any issues. Any idea how can I resolve this? -
How to run pytest upon successful post in Django Rest framework?
I want pytest to call a function that can run if a post type is successful and do the same on github actions? It is a django rest framework project and the model is routed as a URL having a single field only At the moment I have multiple import issues cause the previous developer have made multiple .venvs and both useless so python cannot resolve host for most of the import in the project I also have a submodule which also has test files and I want to ignore that is it possible to ignore tests for a specific directory? -
Django not redirecting to home page after filling in register form
I'm new to django. I want to redirect to the home page after filling in the form to register a new user. But that doesn't happen when I click the submit button. Instead, the form fields are cleared and that's it. I've created two apps: blog and users Here's the basic structure of my project, if it's of any importance: ───django_project │ db.sqlite3 │ manage.py │ ├───blog │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ 0001_initial.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ 0001_initial.cpython-39.pyc │ │ __init__.cpython-39.pyc │ │ │ ├───static │ │ └───blog │ │ main.css │ │ │ ├───templates │ │ └───blog │ │ about.html │ │ base.html │ │ home.html │ │ │ └───__pycache__ │ admin.cpython-39.pyc │ apps.cpython-39.pyc │ models.cpython-39.pyc │ urls.cpython-39.pyc │ views.cpython-39.pyc │ __init__.cpython-39.pyc │ ├───django_project │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ settings.cpython-39.pyc │ urls.cpython-39.pyc │ wsgi.cpython-39.pyc │ __init__.cpython-39.pyc │ └───users │ admin.py │ apps.py │ models.py │ tests.py │ urls.py │ views.py │ __init__.py │ …