Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modify Djangos model-table outside Django
I have a model my_users with fields id,fruit, notified, time. The field notified and time are to be updated (preferably) on another machine than my Django App is running, due to it being a hefty computation. I can do it by e.g df = my_heavy_function() df.to_sql(my_app_my_users) but I'm afraid of writing issues/overlap if some user e.g edits his fruits while the to_sql function is writing (the DB is a PostgreSQL). Is it safe to use this approach, or what is the better way to do these kinds of update to Djangos models that is not a view as such but more a backend operation? -
Django runserver_plus restart immediately after running the server
I tried to set up a Django server with a self-signed SSL using the following command: python manage.py runserver_plus --cert /tmp/cert 0.0.0.0:8060 after running the server, it automatically restarts the server and loads all modules again and I can not find the reason. My output is like this: * Running on https://0.0.0.0:8060/ (Press CTRL+C to quit) * Restarting with stat Performing system checks... System check identified no issues (0 silenced). Django version 3.1.4, using settings 'rokhban.settings' Development server is running at https://0.0.0.0:8060/ Using the Werkzeug debugger (http://werkzeug.pocoo.org/) Quit the server with CONTROL-C. * Debugger is active! * Debugger PIN: 233-701-884 PS: No such thing happens when running the server with python manage.py runserver 0.0.0.0:8060 Why does this happen? -
django project sheme in form of tree in git bash
I'm creating my first django app and I want to ask what command in git bash can show structure of my project in form like at the underneath. Thanks for help │ ├───staticfiles └───webadvisorapi │ settings.py │ urls.py │ wsgi.py │ __init__.py │ ├───static │ .keep -
im trying to count model object but its not working
I'm trying to count model object using Django but it's not working, it doesn't display anything, that's the HTML code, I've tried both .all.count and .count but both aren't showing anything <div class="card"> <div> <h3>Followers: {{profiles.follower.all.count}}</h3> </div> <div> <h3>Followings: {{profiles.following.count}}</h3> </div> </div> And that's the python profile function code def profile(request, username): user = get_object_or_404(User, username=username) user_posts= post.objects.filter(user=user) profiles = Userprofile.objects.filter(user=user) context = { 'user_posts':user_posts, 'profiles': profiles } return render(request, "network/profile.html", context) The Model related class Userprofile(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='profile') follower = models.ManyToManyField('User', blank=True, related_name='follower') following = models.ManyToManyField('User', blank=True, related_name='following') -
How to use Django admin to create celery like tasks
I have a Django backend that I've created for a real estate company. I've built quite a few tasks that are hard coded and I'm wanting to make those tasks customizable via the admin page... but I can't quite figure out how to do that. For example, let's say that (from the admin) I wanted to make it possible to create a task that would send a custom message that would trigger based on a list of triggers (e.g. close date, client birth date, etc). Is this doable? This question is a little vague because I can't quite figure out how to ask what I'm wanting to do. I'm sure that there is a keyword(s) that I can type in to point me on the right path, but I have come up blank up to this point -
Django widget tweaks - date field is empty when using generic update view class
I have problem with generic update View - to customization of template i'm using widget tweaks when i'm trying to update date field with bootstrap class='form=control' my date field is empty. Despite in html value is filled correctly. All the time when i'm using update views my date fields becoms empty. <div class='col-6'> {{ form.data_przegladu.label }} {% render_field form.data_przegladu class="form-control" type='date' %} {{ form.tachograf.label }} {% render_field form.tachograf class="form-control" %} {{ form.data_legalizacji.label }} {% render_field form.data_legalizacji class="form-control" type='date' %} {{ form.uwagi.label }} {% render_field form.uwagi class="form-control" %} </div> Printscreen from my browser -
How can I build mobile application for my django app
I m new to Django so if this question sounds stupid pls don't blame me. So have created a web app using Django. It s a blog app that let s you upload your posts and see other posts and you can log in and stuff like that. Now I also want to create a mobile application for that. But as I researched I saw that you must use Django rest framework for that and then get the data from the API. Can I somehow connect/build a mobile app whit my current app that uses Django and displays data with templates? And if so how and with which tools. -
Axios with django server on localhost
Trying to access django server on localhost from my react native app. All I get is Network Error, which doesn't say much. Tried changing info.plist file as suggested in other answers on stack, tried changing firewall settings and so on. -
How to show the number in ManyToManyField appear as number but not ediatbale
How I can show the number of models.ManyToManyField as a number but not editable because when I set editable=False I couldn't see the number of users in the Django model like this viewers = models.ManyToManyField(Account, editable=False) -
Use data in webhook to populate html form input
I have data coming in through a webhook and I would like it to http://localhost:8000/webhooks/stripe and I would like it to fill out a form on my success.html page when redirected after the checkout. I would like to get the customer_email to fill the email input - @csrf_exempt def stripe_webhook(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) if event['type'] == 'checkout.session.completed': session = event['data']['object'] customer_email = session["customer_details"]["email"] document.getElementById("email").value=customer_email return HttpResponse(status=200) With the forms.py looking like this - class UserRegisterForm(UserCreationForm): email = forms.EmailField(widget= forms.EmailInput(attrs={'id':'email'})) class Meta: model = User fields = ['email', 'password1', 'password2'] Or do I have to use a function in the forms.py to extract the data from the webhook? -
How can i make a "Remember me" Checkbox in loginView form in django?
I need to create a checkbox "remember me" with django.contrib.auth.views.loginView. My code is : login.html <div class="d-flex justify-content-between"> <label class="custom-radio" style="margin-top : 15px"> <input type="checkbox" name="remember_me" valeur="true"> <span class="checkmark"></span> {% trans 'Stay connected' %} </label> views.py from django.contrib.auth.views import ( LoginView as LoginViewBase, LogoutView as LogoutViewBase, PasswordResetView as PasswordResetViewBase) class LoginView(OnlyUnauthenticatedUsersMixin, LoginViewBase): template_name = 'accounts/login.html' next_page = 'pages:domains-of-expertise' account_not_active_message = _('Your account has not been activated yet.') def form_valid(self, form): user = form.get_user() if user.has_profile and not user.profile.email_confirmed: messages.error(self.request, self.account_not_active_message) return redirect('pages:home') return super().form_valid(form) def get_success_url(self): url = self.get_redirect_url() return url or resolve_url(self.next_page) urls.py path('login/',views.LoginView.as_view(),name='login'), I have already add this lines into my settings.py : SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_AGE = 5 # 5 seconds for testing SESSION_SAVE_EVERY_REQUEST = True -
Subclass PasswordResetConfirmView returned token becomes "set-password"
I tried to Subclass my PasswordResetConfirmView for me to create an error message if token is invalid. After some trial and errors, this is what I have come up with based on this Github file: class MyPasswordResetConfirmView(PasswordResetConfirmView): @method_decorator(sensitive_post_parameters()) @method_decorator(never_cache) def dispatch(self, *args, **kwargs): # I declared these myself since the variable itself is from other class and they only have these strings as value INTERNAL_RESET_SESSION_TOKEN = '_password_reset_token' reset_url_token = 'set-password' # I declared these myself since the variable itself is from other class and they only have these strings as value assert 'uidb64' in kwargs and 'token' in kwargs self.validlink = False self.user = self.get_user(kwargs['uidb64']) if self.user is not None: token = kwargs['token'] if token == self.reset_url_token: session_token = self.request.session.get(INTERNAL_RESET_SESSION_TOKEN) if self.token_generator.check_token(self.user, session_token): # If the token is valid, display the password reset form. self.validlink = True return super().dispatch(*args, **kwargs) else: if self.token_generator.check_token(self.user, token): # Store the token in the session and redirect to the # password reset form at a URL without the token. That # avoids the possibility of leaking the token in the # HTTP Referer header. self.request.session[INTERNAL_RESET_SESSION_TOKEN] = token redirect_url = self.request.path.replace(token, self.reset_url_token) return HttpResponseRedirect(redirect_url) # Display the "Password reset unsuccessful" page. if self.validlink: return self.render_to_response(self.get_context_data()) … -
How to create model instance from button click?
Need help. Just learning Django, with no experience in JS. How to implement the following feature: in discover_events.html there is an 'Add to calendar' button. I need to add the respective event from the table to the UserCalendar instance. UserCalendar instance is created automatically when the user is created. User is just clicking the button, the event is automatically added to his personal views, like a bookmark, no need to redirect to any other pages and 'Add to calendar' button changes to 'Remove from calendar'. events.models.py class Event(models.Model): user = models.ForeignKey("users.User", on_delete=models.CASCADE,related_name="events") title = models.CharField(max_length=250) slug = models.SlugField(max_length=50,unique=True, editable=False, null=False) users.models.py class UserCalendar(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) events = models.ManyToManyField(Event, blank=True) def __str__(self): return self.user.email def post_save_user_receiver(sender, instance, created,**kwargs): if created: UserCalendar.objects.create(user=instance) post_save.connect(post_save_user_receiver, sender=User) discover_events.html {% for event in event_list%} <tr> <td> <a href="{{ event.get_absolute_url }}"> {{ event.title}}</a></td> <td>{{ event.category}} </td> <td> {% for tag in event.tags.all %} <span class="badge badge-pill badge-secondary">{{tag.tag}}</span> {% endfor %} </td> <td>{{ event.organizer}}</td> <td>{{ event.event_date_start|date:"SHORT_DATE_FORMAT" }}</td> <td>{{ event.event_date_finish|date:"SHORT_DATE_FORMAT"}}</td> <td> {% if event.event_format == "live" %} <i class="fas fa-users"></i><span class="badge badge-pill badge-default"> {{event.event_format}}</span> {% elif event.event_format == "online" %} <i class="fas fa-wifi"></i><span class="badge badge-pill badge-primary"> {{event.event_format }}</span> {% endif %} </td> <td>{{ event.main_language}}</td> <td> <form id="form_id" … -
no such table: accounts_demandplan
In my Django project, 'MyAPP' I had a model as accounts_demandplan which I have unfortunately deleted from my Jupyter notebook by connecting to my sqlite3.db. Following is the SQL code I executed. import sqlite3 import pandas as pd conn = sqlite3.connect("C:/Users\Parijat\Desktop\Theis project\CRM\db.sqlite3") cur = conn.cursor() cur.execute(" DROP TABLE accounts_demandplan") I know that I did not do the migrations properly and it is now showing the following error OperationalError: no such table: accounts_demandplan Can anyone help how can I resolve the problem so that the deleted model "account_demandplan" can be reflected in my migrations file? -
Can Any One Tell Me Which thing make PostgreSQL the most secure DB?
I searched best DB in the world. I found PostgreSQL for the best DB. Tell me the reason why PostgreSQL is most used and secure database. -
how can i make a mount of balance to counts according to a specific days in Django
so, I made a Django code for booking car online services , renter can rent a car by pressing on a booking button that moves him to form page to enter his his information and chooses a starting and end date, so once he submits, the balance from his account to the owner's account will be transfers according to a specific mount that depends on the number days he picked ,, but the problem is -> the mount is not linked to the date fields so weather he chooses the date or not the mount will still be the same here's the view that handles the transaction... def transfer_rent(renter, owner, amount,start_date,end_date): if (renter.balance < amount): return False else: renter.balance -= amount owner.balance += amount renter.save() owner.save() return True def booking(request,pk): form = bookingCreateForm(request.POST or None) user = request.user if form.is_valid(): rent = Rent.objects.get(pk=pk) car_owner = rent.owner if transfer_rent(user, car_owner, rent.per_day): form.save() messages.success(request,'Successfully Saved') return redirect('/list_history') else: messages.error(request, 'Insufficient balance') return redirect('/list_history') context = { "form": form, "title": "Enter Your Credintials", } return render(request, "booking.html",context) -
Session is not updated after ajax call in django
I'm struggling with session update handle after ajax call in django. I used database session backend engine. but session is not updated database. I consider django_session table, but new session wes not inserted after ajax call. This is my code. View.py def contact(request): contract = request.GET.get('contract ', 1) contract _session = request.session.get('contract ',False) if(not contract_session): request.session['contract '] = Contrato.objects.first().pk request.session.modified = True if Contract.objects.filter(id=contract).exists() and contract != request.session['contract ']: del request.session['contract '] contract = Contract.objects.get(id=contract) request.session.set_expiry(180000) request.session['contract '] = contract .id request.session.modified = True request.session.save() return HttpResponse('ok') settings.py SESSION_COOKIE_AGE=3600, # on hour in seconds INSTALLED_APPS=[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_jwt', 'django_rest_passwordreset', 'django_filters', 'django_countries', 'corsheaders', 'rest_auth', 'pwa', ], MIDDLEWARE=[ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'beecoss_api.middleware.LoginRequiredMiddleware', ], SESSION_ENGINE = "django.contrib.sessions.backends.db", SESSION_SAVE_EVERY_REQUEST = True, template.html var contract= $ ('#contract') .val (); var url = "{% url 'url'%}"; $ .ajax ({ type: "GET", url: url, data: {'contract':contract}, success: function () {} }); Also I was running server localhost:8000 and 127.0.0.1:8000 -
Show message in Django without needing a request
I have a view which uses threading e.g from .utils import my_heavy_function def my_view(request): if request.method == "POST": form = my_model_form() if form.is_valid(): #create thread thr = threading.Thread(target=my_heavy_function,args=(form,)) thr.start() messages.success(request, "Processing ...") return redirect("my_template") else: form = my_model_form() return render(request, "my_app/my_template.html") and it works like a charm; it process the my_heavy_function in the background while making the user able to continue using the webpage. I just need a way to show a message when my_heavy_function is done. Is there a way to make Django display a message even when a new-request is not called but based on some other condition? E.g on a page when a file is done loading etc. (I have on purposed not used Django-Q, Celery or back-ground-tasks for this threading since I find it being overkill) -
Multiple applications inside a Django project
I am creating a ERP web application using Django. How can i connect multiple apps inside of a project with one database. I am using PostgreSQL database and also how can i centralized the database for all modules of ERP -
Testing delete_selected action in Django Admin with pytest
I'm using Django 3.2b1 and pytest 6.2.2. I'm trying to use pytest to write a test to make sure admins are able to delete objects using the delete_selected action. My test looks like this: def test_delete_mymodel_action(admin_client): objs_to_delete = [ MyModel.objects.create(), MyModel.objects.create(), ] MyModel.objects.create() # Don't delete this obj data = { "action": "delete_selected", "_selected_action": [str(f.pk) for f in objs_to_delete], "post": "yes", # Skip the confirmation page } change_url = reverse("admin:myapp_mymodel_changelist") admin_client.post(change_url, data) assert MyModel.objects.count() == 1 The code works and ends in a 302 redirect back to the changelist, but the objects don't get deleted. The response is: test_delete_mymodel_action - assert 3 == 1 The reason I'm testing this is that certain code can cause the delete_selected action to fail. For example, if you override get_queryset() in the ModelAdmin and return a queryset that uses distinct(), the delete_selected action will fail. Here the code from a delete confirmation page in Django Admin: <form method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="VCR7vjVYcb2xuMdPUknotrealViwj92wgZrT21k6RbqGxXNlQnCORU1Fp6NzKhn64"> <div> <input type="hidden" name="_selected_action" value="31418"> <input type="hidden" name="_selected_action" value="31412"> <input type="hidden" name="action" value="delete_selected"> <input type="hidden" name="post" value="yes"> <input type="submit" value="Yes, I’m sure"> <a href="#" class="button cancel-link">No, take me back</a> </div> </form> Some helpful references: Django's delete_selected() method. Testing custom admin actions in … -
In Django In that project i want to create or register a client and display with created by as a login users
class Project(models.Model): project_name = models.CharField(max_length=155) users = models.ForeignKey('auth.user', related_name='projects', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) # created_by = models.ForeignKey('auth.user', related_name='projects', on_delete=models.CASCADE) def __str__(self): return self.project_name class Client(models.Model): client_name = models.CharField(max_length=155, null=True) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey('auth.User', on_delete=models.CASCADE, auto_created='auth.User') updated_at = models.DateTimeField(auto_now=True, null=True) # projects = models.ForeignKey(Project, related_name='clients', on_delete=models.CASCADE) def __str__(self): return self.client_name And when i add the client at server the Error is show: IntegrityError at /clients/ NOT NULL constraint failed: MyApp_client.created_by_id -
Django 3.1 Oath Authentication for Django and Django REST API on AWS
I am just about to start looking into Oath using Django and I am worried that there is a significant risk that I will follow a tutorial that is out of date or that doesn't work with both standard Django and Django REST Framework (I currently use django a lot, but I would like to get much better at REST later on). Can anybody recommend either the most appropriate framework or tutorial for a novice at oath, who currently uses Django 3.1.7. I am currently using AWS if that makes a significant impact on the choice. Thanks Mark -
Django Autoplay video while scrolling is not working
I am Building a BlogApp and I am stucked on a Problem. I am building Autoplay video while scrolling and Pause when the video is out of the screen after scroll. The Problem It is showing nothing when i refresh the page. Not even after scroll. What have i tried I copy loop this code in videos.html for testing the scrolling feature. But was not working I tried this to autoplay video while scrolling but it didn't work for me. <script> $(function(){ $(window).scroll(function(e) { var scrollAmount = $('body').scrollTop(); console.log(scrollAmount); if(scrollAmount >="10" && scrollAmount <= "10") { $("#videoHolder").html( '<video width="400" autoplay>' + ' <source src="{{ video.video.url }}" type="video/mp4">' + '</video>'); </script> videos.html {% for video in show_videos %} <script> $(function(){ $(window).scroll(function(e) { var scrollAmount = $('body').scrollTop(); console.log(scrollAmount); if(scrollAmount >="10" && scrollAmount <= "10") { $("#videoHolder").html( '<video width="400" autoplay>' + ' <source src="{{ video.video.url }}" type="video/mp4">' + '</video>'); </script> {% endfor %} I don't know why this video is not playing. or scroll playing. Any help would be Appreciated. Thank You in Advance. -
access django fk related objects in view as template
I have a models as class Doctor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, related_name="user") # other fields... In my template, I easily can access the doctor object as request.user.doctor but using it in my views it causes the 'User' object has no attribute 'doctor' Error. so is it possible to access it as templates in my views too. -
Manager isn't accessible via Contact instances when refer to same model in a method
I am getting the error Manager isn't accessible via Contact instances StackTrace Environment: Request Method: POST Request URL: http://localhost:8000/upload/ Django Version: 3.1.7 Python Version: 3.9.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'contactapp'] 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 "/Users/Me/.local/share/virtualenvs/test_code-Xw7ix4y5/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/Me/.local/share/virtualenvs/test_code-Xw7ix4y5/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Me/Data/Clients/BanzaiPythonTest/test_code/contactapp/views.py", line 39, in upload_file print(result.get()) File "/Users/Me/.local/share/virtualenvs/test_code-Xw7ix4y5/lib/python3.9/site-packages/celery/result.py", line 223, in get return self.backend.wait_for_pending( File "/Users/Me/.local/share/virtualenvs/test_code-Xw7ix4y5/lib/python3.9/site-packages/celery/backends/asynchronous.py", line 201, in wait_for_pending return result.maybe_throw(callback=callback, propagate=propagate) File "/Users/Me/.local/share/virtualenvs/test_code-Xw7ix4y5/lib/python3.9/site-packages/celery/result.py", line 335, in maybe_throw self.throw(value, self._to_remote_traceback(tb)) File "/Users/Me/.local/share/virtualenvs/test_code-Xw7ix4y5/lib/python3.9/site-packages/celery/result.py", line 328, in throw self.on_ready.throw(*args, **kwargs) File "/Users/Me/.local/share/virtualenvs/test_code-Xw7ix4y5/lib/python3.9/site-packages/vine/promises.py", line 234, in throw reraise(type(exc), exc, tb) File "/Users/Me/.local/share/virtualenvs/test_code-Xw7ix4y5/lib/python3.9/site-packages/vine/utils.py", line 30, in reraise raise value Exception Type: AttributeError at /upload/ Exception Value: Manager isn't accessible via Contact instances I am making a utility function and below is my code: class Contact(models.Model): name = models.CharField(max_length=100) phone = models.CharField(max_length=20, null=True) email = models.CharField(max_length=256, null=True) # Ref: https://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690 created_at = models.DateTimeField(auto_now_add=True) def __repr__(self): return self.name def get_records_by_duration(self, duration=3): minutes_ago = now() + datetime.timedelta(minutes=-duration) contact_object = Contact.objects.filter( (Q(email__in=['adn@mae.com', 'adnan@gmail.com']) | Q(phone__in=[])), Q(created_at__gte=minutes_ago)) total = contact_object.count() print('Total = {}'.format(total)) In my view I am doing …