Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Processing a json HttpResponse using Ajax
I have sent a HttpResponse from views.py to an HTML page. However, while loading the directed page it only shows the JSON object and not the actual HTML page with the details. This is how the page looks after the request is completed These are my expectations for how the data should be displayed views.py def tracker(request): if request.method == "POST": oid = request.POST.get('oid', '') email = request.POST.get('email', '') try: order = Orders.objects.filter(order_id = oid, email = email) if len(order)>0: update = OrderUpdate.objects.filter(order_id = oid) updates = [] for item in update: updates.append({'text': item.update_desc, 'time':item.timestamp}) response = json.dumps(updates, default = str) return HttpResponse(response) else: return HttpResponse({}) except Exception as e: return HttpResponse({}) return render(request, 'shop/tracker.html') tracker.html {% include 'shop/basic.html' %} {% block body %} <div class="container"> <div class="col my-4"> <h2>My Awesome Cart Tracker - Enter yuor Order ID and Email address to track your order</h2> <form method="POST" action="#" id="trackerForm"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-6"> <label for="Oid">Order Id</label> <input type="text" class="form-control" id="oid" name="oid" required=""> </div> <div class="form-group col-md-6"> <label for="inputEmail4">Email</label> <input type="email" class="form-control" id="inputEmail" name="email" required=""> </div> </div> <button type="submit" class="btn btn-primary">Track Order</button> </form> </div> <div class="col my-4"> <h2>Your Order Status</h2> <div id="items" class="my-4"> <ul class="list-group my-4" id="items"> … -
Css and javascript not loading in my website
I have downloaded bootstrap template.When i put its code in html file and load my website,the html content is shown but css and javascript is not shown and many errors come when I inspect element.Kindly tell me the solution. enter image description here -
Run bash script from pydroid inbuilt terminal
chd.sh #! /bin/bash cd django/hellodjango exec bash python manage.py runserver chd.py # a=`python chd.py`;cd $a import os new_dir = "django/hellodjango" os.chdir(new_dir) are the two ways I have tried. Also, on terminal I have tried, . chd.sh ./chd.sh . ./chd.sh I have also tried to assign to variable and then run on terminal but no success. Spent over 4 hours trying multiple methods given on stackoverflow.com but no success yet. The only thing that has worked yet is, alias mycd='cd django/hellodjango' But I will have to copy paste it everytime. alias myrun = `cd django/hellodjango && python manage.py runserver` And, alias myrun = `cd django/hellodjango; python manage.py runserver` doesn't work. This is just a sample, there are so many django commands that I have to use repeatedly. Appreciate if you have read all this way. If you know the link where this is discussed, please attach the link, as I was not able to find after hours of search. -
How to get `max_length` in CharField's description in Django?
I am trying to get affordances of all the fields of a model. For which, I first fetch all the fields using ._meta_get_fields() which returned an ImmutableList of fields, and then for each field, I used its .description attribute. For different fields it returned, BooleanField : "Boolean (Either True or False)" IntegerField : "Integer" DateTimeField : "Date (with time)" CharField : "String (up to %(max_length)s)" As you can see in the case of CharField, even though max_length is defined, Django isn't resolving that variable in CharField's description itself. -
maximum recursion depth exceeded while calling a Python object in django
I was trying to saving comments to a post detail page, but now I am getting this Error: maximum recursion depth exceeded while calling a Python object here is my view.py class PostDetail(LoginRequiredMixin,ModelFormMixin,generic.DetailView): model = PostModel template_name = 'post_detail.html' form_class=CommentForm def get_success_url(self): return reverse('post_detail',kwargs={'slug':self.object.slug}) def get_context_data(self, **kwargs): context = super(PostDetail,self).get_context_data(**kwargs) context ['commentmodel_list'] = CommentModel.objects.filter(post=self.object).order_by('-created_on') return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.instance.author = self.request.user form.instance.post = self.object return super(PostDetail,self).form_valid(form) -
WebAgent with React
I am building a web agent in React. I have set up url's (www.mysite.com/webagent?emailid=4) that will send the corresponding email from the server (using a python script -- django email). window.location.href = 'webagent?emailid=' + emailid; However, I don't really want this page to open (basically just a refresh since it isn't changing any of the content) and want it to just be selected behind the scenes. Is this something that is possible? Any suggestions for how to restructure this to be more efficient? (Part of the original reasoning for doing this is that then I can have a script that calls specific urls on a time schedule) -
Getting this error: ProgrammingError at /admin/ relation "myapp_myuser" does not exist while creating superuser or going on localhost/admin
I tried extending the user model in django with the help of django docs.I wanted to add a mobile field to it.I did everything and then even executed makemigrations , sqlmigrate and migrate and got no error but when i try to execute python manage.py createsuperuser i get a response asking for email and as soon as it enter email i get this error I havent made a separate app for this model and am using the same models.py for the whole project The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\contrib\admin\sites.py", line 249, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\contrib\admin\sites.py", line 220, in inner if not self.has_permission(request): File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\contrib\admin\sites.py", line 194, in has_permission return request.user.is_active and request.user.is_staff File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\utils\functional.py", line 224, in inner self._setup() File "C:\Users\LENOVO\Envs\ myapp\lib\site-packages\django\utils\functional.py", line … -
How to implement google and facebook oauth2 in django rest framework?
I am a nodejs developer but currently migrating to django(being a python lover). I am trying to implement OAuth2 in Django Rest Framework but I don't know how to start. In nodejs, there is passportjs library which is well maintained, and it's got stratigies for every possible authentication type. What about django rest framework ? User name/password auth seems straightforward but oauth2 is not well covered. In DRF docs here, It mentions two libraries for oauth. The first is django-oauth-toolkit which is well maintained but after going through docs, I didn't seem to understand much, it doesn't even talk about googl/facebook oauth. I am not sure what it is used for, anyway. The second one is django-rest-framework-social-oauth2 which seems to be straightforward but it's not been touched for over a year, it's probably not maintained any more. So, How do you guys do oauth2 in your DRF projects ? -
`delete()` after `difference()` in Django ORM
Question is regarding delete() after difference() in Django ORM. My goal here is to delete old model instances when amount of record in db greater then certain number. class StatusLog(models.Model): logger_name = models.CharField(max_length=100) level = models.PositiveSmallIntegerField(choices=LOG_LEVELS, default=logging.ERROR, db_index=True) msg = models.TextField() trace = models.TextField(blank=True, null=True) create_datetime = models.DateTimeField(auto_now_add=True, verbose_name='Created at') Plan: construct queryset with all entries. construct queryset with entries to keep. calculate difference delete rest. Reality: a = StatusLog.objects.all().order_by('pk') a.count() = 93 # as planed b = StatusLog.objects.all().order_by('pk')[:50] b.count() = 50 # as planed c = a.difference(b) c.count() = 43 # as planed c.update(trace='test') # returns 93. Updated whole table. # WTF?????? Should be 43 Is it a bug or I don’t understand something? -
using different fields in foreignkey django
i have to use different fields for as ForeignKey not only str method field !? i tried this but seems doesnt work , and only return str method fields data class ModelA(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) invoice_id = models.IntegerField(unique=True) def __str__(self): return self.product.name class ModelB(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) invoice = models.ForeignKey(Model1,to_field='invoice_id',on_delete=models.CASCADE) i need to show in ModelB invoice field all invoice_id , but it display products ? thanks for helping -
Problems with form_valid in django
I am using a CBV in Django with Detail View and FormMixin also the function form_valid to list posts and create comments. But I get the error in the picture when I am trying to create the comments. I also want that the user can create comments only under his name but when I am trying to create comments I get a list of all authors which I can choose. Here is my view class PostDetail(FormMixin,generic.DetailView): model = PostModel template_name = 'post_detail.html' form_class=CommentForm fields=['comment'] def get_success_url(self): return reverse('post_detail',kwargs={'slug':self.object.slug}) def get_context_data(self, **kwargs): context = super(PostDetail,self).get_context_data(**kwargs) context ['commentmodel_list'] = CommentModel.objects.filter(post=self.object).order_by('-created_on') return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user self.object.post=self.model.post self.object.save() return super(PostDetail,self).form_valid(form) -
Port could not be cast to integer value as 'string' when using Celery with Redis
I had Port could not be cast to integer value as '<somerandomstring>' error showing up in celery error logs. I followed this answer and fixed the issue with celery workers. CELERY_BROKER_URL = 'redis://:{}@localhost:6379'.format(urllib.parse.quote(config.REDIS_PASSWORD, safe='')) CELERY_RESULT_BACKEND = 'redis://:{}@localhost:6379'.format(urllib.parse.quote(config.REDIS_PASSWORD, safe='')) Problem: celery service is working fine now, but the same error appears for celerybeat now and I am unable to fix it as I do not know where the issue is or what to configure other than BROKER_URL and RESULT_BACKEND. Can someone help me find the problem? Traceback for celerybeat from beat.log: Traceback (most recent call last): File "/myproject/venv/lib/python3.8/site-packages/celery/apps/beat.py", line 109, in start_scheduler service.start() File "/myproject/venv/lib/python3.8/site-packages/celery/beat.py", line 622, in start humanize_seconds(self.scheduler.max_interval)) File "/myproject/venv/lib/python3.8/site-packages/kombu/utils/objects.py", line 44, in __get__ value = obj.__dict__[self.__name__] = self.__get(obj) File "/myproject/venv/lib/python3.8/site-packages/celery/beat.py", line 666, in scheduler return self.get_scheduler() File "/myproject/venv/lib/python3.8/site-packages/celery/beat.py", line 657, in get_scheduler return symbol_by_name(self.scheduler_cls, aliases=aliases)( File "/myproject/venv/lib/python3.8/site-packages/celery/beat.py", line 501, in __init__ Scheduler.__init__(self, *args, **kwargs) File "/myproject/venv/lib/python3.8/site-packages/celery/beat.py", line 257, in __init__ self.setup_schedule() File "/myproject/venv/lib/python3.8/site-packages/celery/beat.py", line 545, in setup_schedule self.install_default_entries(self.schedule) File "/myproject/venv/lib/python3.8/site-packages/celery/beat.py", line 262, in install_default_entries not self.app.backend.supports_autoexpire: File "/myproject/venv/lib/python3.8/site-packages/kombu/utils/objects.py", line 44, in __get__ value = obj.__dict__[self.__name__] = self.__get(obj) File "/myproject/venv/lib/python3.8/site-packages/celery/app/base.py", line 1232, in backend return self._get_backend() File "/myproject/venv/lib/python3.8/site-packages/celery/app/base.py", line 950, in _get_backend return backend(app=self, url=url) File "/myproject/venv/lib/python3.8/site-packages/celery/backends/redis.py", line 252, … -
Certain python libraries are not loading in my Django application in production, but load fine in local server
In my views.py file of my Django application I'm trying to load the 'transformers' library with the following command: from transformers import pipeline This works in my local environment, but on my Linux server at Linode, when I try to load my website, the page tries to load for 5 minutes then I get a Timeout error. I don't understand what is going on, I know I have installed the library correctly. I have also run the same code in the python shell on my server and it loads fine, it's is just that if I load it in my Django views.py file, no page of my website loads. My server: Ubuntu 18.04 LTS, Nanode 1GB: 1 CPU, 25GB Storage, 1GB RAM Library: transformers==3.0.2 I also have the same problem when I try to load tensorflow. All the other libraries are loading fine, like pytorch and pandas etc. I've been trying to solve this problem since more than a week, I've also changed hosts from GCP to Linode, but it's still the same. -
SystemCheckError in my Django website, why do these middleware errors appear?
So I was trying to run a web page in Django and I got these errors while django was checking everything: SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. I looked in the Settings file and everything seems correct, those packages that django says are missing are in the MIDDLEWARE section. MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Does anyone know why this appears. Help is much appreciated -
Pythonanywhere don`t see a db dajngo
I added virtualenv, pulled a project, created db(sqlite) from migrations. When i try to get info with postman I get a OperationalError at /auth/login no such table: client_api_profile. In bash I see, that this table exists, what i did wrong? -
How to draw class diagram and sequence diagram for front-end back-end systems?
I'm going to design a web-based ticket reservation system. It has two parts: 1) back-end which is written with django 2) front-end which is written with vue for web-browsers and with kotlin for mobile applications. I think Class Diagram is required only for django. But how to draw sequence diagrams for collaborations between front and end? What are other differences between class and sequence diagrams of such systems with stand-alone object oriented systems (e.g., written only in Java) It would be appreciated if you introduce complete learning resources for this issue. Thank you -
Django Debug Toolbar Does not Show up When Using POST Method in Django Rest Framework
I have django-debug-toolbar set and ready. It shows up on GET requests perfectly fine. But using POST method the toolbar does not show up. What am I getting wrong here? This is my view: class TestView(APIView) def post(self, request): # some operation using serializers result = ['success': [], 'failed': []] return Response(result) I tried setting content_type='text/html' as suggested by the docs. Didn't work. -
Connecting to mongo cloud using mongoengine
I have written a web app in django using mongoengine as a driver and am trying to host my database on mongodb cloud. In mongoengine's connect() method, according to what I understood from the documentation, specifying the url (specified in the connect section on the mongo cloud site) in the hostname argument should do the trick, however requests from the app to the mongo cloud keep timing out. Where am I going wrong? This is the call to the connect method in my setting.py file- mongoengine.connect(db='scheduler', host='mongodb+srv://<user>:<password>@cluster0.oualt.mongodb.net/<db name>?retryWrites=true&w=majority') -
Dashboard - Django admin
Bonjour à tous, J'ai réalisé un modèle "Commande" que j'administre depuis l'interface admin de Django. Je souhaiterais enrichir cette interface admin en ajoutant un format monétaire (€) à mon champ "Montant" et que la somme, le total de toutes mes commandes s'affichent en bas du tableau dans une ligne "Total" dédiée. from django.db import models class Commande(models.Model): Numero_commande = models.CharField(max_length=100, help_text='Numéro de commande', null=True) Objet = models.CharField(max_length=200, help_text='Objet de la commande') Enseigne = models.CharField(max_length=100, help_text='Nom du magasin/site internet', null=True) Date_commande = models.DateField(null=True, blank=True) Date_livraison = models.DateField(null=True, blank=True) Montant = models.CharField(max_length=200, help_text='Montant de la commande') def __str__(self): return self.numero_commande def get_absolute_url(self): """Cette fonction est requise pas Django, lorsque vous souhaitez détailler le contenu d'un objet.""" return reverse('commande-detail', args=[str(self.id)]) Exemple de dashborad que j'aimerais pouvoir reproduire -
How to save map drawing from javascript to django-sqlite database
I read this solution to draw a polygon but can´t figure out how to save this data in my database How to save map drawing state (Polygon, Polyline, Markers) the 2nd answer. I need to draw a polygon and make some math from it, like area. and when the user is login I want to show it. THANKS in advance....! -
How to pass my template into Django Userena signin/signup views
I'm using django-userena-ce in my project. After configuring settings.py, i run my app and tried to sign up, but it calls its own template with form. How can i pass my own html template? I tried this code: urlpatterns = [ path('signup/', 'userena.views.signup', {'template_name': 'userena/register.html'}, name="signup"), ] but it doesn't help. What i'm doing wrong? -
How to display images using jquery in django
I want to get the absolute url of the image in media folder which is not in Model or database using django view and display it to the page using Jquery. How can i do it guy? -
How can I make hex link in python django?
In my models file I have class called Question and for link to the current Question I'm using path('<int:pk>/', views.QuestionCurrent). And i want to make links to be hex not int. Can I do that and if I can, how? -
Sending default value by POST request <form></form>.Django, HTML
i want to send on post request default value index.html <form action="{% url 'home' %}" method="post"> {% csrf_token %} <div class="form-row"> <div class="col-12 col-md-9 mb-2 mb-md-1"> <input type="text" class="form-control form-control-lg" placeholder="Имя" name="first_name"> </div> <div class="col-12 col-md-9 mb-2 mb-md-1"> <input type="text" class="form-control form-control-lg" placeholder="Фамилия" name="last_name"> </div> <div class="col-12 col-md-9 mb-2 mb-md-1"> <input type="text" class="form-control form-control-lg" placeholder="Номер телефона" name="phone_number"> </div> <div class="col-12 col-md-9 mb-2 mb-md-1"> <input type="email" class="form-control form-control-lg" placeholder="Электронная почта" name="email"> <input name="P"> </div> <div class="col-12 col-md-9 mb-2 mb-md-1"> <button type="submit" class="btn btn-block btn-lg btn-primary">Зарегистрироваться!</button> </div> </div> </form> this is my Views.py def index(request): if request.method == 'POST': first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') phone_number = request.POST.get('phone_number') email = request.POST.get('email') status = request.POST.get('P') print(first_name,last_name,phone_number,email,status) s=UserReg(first_name=first_name,last_name=last_name,phone_number=phone_number,email=email) s.save() return render(request, 'index.html') This is what command print(request) shows: [24/Jul/2020 16:01:15] "GET / HTTP/1.1" 200 8089 sasha weltay +1111111 azw@ksdpi.ru None I just wanna send value"P" by the to my views.py -
Django, how to handle password reset email exceptions?
I am using default Django auth_views + Gmail for password reset. Things works fine for me. During production if there is error happen with accessing email server ,users get response as internal server error 500. Because Gmail prevent user access. Instead of internal server error, How can we let users know that the server can't reach email server ? accounts/login/ [name='login'] accounts/logout/ [name='logout'] accounts/password_change/ [name='password_change'] accounts/password_change/done/ [name='password_change_done'] accounts/password_reset/ [name='password_reset'] accounts/password_reset/done/ [name='password_reset_done'] accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm'] accounts/reset/done/ [name='password_reset_complete']