Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use a third-party repo, which requires a conda environment, within my Django project
I'm setting up a Django project on an Ubuntu 18.06 Digital Ocean droplet. I'm using python3-venv to create virtual environment in my project root, and have installed django and other dependencies within this. I'm using a DRF class SplitTrackView(APIView): within which I want to call the separator.separate_to_file method from the spleeter project: https://github.com/deezer/spleeter I've currently cloned the spleeter repo into my project folder, and installed miniconda in my home directory, but the second step in the spleeter setup instructions is: conda install -c conda-forge spleeter So here I'm creating a new virtual envorinment in conda to allow spleeter to run. My questions are: Is cloning the repo into my project root the best approach? How do I handle dependency management when I have a virtual environment for my Django project, and a separate conda one to run spleeter? Many thanks. -
css does not apply style to templates in django
The theme applied by css does not work. In the past it used to apply but i do not what i did that its not executable anymore. base.htmnl is core template for other pages. In base.html i have : <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static 'nana/css/main.css' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </head> <body> <nav class='navbar mynav-fixed-top navbar-expand-lg bg-dark' role='navigation' id='navbar'> <div class="container-fluid"> </div> </nav> <div class="container-fluid"> {% block content %} <div class="main"> </div> {% endblock %} main.css body{background-color: yellow} settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')] The css does not work. I do not knwow why the application does not apply changes in css file. Would appreciate your though and help how to fix it. -
Django - Issue viewing media files on admin page
In my user model, I have a property called profilePic. This is set to an image within my media folder at the root of my project. I display the profilePic image in a template, and it is displayed successfully. However in my admin page, when I click the link set to the profilePic attribute, I get returned a 404 error. Here is my models.py: class User(AbstractUser): profilePic = models.ImageField(upload_to='profile_pics/', default='media/default-profile.png') settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) template: <!DOCTYPE html> <html lang="en"> <body> <img src="{{ user.profilePic }}"></img> </body> </html> The image is successfully displayed in the browser, however in the admin, when I click the path that links to the file, I get s 404 Page Not Found Error. The url changes when I click the path, it changes too http://localhost:8000/media/media/default-profile.png. An extra /media/ is in the url. This may be due to what I set the default property to on the profilePic attribute, however when I remove the media/ and the beginning of the default property, the image cannot be viewed in the browser no longer, however can be viewed in the … -
django ajax click function - change value of foreign key textchoice field
I have 2 models ToDoList and Tasks. In Tasks model I set a ForeignKey to ToDoList (one ToDoList can have many tasks). What I want to do is: I want to have next to every task in the detail view a button. When I click on the button the "status field" of this specific task should change to trash. I want to use ajax and trying to understand it (Iam new to that). Can somebody please help/guide and support me. models.py from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class TimeStamp(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: abstract = True class ToDoList(TimeStamp): class STATUS(models.TextChoices): PUBLISHED = "published", "Published" TRASH = "trash", "Trash" WORKINGDRAFT = "workingdraft", "Workingdraft" headline = models.CharField(max_length=200) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) status = models.CharField("Status", max_length=20, choices=STATUS.choices, default=STATUS.PUBLISHED) def __str__(self): return self.headline def get_absolute_url(self): return reverse('notepad:todo_detail', args=[str(self.id)]) class Tasks(TimeStamp): class STATUS(models.TextChoices): PUBLISHED = "published", "Published" TRASH = "trash", "Trash" WORKINGDRAFT = "workingdraft", "Workingdraft" todos = models.CharField(max_length=250) todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE, related_name='tasks') status = models.CharField("Status", max_length=20, choices=STATUS.choices, default=STATUS.PUBLISHED) def __str__(self): return self.todos views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponseRedirect from django.forms.models import … -
How to fix django.db.utils.IntegrityError: insert or delete on table in Django 3.x
From today morning I'm getting django.db.utils.IntegrityError: insert or update on table "Department_course" violates foreign key constraint "Department_course_Course_type_id_71e71f3c_fk_Departmen" DETAIL: Key (Course_type_id)=(UG) is not present in table "Department_coursetype". error while migrating django models. Help me to fix this problem guys. Today morning I tried to create another two models with foreign keys of department model. From that time the issue was started.But now I deleted these two models. And still i got same error. help me to fix it models.py from django.db import models # Create your models here. class departments(models.Model): # department = models.CharField(max_length = 40, null = True) name = models.CharField(max_length=40, unique=True, primary_key = True) img = models.ImageField(upload_to="Dept_img", null = True) desc = models.TextField(null = True) def __str__(self): return self.name class department_detail(models.Model): name = models.OneToOneField(departments, on_delete=models.CASCADE, null = True) About = models.TextField(null = True) def __str__(self): return self.name.name class course(models.Model): COURSE = ( ('UG','UG'), ('PG','PG') ) Department_name = models.ForeignKey(departments, on_delete=models.CASCADE, null = True) Course_type = models.CharField(null=True, max_length=40, choices=COURSE, default = None) Course_name = models.CharField(null = True, max_length=80) Course_duration = models.CharField(null=True, max_length=30) def __str__(self): return self.Department_name.name class carousel(models.Model): Department = models.ForeignKey(departments,on_delete=models.CASCADE, null = True) Image = models.ImageField(upload_to='Carousel', null = True) Img_title = models.CharField(max_length=30, null=True) Img_desc = models.CharField(max_length=500, null=True) date_created = models.DateTimeField(auto_now_add=True, … -
Multiple Django projects on one domain under sub urls using NGINX and proxy_pass
I have a Django app on mydomain.com/. I want to have another app on, lets say, mydomain.com/staging/. 1st app: mydomain.com/ 2nd app: mydomain.com/staging/ How do I configure it in Nginx and Django? After this location ~* ^/staging/ { rewrite ^/staging/(.*) /$1 break; proxy_pass http://127.0.0.1:18000; }` I still have my 2nd app redirect me to my 1st app. When I use mydomain.com/staging/admin/, it redirects me to mydomain.com/admin/, and every URI I use does the same. What is the proper way of configuring multiple sub-url Django apps? -
How do I solve this error and install Django?
SSL module is not available in Python -
Error running WSGI application in pythonanywhere.com
I have this problem that I cant solve. After i done this in WSGI configuration file, when I go to my link I got this error. Anyone have some idea why? # +++++++++++ DJANGO +++++++++++ # To use your own django app use code like this: import os import sys # ## assuming your django settings file is at '/home/Gvozdeni/mysite/mysite/settings.py' ## and your manage.py is is at '/home/Gvozdeni/mysite/manage.py' path = '/home/Gvozdeni/django-deployment-example/learning_templates' if path not in sys.path: sys.path.append(path) os.chdir(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE","learning_templates.settings") import django django.setup() # #os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' # ## then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() 2020-03-21 10:18:45,203: Error running WSGI application 2020-03-21 10:18:45,204: File "/var/www/gvozdeni_pythonanywhere_com_wsgi.py", line 52 2020-03-21 10:18:45,204: 2020-03-21 10:18:45,204: import django.setup() 2020-03-21 10:18:45,204: 2020-03-21 10:18:45,204: ^ 2020-03-21 10:18:45,204: 2020-03-21 10:18:45,204: SyntaxError: invalid syntax 2020-03-21 10:18:45,204: *************************************************** 2020-03-21 10:18:45,205: If you're seeing an import error and don't know why, 2020-03-21 10:18:45,205: we have a dedicated help page to help you debug: 2020-03-21 10:18:45,205: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2020-03-21 10:18:45,205: *************************************************** 2020-03-21 10:23:13,457: Error running WSGI application 2020-03-21 10:23:13,457: File "/var/www/gvozdeni_pythonanywhere_com_wsgi.py", line 52 2020-03-21 10:23:13,458: 2020-03-21 10:23:13,458: import django.setup() -
SMTPAuthenticationError Django 2
I keep getting this error in my django application shell raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials s1sm13291905wrp.41 - gsmtp') the shell commands: >>> from django.core.mail import send_mail >>> send_mail('Django mail', 'This e-mail was sent with Django.', 'XXXXX@gmail.com', ['to@gmail.com'], fail_silently=False) my settings.py configurations: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '......@gmail.com' EMAIL_HOST_PASSWORD = '.....' EMAIL_PORT = 587 EMAIL_USE_TLS = True I tried every solution out there (Disable 2FA, allowed less secure apps..) Also The gmail/ pass are correct -
In Django GraphQL JWT user registration, How can I return token in mutation?
I have used serializer mutation to create user class UserCreateMutation(SerializerMutation): class Meta: serializer_class = UserRegistration model_operations = ['create'] I want to generate a token while creating the user and return it in mutation, just like token_auth. Is there any way that I can do it using django_graphql_jwt library? P.S. I do not have any token variable in my user model. -
static/index.js net::ERR_ABORTED 404 (Not Found) happen
i'm developing django project with klaytn i have coded web part and want using other javascript in this django project I added other part on "static" directory that in my django project like this and typed on template html header like this: //< script type="text/javascript" src="/static/index.js"> but it's cant find static folder's index.js file error log i need your help -
How to monitor tasks in celery with SQS broker?
What could be a way to have a dashboard similar to flower to monitor the celery tasks. From the documentation, I see that SQS monitoring support is not yet there. What could be another option? I am using Django with celery. -
Django database error while making field unique
On User table i changed phone field to unique by adding unique=True . when i run makemigrations it created file like this : from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('User', '0005_auto_20200321_1543'), ] operations = [ migrations.AlterField( model_name='user', name='phone', field=models.CharField(blank=True, max_length=13, unique=True, verbose_name='phone'), ), ] after running migrate command it raises this error : psycopg2.errors.DuplicateTable: relation "User_user_phone_5262bb8b_like" already exists I checked postgres database constraints and tables . there is no table or relation with this name . so i think there is a problem in migration files . how can i solve this ? In Past phone field was unique and i changed it . now again I change it to unique . -
Django Geo: Distance function and user_point.distance(outlet_point)*100 both are giving different answer
I am trying to sort the restaurant on the bases of nearest outlet using Distance and Point. I tried below django query to get the nearest restaurant under 40km range.: from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.measure import D from django.contrib.gis.geos import GEOSGeometry u_pnt = GEOSGeometry('SRID=4326;POINT (%f %f)' % (lat, long)) db_res = RestaurantBusinessAddress.objects.exclude(restaurant_id__in=blocked_res).filter( point__distance_lte=(u_pnt, D(km=40)), is_active=True, ).annotate( distance=Distance('point', u_pnt)).order_by('distance').values_list('restaurant_id', 'id', 'distance') Output: <QuerySet [(148, 309, Distance(m=5345.52643776)), (150, 312, Distance(m=5355.11929609)), (150, 311, Distance(m=5355.11929609))]> Here I am getting Distance object with values 5345.52643776m and 5355.11929609m But when I am trying to find the distance between two points using below code: user_pnt = Point(float(lat), float(long)) distance = user_pnt.distance(out_pnt) * 100 Output: 11.5 km Why I am getting the the different values? and how can I fix this issue? Please help me, your time will be highly appreciable. -
Django Filter QuerySets Dynamically with 1:1, 1:n and m:n Relations
The goal the project is to match teams (e.g. football) with coaches, according to their interest (e.g. football, soccer) and event (time). I have troubles displaying attributes of 4 different models (user, coaches, event, interest) in one html. The Models have the following relationship: User:Coaches = 1:1 Coaches:Subject = n:m User:Events = 1:n So far I have the following: models.py: class User(AbstractUser): is_coach = models.BooleanField(default=False) is_team = models.BooleanField(default=False) birthdate = models.DateField(null=True) text_education = models.TextField(max_length=500, default='Default Text') class Coach(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) interests = models.ManyToManyField(Subject, related_name='interested_coach') def __str__(self): return self.user.username class Subject(models.Model): name = models.CharField(max_length=30) class Event(models.Model): coach_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name='events_coach') team_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name='events_team', null=True) interests = models.CharField(max_length=255, null=True) date = models.DateTimeField(default=timezone.now) urls.py: urlpatterns = [ path('teams/', include(([ path('search', teams.search, name='search'), ]] views.py def search(request): user_list = Event.objects.prefetch_related() user_filter = UserFilter(request.GET, queryset=user_list) return render(request, 'teams/user_list.html', {'filter': user_filter}) filter.py class UserFilter(django_filters.FilterSet): class Meta: model = User fields = ['username', 'first_name', 'is_staff', 'first_name', 'last_name'] user.html {% extends 'base.html' %} {% block content %} <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> <table class="table table-bordered"> <thead> <tr> <th>User_Username</th> <th>Coach_Interests</th> <th>Coach_User</th> <th>Eventscoach_Events</th> </tr> </thead> <tbody> {% for user in filter.qs %} <tr> <!-- works --> <td>{{ user.username}}</td> <!-- doesnt work … -
Average the results from a function over many objects
I'm trying to calculate stats on the trades in my model. These stats are mainly derived using functions inside my trade model. I've listed all the stats that are so far working and right now I'm stuck on calculating the Avg "win" value and percent. Thanks for the help SOF community! views.py class StatsView(LoginRequiredMixin, TemplateView): template_name = 'dashboard/stats.html' def get_context_data(self, *args, **kwargs): trade = Trade.objects.filter(user=self.request.user, status='cl') context = super(StatsView, self).get_context_data(*args, **kwargs) #ALL WORKING STATS context['all_trades'] = Trade.objects.filter(user=self.request.user).count() context['gross_profit'] = sum([t.get_profit_loss_value() for t in trade]) context['net_profit'] = sum([t.get_profit_loss_value_fees() for t in trade]) context['win_trades_profit'] = sum(t.get_profit_loss_value_fees() for t in trade if t.get_trade_result() == 'win') context['loss_trades_profit'] = sum(t.get_profit_loss_value_fees() for t in trade if t.get_trade_result() == 'loss') context['win_trades_count'] = sum(t.get_trade_result() == 'win' for t in trade) #context['win_trades_count'] = [t.get_trade_result() for t in trade].count('win') ALSO WORKS context['loss_trades_count'] = sum(t.get_trade_result() == 'loss' for t in trade) context['scratch_trades_count'] = sum(t.get_trade_result() == 'scratch' for t in trade) context['total_fees'] = sum([t.get_fees() for t in trade]) #NOT WORKING YET #Calculate Avg Profit For All Winning Trades #Test 1 #Result: Avg(Value(<generator object StatsView.get_context_data.<locals>.<genexpr> at 0x000001D4B7F3B8C8>)) #context['avg_win'] = Avg(t.get_profit_loss_value_fees() == 'win' for t in trade) # Test 2 #Result: Avg(Value(<generator object StatsView.get_context_data.<locals>.<genexpr> at 0x000002C98818F3C8>)) #context['avg_win'] = Avg(t.get_profit_loss_value_fees() for t in trade if … -
get all mobiles with a company - Django REST framework
so, I have a model with ForeignKey that gets all [mobiles] that I saved. I want to get all mobiles by a company. for example: api/company/[samsung] how can I serializers this? models.py class Company(models.Model): name = models.CharField(max_length=250, primary_key=True, unique=True) def __str__(self): return self.name class Mobiles(models.Model): title = models.CharField(max_length=250) company = models.ForeignKey(Company, on_delete=models.CASCADE) release = models.DateField(blank=True, null=True) views.py class MobileApiView(generics.ListAPIView): queryset = Mobiles.objects.all() serializer_class = MobilesSerializers class DetailMobile(generics.RetrieveAPIView): queryset = Mobiles.objects.all() serializer_class = MobilesSerializers serializers.py class MobilesSerializers(serializers.ModelSerializer): class Meta: model = Mobiles fields = '__all__' and urls.py urlpatterns = [ path('mobiles/', MobileApiView.as_view()), path('mobiles/<int:pk>/', DetailMobile.as_view()), ] -
POstgresql: duplicate key value violates unique constraint
I am newbie in development and in Django in particular. I have developed a project that is in testing and I am starting to think about production deployement and in particular the initialization of the database and the creation of the users. I'm not sure which is the simplest and most effective approach ... I have search on google but I did not find anything on this subject ... I'm going to have more than thirty user accounts to create at once, so I wrote a script that I will launch on my prodcution database in addition to managing password hashing (for the moment, I am using a python shell to use the make_password () function and created a valid password) in this script, I am wondering how to send the login / mdp to automate my users. I did not see an option 'send identifiers by email' in the Django admin interface yet very complete so I imagine that I have to create an application or at least a script to manage it? -
Django Queryset based on 2-3 related tables
I have 3 related tables in the database. from django.db import models # Create your models here. class Country(models.Model): country_code = models.CharField('Country code', unique=True, max_length=3) country_name = models.CharField('Country Name', max_length=25, default="") class Customers(models.Model): dnr = models.CharField('Customer Nr', max_length=8, unique=True) dname = models.CharField('Customer Name', max_length=50, default="") dcountry = models.ForeignKey(Country, on_delete=models.CASCADE) class BigTable(models.Model): deb_nr_f = models.ForeignKey(Customes, on_delete=models.CASCADE, related_name='debitor_fnr') sales_2016 = models.IntegerField('Abs. 2016', default=0) sales_2017 = models.IntegerField('Abs. 2017', default=0) sales_2018 = models.IntegerField('Abs. 2018', default=0) sales_2019 = models.IntegerField('Abs. 2019', default=0) sales_2020 = models.IntegerField('Abs. 2020', default=0) How can I create a query set from two tables: Cutomers and Bigtables in this form: Customer Nr 1 /// Sales_2016 /// Sales_2017 /// ... Customer Nr 2 /// Sales_2016 /// Sales_2017 /// ... Customer Nr ... How can I create a query set from three tables: Countries, Cutomers and BigTable in this form: Country Nr 1 /// Sales_2016 /// Sales_2017 /// ... Country Nr 2 /// Sales_2016 /// Sales_2017 /// ... Country Nr ... Thank you -
AttributeError at /login/ 'dict' object has no attribute '_meta' (Django with FireBase)
ı have basic django project and nowadays , ı was trying to connect my django project to firebase but ı am getting an error.I could not get rid of this error and why ı get this error? can someone please help me about this topic? Anyway there is my loginPage function which is in views.py. from django.shortcuts import render, redirect from django.forms import inlineformset_factory from django.contrib.auth import login, logout from django.contrib import messages import pyrebase from django.contrib.auth.decorators import login_required from .models import * from .forms import OrderForm, CreateUserForm from .filters import OrderFilter config = { 'apiKey': "", 'authDomain': "", 'databaseURL': "", 'projectId': "", 'storageBucket': "", 'messagingSenderId': "", 'appId': "", 'measurementId': "" } firebase = pyrebase.initialize_app(config) auth = firebase.auth() def loginPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == "POST": email = request.POST.get('email') password = request.POST.get('password') user = auth.sign_in_with_email_and_password(email, password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Email OR password is incorrect!') return render(request, 'accounts/login.html') where is my mistake? , I can't see any , but when ı try to login with e-mail which is in created in firebase , for example; django123@gmail.com , 123456django when ı click login button ı got, " AttributeError at /login/ 'dict' … -
Django - get string of rendered context variable
How does Django renders variables into their html form in templates ? For instance, given a model field updated = models.DateTimeField(), how can one get the string representation of {{ mymodel.updated }} that is rendered in templates ? -
how to Update Django Database with in coming data using api
I want to get the data from an API source and the incoming data should be updated to my data base every one Hour which should be done in back end and i want to use that data for analysis can anyone suggest me how to update it in back ground every hour(like stock market API i am getting a particular stock price every hour it should be updated every my data base) using Django python. -
Bootstrap modals not appearing properly in Django Admin
I'm trying to display a confirmation modal when clicking the save button in Django admin. but the modal not fade in properly as usual, it seems it isn't able to use the js bootstrap refer to the attached figure This is My HTML code: {% load admin_list static i18n %} <script type="text/javascript" src="{% static 'MDB-Free_4.8.11/js/jquery-3.4.1.min.js' %}"></script> <link href="{% static 'MDB-Free_4.8.11/css/mdb.min.css' %}" rel="stylesheet"> <script type="text/javascript" src="{% static 'MDB-Free_4.8.11/js/bootstrap.js' %}"></script> <div id="results"> .... </div> <div class="modal fade" id="number-inbound-change-modal" tabindex="-1" role="dialog" data-backdrop="true" aria-labelledby="exampleModalLabel" aria-hidden="true" style="display:none"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <button id="clos" type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body row"> <p>{% trans 'the number will be changed, are you sure?' %}</p> </div> <div class="modal-footer"> <div class="cancel-modal-button-box"> <button class="btn btn-primary cancel-modal-button" id="no"> {% trans 'No' %} </button> </div> <div class="save-modal-button-box"> <button type="submit" id="yes" class="btn btn-primary button-space" data-dismiss="modal" aria-label="Close">{% trans 'yes' %} </button> </div> </div> </div> </div> </div> This is the JS code <script type="text/javascript"> document.getElementById("changelist-form").addEventListener("submit", function (event) { event.preventDefault(); console.log('sunbmit'); confirmation(); }); function confirmation() { document.getElementById("number-inbound-change-modal").style.display = "block"; document.getElementById('yes').onclick = function () { document.getElementById("changelist-form").submit(); document.getElementById("number-inbound-change-modal").style.display = "none"; }; document.getElementById('no').onclick = function () { document.getElementById("number-inbound-change-modal").style.display = "none"; }; } </script> -
Acquire model instance as view parameter instead of model id
In laravel, it's possible to have access to entire models with type-hinting the parameter with a model class. for example: routes/web.php Route::get('posts/{post}', function(\App\Post $post) { /* $post is now the model with pk in url and if the pk is wrong it throws an 404 automatically */ }); How is that possible in django? (with functions as view) def posts(request, post_id): post = Post.objects.get(pk=post_id) # ... The second line is completely boilerplate and so much repeated in my code. -
django.db.utils.OperationalError: could not connect to server:
I am trying to make this project running. When I started docker-compose in db and root, I get the following error: backend_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection backend_1 | self.connect() backend_1 | File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__ backend_1 | raise dj_exc_value.with_traceback(traceback) from exc_value backend_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection backend_1 | self.connect() backend_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner backend_1 | return func(*args, **kwargs) backend_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 197, in connect backend_1 | self.connection = self.get_new_connection(conn_params) backend_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner backend_1 | return func(*args, **kwargs) backend_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection backend_1 | connection = Database.connect(**conn_params) backend_1 | File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 126, in connect backend_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) backend_1 | django.db.utils.OperationalError: could not connect to server: Connection refused backend_1 | Is the server running on host "192.168.1.107" and accepting backend_1 | TCP/IP connections on port 5432? From postgres docker I get the following information: postgres_1 | 2020-03-21 09:49:56.090 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 postgres_1 | 2020-03-21 09:49:56.090 UTC [1] LOG: listening on IPv6 address "::", port 5432 So, it seems that my postgres runs on 0.0.0.0 and backend is …