Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django 404 error when loading <img> tag inside template
I have ~26k pictures inside my static folder that I want to load using a template that I have in Django {% for movie in movies %} <div class="col-6 col-sm-12 col-lg-6"> <div class="card card--list"> <div class="row"> <div class="col-12 col-sm-4"> <div class="card__cover"> <img src="{% static 'img/covers/{{ movie.movie_id }}.jpg' %}"> <a href="/movie/{{ movie.movie_id }}" class="card__play"> <i class="icon ion-ios-play"></i> </a> </div> </div> <div class="col-12 col-sm-8"> <div class="card__content"> <h3 class="card__title"><a href="/movie/{{ movie.movie_id }}">{{ movie.movie_title}}</a></h3> <span class="card__category"> <a href="#">Comedy</a> <a href="#">Adventure</a> </span> <div class="card__wrap"> <span class="card__rate"><i class="icon ion-ios-star"></i>{{ movie.movie_rating }}</span> <ul class="card__list"> <li>HD</li> <li>16+</li> </ul> </div> <div class="card__description"> <p>{{ movie.movie_overview }}</p> </div> </div> </div> </div> </div> </div> {% endfor %} The line <img src="{% static 'img/covers/{{ movie.movie_id }}.jpg' %}"> is where I am facing an issue, the console shows img/covers/&7B&Dmovie.movie_id&3B&D.jpg -
Summernote custom buttons in Django Admin
I want to create a preview button in a summernote editor within Django Admin UI. I put the following config in setting.py file: SUMMERNOTE_CONFIG = { 'summernote': { 'airMode': False, 'width': '100%', 'height': '600', 'lang': 'fr-FR', 'toolbar':[ ['style', ['bold', 'italic', 'underline','clear']], ['style', ['strikethrough', 'superscript', 'subscript']], ['fontname',['fontname','fontsize']], ['fontname',['color']], ['para', ['ul', 'ol', 'paragraph','height']], ['table', ['table','picture','hr']], ['undo redo', ['undo','redo']], ['fullscreen help', ['fullscreen','help']], ['preview', ['preview']], ], 'buttons': { 'preview': 'PreviewButton' }, }, 'js': ( '/static/summernote-ext-print.js', ), } in the summernote-ext-print.js file I've added the following: var PreviewButton = function (context) { var ui = $.summernote.ui; // create button var button = ui.button({ contents: '<i class="fas fa-print"/>', tooltip: 'Preview', click: function () { context.invoke('editor.insertText', 'hello'); } }); return button.render(); // return button as jquery object } But in Django Admin UI the button is not rendered. See secreenshot What's wrong in my code ? Regards. -
How can I dynamically add rows to my form?(Django)
I have a Model which connects to a Form. You can assume it is a very simple model with 1 attribute. class Past_Location(models.Model): location = models.CharField(max_length=100) I want to let the user be able to add more rows to the form via a button. So that's why I reflect this model to a formset: LocationFormSet = forms.modelformset_factory( Past_Location, fields='__all__', extra=1, widgets={ 'location': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter Location Name here' } ) } ) Here is the button creation to add more rows. <div class="input-group"> {{ form.name }} <div class="input-group-append"> <input type="text" name="name" value=""> <button id="add" type="button" class="btn btn-success add-form-row">+</button> </div> </div> I thought the class "add-form-row" would be enough to add more rows dynamically but it was not. So I wanted to follow some examples and use jquery to add more rows. However, since my form is reflected from a model, I don't know how to access and add a new row via jquery. I wanted to post a MVP however the project is too complex with too many necessary files. So I would want to know what is the standard way of interacting with modelForms through jquery? -
Python: Execute a program only file times, after that it should be expire
A program that executes the message "Hello" only 5 times after that if we execute it then it should print the message "demo expired" using file handling concepts. e.g: 1>py Hello.py Hello 2>py Hello.py Hello 3>py Hello.py Hello 4>py Hello.py Hello 5>py Hello.py Hello 5>py Hello.py Sorry, your no. of Demo is Expired -
How to display searched results content same as it is in home page. (django)
I want my search results to work same as it is working in home page.but i'm getting errors after clicking links on search results. urls.py views.py module.py search_results.html -
Django context/template : Rendering multiple results
I have this code that I want it to be able to return multiple products. Now it only return the last one. I think it is because the variables are being overwritten but I don't know other ways to fix it. def result(request): rawquery = request.GET.get('q') #gets the product name to search from a form Product_set = Product.objects.filter(name__icontains=rawquery).distinct() for product in Product_set: name = product.name id = product.id store_name = product.store_name Price_set = Scan.objects.filter(product=id) for price in Price_set: current_price = price.price context = { 'name': name, 'store_name': store_name, 'price': current_price, 'query': rawquery } return render(request, 'result.html', context) This is the template % {extends 'base.html' %} {% block content %} <h1>Results for {{ query }} </h1> <p> {% if name %} {{name}} {% else %} None {% endif %} | {% if store_name %} {{store_name}} {% endif %} | {% if price %} {{price}} {% endif %} </p> {% endblock content %} -
How to convert Django Q object to SQL String
I was working with Django Q object to compose a query. I then switched my query to raw SQL because of the complicated features it needed. I want to convert the Django query composed of Q objects to convert to SQL WHERE clause. Is there any way I could do that? -
How to build a global search option for Django website having multiple models
I have three installed apps in Django which act as three sub web pages in a website. Each app has its own model (some columns like title, pub-date, etc.) and its own search functionality (which searches through each of the column in a model). Now, I want to add a global search option to the whole website which can search through all these three models (of the three apps) via a key word. Is this possible? If so, can anyone guide me please?