Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Custom handler500 not working despite following docs
I followed the docs step-by-step and searched for a solution everywhere but my custom handler500 won't work. I use Django 2.2 with Python 3.8. Here's my urls.py: urlpatterns = [ # some urls ] handler500 = "path.to.my.handler" my handler: def handler500(request, exception=None, *_, **_k): print("yeah I got called") return render(request, "my_template.html", { "exception": exception }) my view: def example_view(request): # I tried all of these return HttpResponseServerError() return HttpResponse(status=500) raise Exception("There was an error") # This just shows: "A server error occurred. Please contact the administrator." in the browser. raise HttpResponseServerError() # This shows the same message as above. a_typo # This typo also shows the same message as above. Why doesn't ANY of these errors show my template? The handler didn't get executed at any time. The print() function never got called. -
Python: Selenium no such element: Unable to locate element: {"method":"xpath","selector":"//button[@data-id=1]"}
Why I got this error no such element: Unable to locate element: {"method":"xpath","selector":"//button[@data-id=1]"} test.py zone = Zone.objects.last() self.browser.refresh() time.sleep(2) self.browser.find_element_by_xpath("//button[@data-id="+str(zone.id)+"]").click() # zone.id = 1 I have also tried with self.browser.find_element_by_id('update_id_'+str(zone.id)) but not working :( what's wrong going on ? html <button type="button" id="updateButton update_id_2" class="btn btn-xs btn-primary updateButton" data-id="2"> <i class="fa fa-edit"></i> </button> -
Complex Database Query in Django Graph-Structure
I have a django-project with the following model structure. At first I have a graph-structure with nodes and (directed and weighted) edges in the following way: class Node(models.Model): name = models.TextField() class Edge(models.Model): from_node = models.ForeignKey(Node, on_delete=models.DO_NOTHING, related_name='edge_from_node') to_node = models.ForeignKey(Node, on_delete=models.DO_NOTHING, related_name='edge_to_node') costs = models.IntegerField() There also do exists token, whereby a node can be related to multiple tokens but a token can only be related to one node: class Token(models.Model): node = models.ForeignKey(Node, on_delete=models.DO_NOTHING) Additional I have a User object that can own multiple tokens: class MyUser(models.Model): tokens = models.ManyToManyField(Token) I now want to make a database query that for a given TargetNode and MyUser gives the edge with the minimal costs connecting any node, for which MyUser owns a token, with the TargetNode. Let me make a simple example: # we create 4 nodes ... n1 = Node(name="node 1") n2 = Node(name="node 2") n3 = Node(name="node 3") n4 = Node(name="node 4") n1.save() n2.save() n3.save() n4.save() # -.. and create 3 edges e1 = Edge(from_node=n2, to_node=n1, costs=3) e2 = Edge(from_node=n3, to_node=n1, costs=2) e3 = Edge(from_node=n4, to_node=n1, costs=1) e1.save() e2.save() e3.save() # create a user user = MyUser() user.save() # create 2 tokens for the given user to node2 … -
Django error: Instance of 'OneToOneField' has no 'username' member pylint(no-member)
I'm new to Django and I'm learning it throw a youtube tutorial. I'm trying to build a simple Blog but I have some problem that I think could be related to python or django version. I'm using python3.7.5 and django2.1.5. I've created the following model which represent the user's profile which overrides the save method to enable a resize of the uploaded profile picture. from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) From this I get a few errors, for example in str method from this line: return f'{self.user.username} Profile' I get this error: Instance of 'OneToOneField' has no 'username' memberpylint(no-member) And I get similar error every time I use the self. Can anyone help me? -
"TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType" when installing Django via pipenv on Windows 10:
I am trying to install Django on my Windows 10 System. Python 3.7.7 and pipenv 2018.11.26 are propoerly installed. When I try to run pipenv install django==2.2.5 i get the following error message, for which I just can't figure out the reason: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2032.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2032.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts\pipenv.exe\__main__.py", line 9, in <module> File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 764, in __call__ return self.main(*args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 717, in main rv = self.invoke(ctx) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 956, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\decorators.py", line 64, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\cli\command.py", line 254, in install editable_packages=state.installstate.editables, File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\core.py", line 1927, in do_install pypi_mirror=pypi_mirror, File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\core.py", line 1386, in pip_install pip_command = [which_pip(allow_global=allow_global), "install"] File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\core.py", line 1459, in which_pip return which("pip") File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\core.py", line 117, in which if not os.path.exists(p): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2032.0_x64__qbz5n2kfra8p0\lib\genericpath.py", line 19, in exists os.stat(path) TypeError: stat: path should be string, … -
How can i get image from Profile model into my Post model
There are two model profile and post..i want to get image from profile model..into my post model..how can I get? -
How to install nginx on hosting django
I have nginx code.conf want to show statics, to position it on the hosting(jino) and what actions to make at the command line(via ssh)? Everywhere write about using uwsgi but I don't have it and the site loaded all the same url, but without the statics don't know if it is pre-installed on your hosting Since location is not my project as I don't know any way to register nginx.conf upstream caparol_center_spb_decision { server unix:///tmp/educa.sock; } server { listen 80; server_name www.caparolcenterspb.ru caparolcenterspb.ru; location / { include /etc/nginx/uwsgi_params; uwsgi_pass educa; } location /static/ { alias /home/projects/educa/static/; } location /media/ { alias /home/projects/educa/media/; } } -
No reverse match in Django when passing in a query argument
I am trying to pass a query argument into a Django view through the URL, like so: 127.0.0.1:8000/vysledky/?a_id=1 However, whenever I try to go to that URL, it gives me a NoReverseMatch error. The full error report is listed below: Request Method: GET Request URL: http://127.0.0.1:8000/vysledky/?a_id=1 Django Version: 3.0.5 Python Version: 3.8.0 Installed Applications: ['analysis.apps.AnalysisConfig', 'users.apps.UsersConfig', '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'] Template error: In template /Users/vojtamazur/Documents/CS_IA/mysite/analysis/templates/analysis/base.html, error at line 0 Reverse for '' not found. '' is not a valid view function or pattern name. 1 : <!DOCTYPE html> 2 : <html> 3 : <head> 4 : {% if title %} 5 : <title> Analýza - {{ title }} </title> 6 : {% else %} 7 : <title> Analýza </title> 8 : {% endif %} 9 : </head> 10 : <body> Traceback (most recent call last): File "/Users/vojtamazur/Documents/CS_IA/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/vojtamazur/Documents/CS_IA/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/vojtamazur/Documents/CS_IA/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/vojtamazur/Documents/CS_IA/env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/vojtamazur/Documents/CS_IA/env/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/vojtamazur/Documents/CS_IA/env/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in … -
How do I automatically inherit a foreignkey model's field in django rest?
Models.py, From django admin what I do is I can add a product to Featured but the problem is when I select a product in admin to make featured I want to automatically inherit that product's image url which was uploaded when that product was created. class Product(models.Model): seller = models.ForeignKey(Seller, on_delete=models.CASCADE) title = models.CharField(max_length=120, primary_key=True) image = models.FileField() def __str__(self): return self.title class FeaturedProduct(models.Model): db_identification = models.CharField(max_length=120) featured = models.ForeignKey(Product, on_delete=models.CASCADE) photograph = How do I inherit it automatically from foreignkey product selected? timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.db_identification -
How can i connect a Javascript client to a Python-SocketIO server?
I'm just getting started to Python-SocketIO, i created an example server, it looks like this: import eventlet import socketio sio = socketio.Server() app = socketio.WSGIApp(sio, static_files={ '/': {'content_type': 'text/html', 'filename': 'index.html'} }) @sio.on('connect') def connect(sid, environ): print('connect ', sid) @sio.on('msg') def message(sid, data): print('message ', data) @sio.on('disconnect') def disconnect(sid): print('disconnect ', sid) if __name__ == '__main__': eventlet.wsgi.server(eventlet.listen(('', 5000)), app) Then, i have an HTML file which is running on a Django application, i would like to connect that client to my Python-SocketIO server: <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script> <script> socket = io.connect(''); socket.on('connect',function() { console.log('Client has connected to the server!'); }); socket.on('msg',function(data) { console.log('Received a message from the server!',data); }); socket.on('disconnect',function() { console.log('The client has disconnected!'); }); // Sends a message to the server via sockets function send(message) { socket.send('msg',message); }; </script> The problem is that, on my client side, i keep getting the following errors: Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=N5eSEa2' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. localhost:5000/socket.io/?EIO=3&transport=polling&t=N5eSEa2:1 Failed to load resource: net::ERR_FAILED My Django server is running on http://127.0.0.1:8000/. Can anyone help me find what i'm doing wrong? -
get latest object from databse regardless of user in django
I am learning python and django and I am coding a project similar to IMDB. I am using python 3.8.2 64 bit and django 3 I want to display the latest review a movie received regardless of the user that wrote it. Now it shows the user's own latest review and after logging the user out the review remains without displaying the user that wrote it. I have tried to clear cache and history, didn't help. this is the model: from django.db import models from django.contrib.auth.models import User class Movie(models.Model): movie_title = models.CharField(max_length=250) movie_poster = models.ImageField(default='default.png', blank=True) movie_short_description = models.TextField() director = models.CharField(max_length=250) actor1 = models.CharField(max_length=250) actor2 = models.CharField(max_length=250) actor3 = models.CharField(max_length=250) actor4 = models.CharField(max_length=250) year = models.IntegerField() def __str__(self): return self.movie_title + ' - ' + str(self.year) class Review(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) user = models.ForeignKey(User, default = None, on_delete=models.DO_NOTHING) score = models.IntegerField() review_title = models.CharField(max_length=250, default="") movie_review = models.TextField() date = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'date' def __str__(self): return self.review_title views.py def movie_detail(request, pk): try: movie = Movie.objects.get(pk=pk) review = Review.objects.all().latest() except Exception as e: print(e) return render (request, 'movies/movie_detail.html', {'movie': movie, 'review': review}) html code: </table> </p> <p>User Reviews</p> <h3>Score: {{review.score}} {{review.review_title}}</h3> <h6>{{review.date}}, by {{ user.get_username … -
Optimize file opening in Django (clean and attributes method)
In my forms.py I have a clean() method. The clean method does a lot of things. It opens the file, validates the headers, validates the content etc etc. It works fine. forms.py class BatchFileUploadForm(forms.Form): csv_file = FileField(label='CSV File', required=False) def __init__(self, *args, **kwargs): super(BatchFileUploadForm, self).__init__(*args, **kwargs) self.fields['csv_file'].widget = CustomButtonFileWidget() self.fields['csv_file'].help_text = 'Upload a CSV file which contains the results' def clean(self): uploaded_csv_file = self.cleaned_data['csv_file'] allowed_headers = {'id','name','approve','reject'} validation_errors = [] if not uploaded_csv_file.name.endswith(settings.FILE_UPLOAD_TYPE): raise forms.ValidationError("Please upload .csv extension files only") csvin = csv.DictReader(StringIO(uploaded_csv_file.read().decode('utf-8'))) # lowercase all fieldnames before doing anything else csvin.fieldnames = [name.lower() for name in csvin.fieldnames] After the file is clean, I want to save the contents of the file. So in view.py I have to reopen the file again view.py def upload_batch(request): fileList= [] approved_count = 0 rejected_count = 0 form = BatchFileUploadForm( data=(request.POST or None), files=(request.FILES or None) ) if(form.is_valid()): uploaded_csv_file = request.FILES['csv_file'] csvin = csv.DictReader(StringIO(uploaded_csv_file.read().decode('utf-8'))) # lowercase all fieldnames before doing anything else csvin.fieldnames = [name.lower() for name in csvin.fieldnames] for row in csvin: fileList.append(row) if row['approve'] == 'x': approved_count+=1 if row['reject'] =='x': rejected_count+=1 # putting fileList in session so it can be accessed in the second method save() return render(request, "file/confirm_save.html", {'form': form, 'fileList':fileList, … -
Django: Take the data from database and display on the page in a modified form
Please tell me how to correctly solve the following problem There is a phone number in the database. On the site it is displayed in the same form in which it is recorded in the database +1234567890 And I need this number to look like this, on the site page without modification in the database +(123) 456-7890 views.py def Data(request): card = Cards.objects.filter(is_published=True) context = {'card': card} return render(request, 'templates/cards.html', context) models.py phone = models.CharField(max_length=12, null=True) cards.html {{ card.phone }} Thanks! -
Django Celery - No result backend is configured while running in prod
I use ASGI aka uvicorn to run my django application in production and i'm also using celery to call specific tasks at my app. Now I configured a result backend so that I can see all my tasks results at the Django admin which is working fine if I use the Django development server. But if I switch to production mode and using uvicorn I get back the following error: Exception Value: No result backend is configured. Please see the documentation for more information. while waiting on a celery task I call like that at my views.py: my_task = gen_new.apply_async(kwargs={"user_pk": user.pk}) my_task.get(timeout=30, interval=1) my asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'App.settings') application = get_asgi_application() starting the ASGI server like so: gunicorn App.asgi:application \ --workers $UVICORN_WORKERS \ --bind=127.0.0.1:8000 \ --log-level info settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": [ str("redis://") + str(':') + env.str('REDIS_PASSWORD') + str('@') + env.str('REDIS_HOST') + ":" + env.str('REDIS_PORT') + str("/") + env.str('REDIS_CACHE_DB') ], "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "SOCKET_CONNECT_TIMEOUT": 30, # in seconds "SOCKET_TIMEOUT": 30, # in seconds "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", "CONNECTION_POOL_KWARGS": {"max_connections": env.int('REDIS_MAX_CONN'), "retry_on_timeout": True} } } } BROKER_URL = str("redis://") + str(':') + env.str('REDIS_PASSWORD') + str('@') + env.str('REDIS_HOST') + str(":") + env.str('REDIS_PORT') CELERY_RESULT_BACKEND … -
Django can't extend to a template in another app
This is the structure of the project right now. webbshop templates webbshop base.html home templates home index.html In my "webbshop" settings which is the main app i have put the home as an installed app. But when i try to extend the base.html from index.html I get this error "django.template.exceptions.TemplateDoesNotExist: webbshop/base.html" On the page it shows this. https://i.stack.imgur.com/QUQbd.png It appears that it does not go and look for the template in the webbshop app. I searched around and that should work. This is my index.html {% extends 'webbshop/base.html' %} {% block content %} hey {% endblock %} -
"PL/SQL: ORA-02289: sequence does not exist" in django while doing loaddata. database is remote oracle 12c
while doing loaddata fixture, getting error PL/SQL: ORA-02289: sequence does not exist. Django version is 1.11.12. django.db.utils.DatabaseError: ORA-06550: line 10, column 17: PL/SQL: ORA-02289: sequence does not exist ORA-06550: line 10, column 9: PL/SQL: SQL Statement ignored in python shell, i can create objects but through fixtures, i couldn't. please help. -
Loop over tbody in Django views
I am trying to loop over a tbody in my django views to get the data from the form but when i print the items in the tbody it only shows the last one Here's the part I am trying to loop on <tbody class="player-instances"> <tr> <td><input type="text" name="form-0-pname" id="id_form-0-pname"></td> <td><input type="number" name="form-0-hscore" id="id_form-0-hscore"></td> <td><input type="number" name="form-0-age" id="id_form-0-age"></td> </tr> <tr> <td><input type="text" name="form-0-pname" id="id_form-1-pname"></td> <td><input type="number" name="form-0-hscore" id="id_form-1-hscore"></td> <td><input type="number" name="form-0-age" id="id_form-1-age"></td> </tr> </tbody> Views.py if form.player_instances.cleaned_data is not None: for item in form.player_instances.cleaned_data: print("item", item) print("form.cleaned_data", form.cleaned_data) player = Player() player.pname= item['pname'] player.hscore= item['hscore'] player.age= item['age'] player.save() team.player.add(player) team.save() The output in terminal is the following: item {'pname': 'tt22', 'hscore': 8, 'age': 89} form.cleaned_data {'tname': 'tt1'} Why is it overriding the first input fields despite having different id? -
profile photo not updating after uploading a different photo in Django. request.FILES is always empty. Using Django 2.1
I am trying to update the profile photo of a customer. But it is not updating. request.FILES shows empty if I try to print. if I print request.POST file, it contains the uploaded file but It is not in request.FILES views.py @login_required(login_url='login') @allowed_users(allowed_roles=['customer']) def accountSettings(request): if request.method == 'POST': form = CustomerForm(request.POST, request.FILES, instance=customer) if form.is_valid(): form.save() else : form = CustomerForm(instance=customer) context = {'cust_form' : form} return render(request, 'accounts/account_settings.html', context) models.py class Customer(models.Model): cust_user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default="default.png", null=True, blank=True) # blank=True => not required field date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name forms.py class CustomerForm(ModelForm): class Meta: model = Customer fields = '__all__' exclude = ['cust_user'] I found the cause of empty request.FILES is not adding enctype="multipart/form-data" in form. But I have added that too. accountSettings.html {% extends 'accounts/main.html' %} {% load static %} {% block content %} <style> .profile-pic{ max-width: 200px; max-height:200px; margin: 0 auto; border-radius: 50%; } </style> <br> <div class="row"> <div class="col-md-3"> <div class="card card-body"> <a class="btn btn-warning" href="{% url 'home' %}"> &#8592; Back to Profile</a> <hr> <h3 style="text-align: center">Account Settings</h3> <hr> <img class="profile-pic" src="{{request.user.customer.profile_pic.url}}" > </div> … -
Make success message disappear after few seconds of django form submission and display empty form
I have a Django form where the person needs to add their details to subscribe and I want the page to show successful submission message below the submit button for few seconds (lets say 3) and then it should disappear and the form fields should be displayed empty. The function definition in views.py is as follows : def new_customer(request): if request.method == "POST": form = customer_form(request.POST) if form.is_valid(): form.save() messages.add_message(request, message_constants.SUCCESS, '✔️ SUCCESSFUL SUBSCRIPTION') return HttpResponseRedirect('http://127.0.0.1:8000/subscribe/') else: form = customer_form() return render(request,"new_customer.html",{'form':form}) The Django template : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Subscribe</title> <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet"> <link href="{% static "nav.css" %}" rel="stylesheet"> <link href="{% static "form.css" %}" rel="stylesheet"> </head> {% include "navbar.html" %} <body> <form method="POST" class="post-form" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <button type="submit" class="btn">Subscribe</button> {% if messages %} <ul id ="successMessage" class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %} style="color:green; font-size: 20px; list-style-type: none;">{{ message }}</li> {% endfor %} </ul> {% endif %} </form> </body> </html> The current code helps display the message for successful submission, as well as empty form fields but does not make it disappear. Could anyone help ? -
Django React project structure
I have a project with Django as back-end. And for the client side I have 4 different sections: Django Admin Panel for super user which renders by Django itself. User Login and Signup section which is rendered by Django-Jinja template system. App admin panel which is a react app Main app front-end which is a react app The structure that I have in my mind is like this: ├── djangoproject │ ├── __init__.py │ ├── settings.py (can be folder) │ ├── urls.py │ └── wsgi.py ├── apps | ├── admin_panel | ├── core | ├── auth | └── ... ├── templates | ├── admin_panel (react) | ├── core (react) | └── auth ├── static └── manage.py I have two questions: 1- should I change the structure of my project (for example bring react folders outside or use frontend folder naming instead of templates?) 2- Is it common (or reasonable) to use git sub module for react apps and only commit build of them in main project? If it is can you give any example or best practice? -
how to host simple blog site made django framework by using termux?
Here is my logs . I had made a app on name called my blog on heroku . I had runtime.txt , requirements.txt and pocfile what i am missing https://del.dog/raw/ughuphivol -
How to connect Mongo DB from django?
I am trying to connect mongodb from django.which is settings.py. In setting.py i gievrn connection like DATABASES = { 'default': { 'ENGINE': 'django', 'NAME': 'mydb', } } Where i am executing command like: python manage.py makemigrations it is throwing error like django.core.exceptions.ImproperlyConfigured: 'django' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Please tell me how to connect Mongodb from django. Thanks -
For a "Movie Ticket Booking Web App" I want django movie recommendations based on watch history. What will be the requirements for it?
System should recommend at least 4-5 movies based on user search/watch history. What will be requirements for that? I am using django framework in my app. -
OperationalError: no such column: django-modeltranslation. Django
I have a working app in English. I have started translating tables and istalled django-modeltranslation. I have 11 similar pre-populated tables with the similar content. 8 tables have successfully migrated via python3 manage.py makemigrations and python3 manage.py migrate Migration of remaining 3 tables causes the same error for all three tables. django.db.utils.OperationalError: no such column: rsf_dirt.dirt_en django.db.utils.OperationalError: no such column: rsf_application.application_en django.db.utils.OperationalError: no such column: rsf_dirtproperties.dirtproperties_en All tables properly work via admin panel. Please help. models.py from django.db import models from django.utils.translation import gettext_lazy as _ class FP_sealing(models.Model): value = models.CharField(_('Material Sealing'), max_length=10) descr = models.CharField(_('Description'), max_length=200, default="") def __str__(self): return("Seal: " + self.value) class FP_ventil(models.Model): value = models.CharField(_('Backflush valve'), max_length=20) descr = models.CharField(_('Description'), max_length=200, default="") aufpreis_el_ventil = models.IntegerField(_('Extra Cost el.Valve'), default=0) def __str__(self): return("Ventil: " + self.value) class FP_motor(models.Model): value = models.CharField(_('Motor Power'), max_length=20) descr = models.CharField(_('Description'), max_length=200, default="") def __str__(self): return("Motor: " + self.value) class FP_material_geh(models.Model): value = models.CharField(_('Material Housing'), max_length=25) descr = models.CharField(_('Description'), max_length=250, default="") def __str__(self): return("Mat.Geh.: " + self.value) class FP_coating(models.Model): value = models.CharField(_('Coating'), max_length=25) descr = models.CharField(_('Description'), max_length=250, default="") def __str__(self): return("Coating: " + self.value) class FP_color(models.Model): value = models.CharField(_('External Color'), max_length=25) descr = models.CharField(_('Description'), max_length=200, default="") def __str__(self): return("Color: " + self.value) class … -
Django Forms with a field based on a Foreign Key
I'm working on a Django Form that add new instances of a Model. The Model itself have a ForeignKey instance. Let's say I wanna record all work shifts of each worker. My Model: class WorkShifts(models.Model): date = models.DateField() check_in = models.TimeField() check_out = models.TimeField() person_name = models.ForeignKey(Worker, on_delete=models.DO_NOTHING) And this is my Form: class AddWorkShifts(forms.ModelForm): date = forms.DateField(initial=datetime.date.today, input_formats=['%d/%m/%Y']) check_in = forms.TimeField() check_out = forms.TimeField() class Meta: model = WorkShifts fields = '__all__' def __init__(self, *args, **kwargs): super(AddWorkShifts, self).__init__(*args, **kwargs) self.fields['date'].widget.attrs['class'] = 'form-control' self.fields['check_in'].widget.attrs['class'] = 'form-control' self.fields['check_out'].widget.attrs['class'] = 'form-control' self.fields['person_name'].widget.attrs['class'] = 'form-control' My HTML code: <form method="POST"> {% csrf_token %} {{ form.date }}<br /> {{ form.check_in }}<br /> {{ form.check_out }}<br /> {{ form.person_name }} <button type="submit">Load</button> </form> And my view: def load_shifts(request): form = AddWorkShifts() if request.method == 'POST': form = AddWorkShifts(request.POST) if form.is_valid: form.save() context = {'form': form} return render(request, 'users/wshifts.html', context) At this point, everything works fine. Notice that form.is_valid doesnt have the () signs. But since I have so many persons (the Foreign Key), I configured a JS Autocomplete plugin (EaseAutoComplete) and redesign the form like this: <form align="center" method="POST"> {% csrf_token %} <input type="text" class="p_name" id="provider-file" /> {{ form.date }}<br /> {{ form.check_in }}<br /> …