Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to handle DecimalField with NaNs in Django 4?
Django issue 33033 says that DecimalField has never supported handling NaNs. However, until recent Django, those were permitted, so I have a database full of them from Django 3.2.13. What's the easiest way to support a DecimalField with NaN in Django now that the official DecimalField prevents them (with an exception)? I could make another custom field that has an extra field saying whether the value is a NaN or not. Seems terribly awkward. -
Blocking INVALID_HOST + Bad Request attempts in AWS
I have a Django app running in Elastic Beanstalk. Every day, I am seeing a ton of seemingly malicious attempts to get into my app. Here are the most common type of events: Invalid HTTP_HOST header: '52.33.#.#'. You may need to add '52.33.#.#' to ALLOWED_HOSTS. or Bad Request: /sitemap.xml (many different URL patterns beyond sitemap.xml) I saw a post here about deploying WAF rules as a potential solution. I would rather go this route if there is a predefined path. Looking for some collective wisdom on how to block this junk traffic. Thanks. -
How can i solve syntax error during making webapp?
im working with django and making webapp now this has occurred def Notes(generic.DetailView): ^ Error invalid syntax Function name:NotesDetaiView -
How to get the selected value from html select with django
I would like to know if it's possible to get the selected value from a select HTML without using a submit input? Because when I hit the submit, the value selected is returned but it reloads the web page and the select goes back to it's intial state. Here is my code to visualize better: views.py def index(request): id_desi = request.POST.get('drop_desi') return render(request, 'index.html', {'designation_liste': df.designation_liste}) index.html <form action="{% url 'DataMat-index' %}" method="POST">{% csrf_token %} <select name="drop_desi"> <option disabled selected value> -- select value -- </option> {% for i in designation_liste %} <option value="{{ i }}">{{ i }}</option> {% endfor %} </select> <input type="submit" value="valider"> </form> -
Custom Django 'delete' action not firing from admin list view
I have a 'notes' model in my Django app where I've built some custom delete actions: class Note(models.Model): [MODEL FIELDS HERE] def delete(self, *args, **kwargs): [STUFF HEPPENS HERE] super(Note, self).delete() If I click into the individual note from the Django admin and hit the 'Delete' button, the custom delete actions work just fine, but if I check the box next to the note in the list view and choose 'Delete selected notes' from the dropdown, they do not. What am I missing here? -
I can't use Tiny Mce in django properly
My models.py from django.db import models from tinymce.models import HTMLField # Create your models here. class Post(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) content = HTMLField() author = models.CharField(max_length=50) slug = models.CharField(max_length=130) date_and_time = models.DateTimeField(blank=True) def __str__(self): return self.title I got this output using Tinymce I think models.py is use for this question's answer. I hope any devloper answer -
How to log to a new file in every route handler function?
In my flask api, I have a function like this: @app.route('/sample_route') def my_func(): # log something... # doing something... # log the processing results to a new .log file I want to create a new .log file every time a new request comes to my_func function. I've tried some ways but none of them works correctly. Does anyone have an idea? -
django send mail on update password
I have a ChangePasswordView for my User: class ChangePasswordView(PasswordChangeView): form_class = ChangePasswordForm success_url = reverse_lazy('password_success') I've been using the send_mail function to notify Users when they update their information, however, in this case, I'm having some trouble. I added this to my ChangePasswordView: def form_valid(self, form): form.update_password_email() return redirect(self.success_url) And this to my ChangePasswordForm: def update_password_email(self): email = self.cleaned_data.get('email', None) if email and self.is_valid(): send_mail( 'Password changed', 'Message', NOTIFICATION_EMAIL, [self.cleaned_data['email']], fail_silently=True ) But it doesn't work. I go to django's change password page, enter my old password, new password and confirm it, but the logic isn't running. Instead I get redirected to my success_url with no password change and no email notification. Is the issue happening because of my view or my form? And what issue is happening. Also do I need form_valid(): and if self.is_valid(): or is one of those extra? I assume they're doing the same thing. -
heroku logs is giving an error, after uploading it on heroku
enter image description here enter image description here I uploaded a django project in heroku, but getting an application error, am i missing something in procfile?? , what changes should I make -
How to manage two user roles in flutter?
I am building an MVP for a two-user type flutter mobile app,(eg: Like a delivery app with a driver and a rider). Since is an MVP is it efficient to keep both user types in one application and switch app states depending on the type of the user and their role? -
Django Unique Constraint for Three fields Not working
I have the following model. class ModelAnswer(BaseModel): questions = models.ForeignKey( to=ModelQuestions, on_delete=models.CASCADE ) answer = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.questions} - by {self.user}' class Meta: constraints = [ models.UniqueConstraint(fields=['created_at','user', 'questions' ], name='unique questions per user') ] plan is to have one answer per question by user per day ie on next day new answer can be added for new question but only once. I tried adding unique constraint but it does not work My question model is as class ModelQuestions(BaseModel): MODEL_CATEGORY_CHOICES = ( ('Circumstances', 'Circumstances'), ('Thoughts', 'Thoughts'), ('Feelings', 'Feelings'), ('Action', 'Action'), ('Result', 'Result')) model_subcategory = models.CharField(max_length=50, choices=MODEL_CATEGORY_CHOICES) questions = models.CharField(max_length=200) def __str__(self): return self.model_subcategory How do I allow the unique answers to questions by users each day? Although I tried filtering method with exists() soln but I want to implement with unique constraint. -
How to solve users' lazy time input method in python DateTimeField? [closed]
In my Django application, there is a field that accepts User/ Admin's input time. The expect outcomes would be: Input 7 indicates 7:00 Input 715, then it would be recognized at 7:15. The same 2011 -->20:11 015 -->0015 Any comments? P.S. I don't have code because I would like to know the apprach first. Thank you! -
why I receive 'Duplicate entry' error in django testing?
I had some unit tests in Django that worked fine. I added some lines to send queries to MySQL. After that every unit test that includes authentication is raising exceptions, even I remove those lines. what is the problem? Django error report: _mysql.connection.query(self, query) django.db.utils.IntegrityError: (1062, "Duplicate entry 'myuser' for key 'auth_user.username'") My Tests: class AnnotationPage(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user( username='myuser', password='12345678') def test_labeling(self): ajaxData = {'testing': 'True', 'direction': 'forward'} request = self.factory.post('/annotation', ajaxData) request.user = self.user response = AnnotationView(request) assert response.content == b'{"image": "image.png", "id": 1}' My Tests with queries: class AnnotationPage(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user( username='myuser', password='12345678') self.cursor = connection.cursor() query = "TRUNCATE TABLE homepage_imagelabel" self.cursor.execute(query) def test_labeling(self): self.cursor = connection.cursor() query = "INSERT INTO homepage_imagelabel (ImageFile) VALUES ('image.png')" self.cursor.execute(query) ajaxData = {'testing': 'True', 'direction': 'forward'} request = self.factory.post('/annotation', ajaxData) request.user = self.user response = AnnotationView(request) assert response.content == b'{"image": "image.png", "id": 1}' -
Why does Stripe's webhook send the same event twice at about the same time?
I'm building a payment system using Stripe. After making a payment with Stripe, we use the 'invoice.paid' event to authorize the user. I've tried it several times and noticed that the webhook sends the same event twice at about the same time. This reproduced the same problem both when I made a payment in test mode from a web page and when I ran the following command from the terminal. stripe events resend evt_xxxxxxxxxxxxxxx However, this is a phenomenon confirmed only in the development environment by executing the following command. stripe listen --forward-to http://0.0.0.0:8080/webhook/ I haven't tried it in production yet. I get the same event twice, so I saved the event ID and set it to return 200 status when I received the second event. def webhook_view (request): payload = json.loads(request.body) event_id = payload.get('id') event_type = payload.get('type','') logger.info (f'type: {event_type} event_id: {event_id}') if Event.objects.filter (id = event_id).exists (): logger.info (f'{event_id} already exists') return HttpResponse (status = 200) Event (id = event_id, created_at = timezone.now(), data = json.dumps(payload)).save() However, the interval between the two requests is so short that the second event passes the check. [2022-07-24 22:28:53,677] [webhook_view: 60] type: invoice.paid event_id: evt_1LP4n0BB5Q5Dr2x7QDEfWFak [2022-07-24 22:28:53,682] [webhook_view: 60] type: invoice.paid event_id: … -
Django | Can't render out user specific content
I am trying to render out model objects that are unique to a user. All methods I've found haven't worked and I've been trying to figure this out for a while now. What is supposed to happen is that you can see the jobs you've posted in the manage-jobs.html template. Also I've removed all of my failed attempts to render out user specific content, it's not that I haven't tried to do this by myself. Thanks. models.py class Job(models.Model): company = models.CharField(max_length=40, null=True, verbose_name="Company/Employer") description = models.TextField(null=True) role = models.CharField(max_length=25) area_of_filming = models.CharField(max_length=50, verbose_name="Area Of Filming", default="") contact_email = models.EmailField(verbose_name='Contact Email', max_length=60, default='') created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(Account, default='', null=True, on_delete=models.CASCADE) def __str__(self): return self.company class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) name = models.CharField(max_length=45, unique=False) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_employee = models.BooleanField(default=True, verbose_name='Are you using FilmLink as an employee?') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'is_employee'] objects = MyAccountManager() class Meta: permissions = [ ("post_jobs", "Can post jobs"), ] def __str__(self): return self.name def has_perm(self, perm, obj=None): return True def has_perms(self, perm): return True def has_module_perms(self, app_label): return True @property … -
How to access External url link in django
I want to access External web link On my django website,but i dont access it so how to access it on button click action. -
django could not be resolved from source Pylance
I just begun performing crud operations using Django. I have installed Django using pip install django. I then set the environment: venv\Scripts\activate but when i run python3 manage.py makemigrations, i get "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?". Any help kindly -
Why is my django web-app login form not working?
I've tried to add login form to my tasks web-app, but something goes wrong and I can't login to my created admin user. After click on the login button page just clearing up and my url changes to that. I have no idea how to fix it, help me please. urls.py urlpatterns = [ path('', TaskList.as_view(), name='tasks'), path('login/', CustomLoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(next_page='login'), name='logout'), path('task/<int:pk>', TaskDetail.as_view(), name='task'), path('task-create/', TaskCreate.as_view(), name='task-create'), path('task-edit/<int:pk>', TaskUpdate.as_view(), name='task-edit'), path('task-delete/<int:pk>', TaskDelete.as_view(), name='task-delete'), ] views.py class CustomLoginView(LoginView): template_name = 'base/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('tasks') login.html <h1>Login</h1> <form metrhod="POST" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Login"> </form> -
Do I need cstf protection when backend and frontend have different domains?
I have: React app: https://myreact.com Django + DRF: https://mydjango.com React has a form that when submitted sends a POST request to mydjango.com/handle-form with all the cookies, because I speicfy withCredentials: true in my ajax request (thus all the cookies are sent). As I can see it, there's no way to perform csrf attack, because browser stores cookies only for myreact.com. And if an attacker creates a domain myreact2.com with the same exact form (that upon submitting sends POST request to mydjango.com/handle-form), cookies from myreact.com won't be sent, meaning there's no csrf attack. The questions: Am I right? Will browser store cookies only in myreact.com or in both domains, when I make an ajax request from myreact.com to mydjango.com and mydjango.com in response sends a Set-Cookie header? I understand how it would work, when both frontend and backend shared the same domain. CSRF attack could be very possible without csrf token or something else. But my case bothers me. -
Kindly advise me on how to go about this
I have an assignment from a bootcamp to build a price compare website api. As an advanced BACKEND developer, kindly advise me on how to go about it after getting jumia and ebay developer api's. Will I save their data into my database and query from there? If yes, how would their price change reflect in my database? Don't laugh please, I am just a begginer django. -
How do I add another field to my model without getting an error?
I added another field to my Listing() model called highest_bid. However, when I try to look at the listing model in the /admin page I get the OperationalError: no such column: auctions_listing.highest_bid After adding this field I tried using makemigrations, but it said that there were no changes and I also tried using migrate but that also said that there was nothing to migrate. I also tried removing null=True on the field but that did not change anything. How do I add this field without getting an error? models.py: class Listing(models.Model): ... highest_bid = models.FloatField() # highest_bid = models.FloatField(null=True) # they both returned the same error -
MongoDB connection with Django i am getting below error after configuration
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'django' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
django: How do i save form in django without the django forms?
I am trying to save a contact form, but i am not using the django form but instead the input field. I am getting the name, email address and message body from the html templates using input field like this <input type="text" id="name"> but the form doesn't get any data from the input field, it seems i am missing something but i cannot find out what is happening. I have tried passing in the name, email and message into id="name" id="email" id="message" but nothing still happends. This is my code index.html <form method="POST"> {% csrf_token %} <input type="text" id="name" value="" /> <input type="text" id="email" value="" /> <input type="text" id="address" value="" /> <button type="button">Let's Withdraw</button> </form> views.py if request.method == "POST": name = request.POST.get("name") email = request.POST.get("email") message= request.POST.get("message") print("Message Sent") return redirect("core:index") else: pass -
What to learn to make production ready Django apps after Django basics
I have learned Django and Sqlite and I'm pretty comfortable with it but I only know how to make a app run on my machine and nothing about production. I know i need to learn Nginx Guicorn Postgres and hosting but i don't know where to learn. I have watched some tutorials on youtube but that has only consfused me. Can you recommend some tutorials for deployment of Django projects and What other things or practices do i need to learn for making production grade webapps. -
I keep getting <WSGIRequest GET: '/create-link-token'>; trouble connecting django to plaid api
I'm trying to connect my Django backend to Plaid's API but I've been stuck on how to only return the body from the Object. This is the traceback I'm getting: Request Method: GET Request URL: http://127.0.0.1:8000/create-link-token Django Version: 4.0.6 Python Version: 3.9.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Daniel Tshibangu\Desktop\mukadi\plaid-integration\python\backend\app\views.py", line 82, in create_link_token response = client.link_token_create(request) File "C:\Python39\lib\site-packages\plaid\api_client.py", line 769, in __call__ return self.callable(self, *args, **kwargs) File "C:\Python39\lib\site-packages\plaid\api\plaid_api.py", line 7404, in __link_token_create return self.call_with_http_info(**kwargs) File "C:\Python39\lib\site-packages\plaid\api_client.py", line 831, in call_with_http_info return self.api_client.call_api( File "C:\Python39\lib\site-packages\plaid\api_client.py", line 406, in call_api return self.__call_api(resource_path, method, File "C:\Python39\lib\site-packages\plaid\api_client.py", line 193, in __call_api response_data = self.request( File "C:\Python39\lib\site-packages\plaid\api_client.py", line 452, in request return self.rest_client.POST(url, File "C:\Python39\lib\site-packages\plaid\rest.py", line 264, in POST return self.request("POST", url, File "C:\Python39\lib\site-packages\plaid\rest.py", line 150, in request r = self.pool_manager.request( File "C:\Python39\lib\site-packages\urllib3\request.py", line 78, in request return self.request_encode_body( File "C:\Python39\lib\site-packages\urllib3\request.py", line 170, in request_encode_body return self.urlopen(method, url, **extra_kw) File "C:\Python39\lib\site-packages\urllib3\poolmanager.py", line 376, in urlopen response = conn.urlopen(method, u.request_uri, **kw) File "C:\Python39\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen httplib_response …