Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 /> … -
Django - navbar not showing properly while user logged in
I have a website with the following paths : urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='pages/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='pages/logout.html'), name='logout'), path('mydata/', user_views.mydata, name="data"), path('', include('mysite.urls')), ] each coding section in views directory is preceding by: from django.contrib.auth.decorators import login_required [...] @login_required def profile(request): [...] @login_required def mydata(request): [...] My problem is that I wish the user to be able to only see 'profile' and 'logout', not 'login' or 'register', the logic works with every path, except for /mydata and I can't figure out why. As for my HTML file the base.html looks like this: {% if user.is_authenticated %} <a class="nav-item nav-link" href="/profile">Profile</a> <a class="nav-item nav-link" href="/logout">Logout</a> {% else %} <a class="nav-item nav-link" href="/login">Login</a> <a class="nav-item nav-link" href="/register">Register</a> {% endif %} I include it in my mydata.html file like this: {% extends "pages/base.html" %} {% block content %} [...] {% endblock content %} My question is, is there any workarounds this, to make sure the user is authenticated @ /mydata, I am still relatively new, so your input is welcome. -
Embedding PDF works in IE, but not Chrome
I'm currently using Django to write a simple website, and on one of my pages I'm trying to embed a PDF in the page. The code is pretty simple: <object data="/media/pdfs/my_pdf.pdf" type="application/pdf" style="width:600px; height:750px"> </object> This works on Internet Explorer, but not Chrome. Also, this does work on Chrome if I use a PDF that's hosted online instead of from localhost. Does anyone know why this would be? -
Is my Django model organization involving a ManyToManyField and list_display efficient
I'm trying to modelise the projects undertaken by a company, where each project can have an arbitrary number of tags which relate to specific aspects of the project. An example would be a project whose language would be French, therefore the project would have a language tag whose value is french. However, any project can have an arbitrary amount of tags which point themselves to an arbitrary value. My goal is customizing the ModelAdmin of Django so that the list_view will display a column for each tag pointed to by the ManyToMany field of the project handled by said ModelAdmin Here's what I have so far models.py from django import models class Tag(models.Model): category = models.CharField(max_length=500, blank=False) value = models.CharField(max_length=500, blank=False) class Book(models.Model): name = models.CharField(max_length=500, blank=False) tags = models.ManyToManyField(max_length=500) admin.py @admin.register(Book) @admin.register(Tag) class BookAdmin(admin.ModelAdmin): list_display = ('name', 'tags') def tags(self, object): tags = object.tags.all() output = "" for tag in tags: output += "{0} : {1}".format(tag.category, tag.value) return output For now the solution only works for displaying all tags in one column. Any possible paths I could take to solve this problem ? -
How can i add phone number and data of birth to this signup from?
i want to add phone number and date of birth(dd/mm/yyy) for this form how can i add it? Views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .forms import * def home(request): context = {} return render(request, 'authenticationapp/home.html', context) def signup(request): signup_form = SignUpForm() if request.method == 'POST': signup_form = SignUpForm(request.POST) if signup_form.is_valid(): signup_form.save() user = signup_form.cleaned_data.get('username') messages.success(request, 'Hi'+ ' '+user+ ' ' +'Your Account Created Successfully...') return redirect('signin') context = {'signup_form':signup_form} return render(request, 'authenticationapp/signup.html', context) forms.py from .views import * from .models import * from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] signup.html <h1>SignUp</h1> <form method="POST" action=""> {% csrf_token %} {{ signup_form.as_p }} <input type="submit" name="SignUP"> </form> i want to add phone number and date of birth(dd/mm/yyy) for this form how can i add it? -
how to display the values from .py file in web browser using django?
I am having the .py file which is printing values in command prompt when I run but I need it to be print in web browser can anyone say how can I achieve this? my .py file is # Here using selenium for scraping # importing necessary modules import selenium.webdriver from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By # the relevant url url = 'https://web.bet9ja.com/Sport/SubEventDetail?SubEventID=76512106' driver = webdriver.Chrome(r"c:/Users/SATYA/mysite/chromedriver") driver.get(url) driver.implicitly_wait(10) # seconds elements = [ item.text for item in driver.find_elements_by_css_selector("div.SEOddLnk.ng-binding")] print(elements[0:6]) names = [ item.text for item in driver.find_elements_by_css_selector("div.SECQ.ng-binding")] print(names[0:2]) values = [ item.text for item in driver.find_elements_by_css_selector("div.SEOddsTQ.ng-binding")] print(values[0:6]) driver.quit() output coming in command prompt is: ['3.60', '4.20', '1.87', '1.83', '1.19', '1.25'] ['1X2', 'Double Chance'] ['1', 'X', '2', '1X', '12', 'X2'] My requirement is to get the same output in the web browser can anyone help me? -
'docker-compose up' hangs when attaching files for running Django server in virtualization
I'm trying to run Django inside a Docker container and connect to it using VS code remote, but it keeps hanging at the attach part. Here is my Dockerfile FROM registry.gitlab.com/datadrivendiscovery/images/primitives:ubuntu-bionic-python36-v2020.1.9 ENV PYTHONPATH=$PYTHONPATH:/app WORKDIR /app/ EXPOSE 8000 COPY requirements.txt /app/requirements.txt WORKDIR /app RUN pip install --upgrade pip RUN pip install -r requirements.txt CMD ["sh", "-c", "python3 /app/manage.py runserver"] COPY . . My docker-compose.yml version: '3' services: web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" I don't have a database setup so I don't have that in the yml.