Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should I set up all the logging messages in every page of my django project?
Should I use all of these in views and models and urls in my django project?: logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') I mean, should I just paste these at the end of the files in my project or should I do something different? Would that be enough? (I'm new to logging). -
How to Fixed Django Database Error On Apache Server
The Best Way To Permission Apache Server http://coder-i.com/Digital-Ocean-Apache-To-Django-Database-Operational-Error -
Docker Airflow within Fedora issue on LDAP
can anyone assist with an Docker Airflow within Fedora issue on LDAP , I'm getting the following error after configuring ldap within airflow.cfg File ldap3/strategy/base.py line 147 in open raise LDAPSocketOpenError(unable to open socket exception_historyldap3.core.exceptions.LDAPSocketOpenError: ('unable to open socket', [(LDAPSocketOpenError("('socket ssl wrapping error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:877)',)",), ('ldaps://', 636))]) Any idea how this can be resolved all certs (.cer .key & CA) have been loaded successfully and airflow is running on https://hostname:8080/ -
Clean method is calling another clean method if ValidationError is raised
In my forms.py I have two forms. One is a called a SeriesForm which gets it fields from Series model in models.py, another one is called a SeasonsForm which gets it fields from Seasons model in models.py. If ValidationError is raised in SeasonsForm it calls SeriesForm clean method which is what I don't want if no ValidationError is raised SeriesForm clean method isn't called and everything works fine. The reason I don't want this behavior is because I am rendering both forms in the same page and this behavior causes the other form(SeriesForm) to display values that I've entered in SeasonsForm (when I submit the form). The SeriesForm is like a user editing his profile page, in simple words it gets it instance from the database to fill the values so I do something like this in views.py: series = Series.objects.get(...) SeriesForm(request.POST, instance=series) # notice the instance parameter Maybe because the Seasons model has a foreign key that references Series model it calls the SeriesForm clean method is it because of that? Complete Code I've provided comments in code to help to focus on the important things. models.py class Series(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) SeriesName = models.CharField(max_length=30, default="") slug … -
Allow GET request for only certain Group of Users Django Rest Framework
I am just getting started with Django Rest framework and want to create a feature such that it allows superuser to create a message in admin.py and allow it only to be seen by a certain group(s) ie. "HR","Managers","Interns" etc. in other words, only a user belonging to "HR" group will be allowed to get data from view assigned to "HR" group by admin. I would like to have only one view that appropriately gives permission. Something like #views.py class message_view(APIView): def get(request): user = request.user group = get_user_group(user) #fetches user's respective group try: #if message assigned to 'group' then return API response except: #otherwise 401 Error I need some guidance with this. -
HTML - Create multiple forms out of one form template
I currently have multiple forms that are similar but have small changes. First, the user choses the form from a drop-down menu and then the form is shown below. My forms looks like this. Form 1 Customer Name Phone Number Address Form 2 Customer Name Is married? Form 3 Customer Name Social Security Number Address My code looks something like this. <select onchange="changeOptions(this)"> <option value="" selected="selected"></option> <option value="form1">f1</option> <option value="form2">f2</option> <option value="form3">f3</option> </select> <form class="className" name="form1" id="form1" style="display:none"> ---form--- <form class="className" name="form2" id="form2" style="display:none"> ---form--- <form class="className" name="form3" id="form3" style="display:none"> ---form--- <script> function changeOptions(selectEl) { let selectedValue = selectEl.options[selectEl.selectedIndex].value; let subForms = document.getElementsByClassName('className') for (let i = 0; i < subForms.length; i += 1) { if (selectedValue === subForms[i].name) { subForms[i].setAttribute('style', 'display:block') } else { subForms[i].setAttribute('style', 'display:none') } } } </script> Is there any way to create a 'main' form that has all the form elements and then specify which element to use in each form? The method I'm using right now works fine but there is too much repeated code and probably won't scale correctly if I try to make a change in one of the elements (since I would have to change each one of them and it … -
How to match 2 fields in html (django)
I have a question answer quiz. When I put it in html I get such a result current result (image) I have to manually select the question but I do not want to. I want the question and its corresponding form to appear automatically. what i want (image). I can't guess exactly but I think I have a view to change this is code --> models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE) answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question import random def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm e=Question.objects.all() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): form.save() return render(request, "question/ans.html", {"form":form, "e":e}) ans.html <!DOCTYPE html> <html> <head> <title>question</title> </head> <body> {% for i in e %} <form method="POST" novalidate> {% … -
Field 'id' expected a number but got 'favicon.ico'
I am building a blog app. AND i am using Django 3.8.1 Version. I am stuck on a Problem Traceback (most recent call last): File "C:\app\so\lib\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value return int(value) The above exception (invalid literal for int() with base 10: 'favicon.ico') was the direct cause of the following exception: File "C:\app\so\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\app\so\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\app\so\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\app\mains\views.py", line 261, in detail_view data = get_object_or_404(Post,pk=id) File "C:\app\so\lib\site-packages\django\shortcuts.py", line 76, in get_object_or_404 return queryset.get(*args, **kwargs) File "C:\app\so\lib\site-packages\django\db\models\query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "C:\app\so\lib\site-packages\django\db\models\query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\app\so\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "C:\app\so\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\app\so\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\app\so\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\app\so\lib\site-packages\django\db\models\sql\query.py", line 1319, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\app\so\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup lookup = lookup_class(lhs, rhs) File "C:\app\so\lib\site-packages\django\db\models\lookups.py", line 24, in __init__ self.rhs = self.get_prep_lookup() File "C:\app\so\lib\site-packages\django\db\models\lookups.py", line 76, in get_prep_lookup return self.lhs.output_field.get_prep_value(self.rhs) File … -
Django Rest Framework Auth backend JSON Web Token not generating tokens
Hello everyone I'm new to Django Rest Framework I just want token based authentication backend in my project. I follow this REST framework JWT Auth and saw another token based authentication backend Simple JWT both looks same I am totally confused and get demotivated please guide me how can i acchive this task and how these two backends(REST framework JWT Auth & Simple JWT) are different to each other and which one i should choose. Here is my code for UserRegistration in DRF using REST framework JWT Auth backend and it gives me this error. Its because of get_token(self, obj) in serializer.py file raise DecodeError("Invalid token type. Token must be a {0}".format( jwt.exceptions.DecodeError: Invalid token type. Token must be a <class 'bytes'> Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework.authentication.SessionAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ] } import datetime JWT_AUTH = { 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': # 'rest_framework_jwt.utils.jwt_response_payload_handler', 'users.api.utils.jwt_response_payload_handler', # 'JWT_SECRET_KEY': settings.SECRET_KEY, # 'JWT_GET_USER_SECRET_KEY': None, # 'JWT_PUBLIC_KEY': None, # 'JWT_PRIVATE_KEY': None, # 'JWT_ALGORITHM': 'HS256', # 'JWT_VERIFY': True, # 'JWT_VERIFY_EXPIRATION': True, # 'JWT_LEEWAY': 0, # 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300), # 'JWT_AUDIENCE': None, # 'JWT_ISSUER': None, 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'JWT', 'JWT_AUTH_COOKIE': None, } serializers.py class UserRegistrationSerializer(serializers.ModelSerializer): password1 … -
Django comparing string value from model with int
I'm working on a project and got stuck while trying to figure out how to compare int value that I get from my form with the string value in my model. *Project is a tech shop and I'm creating filters for it. Among them are number of cores and amount of RAM. The thing is when I'm comparing the values for cores (also string, models are below) everything works fine, but with RAM it just doesn't wanna work. models.py class Specs(models.Model): product = models.ForeignKey(Product, ...) spec_name = models.CharField(...) [for amount of ram it is 'ram', for number of cores is 'cpuc'] spec_value = models.CharField(...) [for RAM or number of cores it would be just a number(still string)] Now in my views.py I get the GET data and do the following: **results is the filter from Product model num_of_cores= str(request.GET['num_of_cores']) results = results .filter(Q(specs__spec_name__iexact='cpuc') & Q( specs__spec_value__gte=num_of_cores)) This works fine, but the one bellow, for some reason just doesn't work: ram_amount= str(request.GET['ram_amount']) results= results.filter(Q(specs__spec_name__iexact='ram') & Q(specs__spec_value__gt=ram_amount)) I have no idea what the deal is. The variables are all the same type and it works for one but not the other. I don't understand... -
Getting duplicate users in leaderboard
I'm trying to make a leaderboard for the most liked users by counting the likes of their post and ordering them. However if the user has 2 or more post, it will duplicate the user in the leaderboard with the total likes that he has. Is there a way to fix this? Thank you. models.py: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content = models.TextField(max_length=1500, verbose_name='Content') likes = models.ManyToManyField(User) views.py: def top_user(request): top_user = Post.objects.annotate(total_likes=Count('user__post__likes')).order_by('-total_likes') context = {'users': top_user} return render(request, 'blog/top_user.html', context) html: {% for top in users %} <h5>{{ top.user }}</h5> <p>Upvotes: {{ top.total_likes }}</p> {% endfor %} -
ProgrammingError at / relation "theblog_category" does not exist LINE 1: ..._category"."name", "theblog_category"."name" FROM "theblog_c
while deploying on Heroku I am getting this error. I did local migrations already. My website is running on localhost:8000. It's working perfectly and no complaints there. My heroku website is running, but my database isn't there on my heroku server. I suspect that it's a Django migrations problem, but I can't fix it. I tried the following code: heroku run python manage.py migrate. Same error as before. I tried add, commit and push for the heroku server. git add 'theblog/migrations/* git commit -am 'Heroku' git push heroku It was successful, however 'heroku run python manage.py migrate' was not sucessful. Same message as before. Possible, delete the heroku server and I could try again ~ $ ./manage.py makemigrations Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "theblog_category" does not exist LINE 1: ..._category"."name", "theblog_category"."name" FROM "theblog_c... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line … -
RingCentral OAuth with Django
I'm working through RingCentral's Authorization Flow Quick Start App using Django. This required making a few changes to the Flask code provided, but most of the flow is working. The index page sends me to RingCentral login, which then sends me back to the test page as it should. But when I click on any of the three links on that page I get the same error: AttributeError at /test/ 'bytes' object has no attribute 'get' Here's the Django view that handles the test page (slightly modified from the Flask code provided): def test(request): platform = SyncConfig.rcsdk.platform() platform.auth().set_data(request.session['sessionAccessToken']) if platform.logged_in() == False: return index(request) api = request.GET.get('api') if api == "extension": resp = platform.get("/restapi/v1.0/account/~/extension") return resp.response()._content elif api == "extension-call-log": resp = platform.get("/restapi/v1.0/account/~/extension/~/call-log") return resp.response()._content elif api == "account-call-log": resp = platform.get("/restapi/v1.0/account/~/call-log") return resp.response()._content else: return render(request, 'sync/test.html') And sync/test.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <b><a href="/logout">Logout</a></b> <h2>Call APIs</h2> <ul> <li><a href="/test?api=extension">Read Extension Info</a></li> <li><a href="/test?api=extension-call-log">Read Extension Call Log</a></li> <li><a href="/test?api=account-call-log">Read Account Call Log</a></li> </ul> </body> </html> Has anyone setup a Django authorization flow for RingCentral and can show me where this is breaking? -
Transform function view in Class Based View in Django
I have an archive page with a form that has 2 select option inputs with year and months and I want to select from the database the objects that were created at the year and month selected from the page, I have this function view that works fine but I need the CBV version, I tried with View but it's not working, please a little of help. def archive(request): if request.method == 'POST': year = datetime.strptime(request.POST.get('year'), '%Y') month = datetime.strptime(request.POST.get('month'), '%m') incomes = Income.objects.filter( user=request.user, created_date__year=year.year, created_date__month=month.month) spendings = Spending.objects.filter( user=request.user, created_date__year=year.year, created_date__month=month.month) else: incomes = Income.objects.filter(user=request.user) spendings = Spending.objects.filter(user=request.user) year, month = False, False context = { 'title': 'Archive', 'spendings': spendings, 'incomes': incomes, 'currency': Profile.objects.get(user=request.user).currency, 'total_incomes': round(assembly(incomes), 2), 'total_spendings': round(assembly(spendings), 2), 'total_savings': round(assembly(incomes) - assembly(spendings), 2), 'year': year, 'month': month, } return render(request, 'users/archive.html', context) -
how can i fix django form validation error?
I created a login view and i have this user in database(email:john@gmail.com,password:123) when i filled out my form i got message error means this user wasn't exist, but i have this user in database. what do i do to fix it? my views.py: class User_Login(View): def get(self,request): form = UserLoginForm() return render(request,'login.html',{'form':form}) def post(self,request): form = UserLoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request,email=cd['email'],password=cd['password']) if user is not None: login(request,user) messages.success(request,'شما با موفقیت وارد شدید','success') return redirect('product:home') else: messages.error(request,'نام کاربری و یا رمز عبور اشتباه است','danger') return redirect('users:login') my forms.py: class UserLoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}), label="ایمیل") password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}),label='رمز عبور') -
Django: How to filter a subset in a querset?
How can I filter the elements in a subset? class Order(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) ... class Bill(models.Model): order = models.ForeignKey(Order, blank=True, null=True, on_delete=models.SET_NULL)) billdate = models.DateTimeField(default=timezone.now) payed = models.BooleanField(default=False) ... order = Orders.objects.all() order[0].bill_set will return all Bills. But I just want to get the latest 3 elements, ordererd by billdate. How can I do this? I want to use the result in Django Rest Framework in my viw: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ( 'id' 'bill_set' ) class AffiliateOrderViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = OrderSerializer def get_queryset(self): return Order.objects.filter(bill_set__filter_somehow_only_the_last_3_entries_ordered_by_date) Any idea? -
Automatically populating HTML attributes with Django for-loop
I am making a website using Django and Wagtail CMS, and have a way of filtering posts by a custom attribute called "data-group" in the html template. It works when I hard-code everything, but I would like to use some logic to have that attribute filled dynamically for each post. Basically, I want the post tags to be populated there, but I am having a problem doing this. I will highlight relevant lines of the code with -------------------------- An example of hard-coded filter buttons: <ul class="portfolio-filters"> <li class="active"> <a class="filter btn btn-sm btn-link" data-group="category_all">All</a> </li> <li> <a class="filter btn btn-sm btn-link" data group="category_detailed">Detailed</a> </li> <li> <a class="filter btn btn-sm btn-link" data-group="category_direct-url">Direct URL</a> </li> <li> <a class="filter btn btn-sm btn-link" data-group="category_image">Image</a> </li> <li> <a class="filter btn btn-sm btn-link" data-group="category_soundcloud">SoundCloud</a> </li> <li> <a class="filter btn btn-sm btn-link" data-group="category_video">Video</a> </li> <li> <a class="filter btn btn-sm btn-link" data-group="category_vimeo-video">Vimeo Video</a> </li> <li> <a class="filter btn btn-sm btn-link" data-group="category_youtube-video">YouTube Video</a> </li> </ul> When any of the above buttons are clicked, it filters posts/items with similar values in the data-group attribute. An example of the items it is filtering are below in the figure data-groups list: --------------------------<figure class="item standard" data-groups='["category_all", "category_detailed"]'> -------------------------- <div class="item"> <div class="blog-card"> <div … -
Dockerizing Django & Gunicorn - Docker-compose up error - env vars not set
Launching Django app via docker build + docker run works fine. However, by docker-compose up: I get the error: File "/usr/src/api/api/settings.py", line 39, in <module> api_1 | DEBUG = bool(int(os.environ.get('DJANGO_DEBUG', 0))) api_1 | ValueError: invalid literal for int() with base 10: '' Within my settings.py, I set them as shown below. When hardcoding the vars SECRET KEY & DEBUG in settings.py the docker-compose up works fine. Thus, it seems that the env-vars, as set in manage.py are not comming throug. SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', "testing") DEBUG = bool(int(os.environ.get('DJANGO_DEBUG', 0))) set env vars error descriptiption -
preventDefault() not working after use of ajax in Django 3.1.4
I know javascript a little. But in a tutorial I have to add some jquery and ajax functionality. here is a form: <form class="form-product-ajax" method="POST" action="{% url 'carts:update' %}" class="form"> {% csrf_token %} <input type="hidden" name="product_id" value=" {{p roduct.id}} "/> {% if in_cart %} <button type="submit" class="btn btn-link btn-sm" style="padding:0px;cursor:pointer;" name="button">Remove?</button> {% else %} <span class="submit-span"> {% if product in cart.products.all %} In cart<button type="submit" class="btn btn-danger" name="button">Remove?</button> {% else %} <button type="submit" class="btn btn-success" name="button">Add to cart</button> {% endif %} </span> {% endif %} </form> my jquery and ajax: <script type="text/javascript"> $(document).ready(function(){ var productForm=$(".form-product-ajax") productForm.submit(function(event){ event.preventDefault(); var thisForm=$(this) var actionEndpoint=thisForm.attr("action"); var httpMethod=thisForm.attr("method"); var formData=thisForm.serialize(); $.ajax({ url:actionEndpoint, method:httpMethod, data:formData, type : 'POST', success: function(data){ var submitSpan = thisForm.find(".submit-span") if(data.added){ submitSpan.html("<button type="submit" class="btn btn-danger" name="button">Remove?</button>") }else{ submitSpan.html("<button type="submit" class="btn btn-success" name="button">Add to cart</button>") } }, error: function(errorData){ } }) }) }) </script> Here is my views.py's function: def cart_update(request): #print(request.POST) product_id=request.POST.get('product_id') if product_id is not None: try: product_obj=Product.objects.get(id=product_id) except Product.DoesNotExist: print("Produuct does not exists") return redirect("cart:home") cart_obj,new_obj=Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) added=False else: cart_obj.products.add(product_obj) added=True request.session['cart_items']=cart_obj.products.count() if request.is_ajax(): print("Ajax request") json_data={ "added": added, "removed": not added, } return JsonResponse(json_data) #return redirect(product_obj.get_absolute_url()) return redirect("carts:home") jquery and ajax version: {% load static … -
'AdminSiteTests' object has no attribute 'user' Django unit tests
I can't seem to figure out why my unit test is failing for the following Traceback (most recent call last): File "/app/core/tests/test_admin.py", line 26, in test_users_listed self.assertContains(res, self.user.name) AttributeError: 'AdminSiteTests' object has no attribute 'user' test_admin.py from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setup(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='admin@test.com', password='test123' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email='test@test.com', password='test123', name='test name' ) def test_users_listed(self): """Test that users are listed on user page""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from core import models class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display = ['email', 'name'] admin.site.register(models.User, UserAdmin) models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user""" if not email: raise ValueError('Users must have a email address') user = self.model(email=self.normalize_email(email), **extra_fields) # Must encrypt password using set_password() that comes with BaseUserManager user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Creates and saves new superuser""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports using … -
How to load new template using ajaxed data in django?
I have posted a list using ajax to a view but i can not load the next template to show the posted list in the template.Any Idea? Here is my code: view.py def meter_view (request): data = [] list = request.POST.getlist('list[]') for each in list: d = Meter.objects.get(id = each) data.append(d) print(data) context = { 'data' : data } return render(request,'selectedMeters.html',context) ajax part and the button: <button type="button" class="btn" id="export"> Export </button> $('#export').on('click', function() { $.ajax({ type: 'POST', url: '{% url 'meters-list' %}', data: {'list[]': list }, });}) I want to load selectedMeters.html template after after posting data to it. How can I do that? Thanks. -
Django Installed apps
Why does Django installed apps end with a comma at the end eg INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'dj ango.contrib.staticfiles', 'rest_framework', ] Is the extra comma necessary? -
Adding an element that is not part of a model to Django admin page
I am trying to add a date that displays at the top of every page in Django admin but I haven't been able to find any documentation that discusses this. It needs to be a date that populates based on a script that says when the data was last pulled. Would anyone have any ideas on how to do this? -
Django can not connect to MySQL container?
I have a docker-compose like a bellow: version: '3' services: mysql: image: mysql ports: - 3306:3306 env_file: ./src/.environment volumes: - mysql_data:/var/lib/mysql web: build: context: ./src dockerfile: Dockerfile command: bash -c "python manage.py collectstatic --no-input && python manage.py makemigrations --no-input && python manage.py migrate --no-input" env_file: ./src/.environment ports: - 8001:8001 depends_on: - mysql volumes: - ./src:/var/www/project/src - staticfiles:/var/www/project/src/statics .environment content as follow: DATABASE_MYSQL_NAME=dataCollection DATABASE_MYSQL_HOST=mysql DATABASE_MYSQL_USER=user1 DATABASE_MYSQL_PASSWORD=user123456 DATABASE_MYSQL_PORT=3306 Then in django setting I have follow database configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv('DATABASE_MYSQL_NAME'), 'HOST': os.getenv('DATABASE_MYSQL_HOST'), 'USER': os.getenv('DATABASE_MYSQL_USER'), 'PASSWORD': os.getenv('DATABASE_MYSQL_PASSWORD'), 'PORT': os.getenv('DATABASE_MYSQL_PORT'), } } But, when I run docker-comose up it throws the following error: MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'mysql' (115)") I don't know what the problem is? -
ERROR: Could not find a version that satisfies the requirement ipython==7.18.1
Getting this error while pushing to heroku ERROR: Could not find a version that satisfies the requirement ipython==7.18.1 (from -r /tmp/build_bd03014c/requirements.txt (line 36)) (from versions: 0.10, 0.10.1, 0.10.2, 0.11, 0.12, 0.12.1, 0.13, 0.13.1, 0.13.2, 1.0.0, 1.1.0, 1.2.0, 1.2.1, 2.0.0, 2.1.0, 2.2.0, 2.3.0, 2.3.1, 2.4.0, 2.4.1, 3.0.0, 3.1.0, 3.2.0, 3.2.1, 3.2.2, 3.2.3, 4.0.0b1, 4.0.0, 4.0.1, 4.0.2, 4.0.3, 4.1.0rc1, 4.1.0rc2, 4.1.0, 4.1.1, 4.1.2, 4.2.0, 4.2.1, 5.0.0b1, 5.0.0b2, 5.0.0b3, 5.0.0b4, 5.0.0rc1, 5.0.0, 5.1.0, 5.2.0, 5.2.1, 5.2.2, 5.3.0, 5.4.0, 5.4.1, 5.5.0, 5.6.0, 5.7.0, 5.8.0, 5.9.0, 5.10.0, 6.0.0rc1, 6.0.0, 6.1.0, 6.2.0, 6.2.1, 6.3.0, 6.3.1, 6.4.0, 6.5.0, 7.0.0b1, 7.0.0rc1, 7.0.0, 7.0.1, 7.1.0, 7.1.1, 7.2.0, 7.3.0, 7.4.0, 7.5.0, 7.6.0, 7.6.1, 7.7.0, 7.8.0, 7.9.0, 7.10.0, 7.10.1, 7.10.2, 7.11.0, 7.11.1, 7.12.0, 7.13.0, 7.14.0, 7.15.0, 7.16.0, 7.16.1) remote: ERROR: No matching distribution found for ipython==7.18.1 (from -r /tmp/build_bd03014c/requirements.txt (line 36)) remote: ! Push rejected, failed to compile Python app.