Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail: How to validate m2m inline model?
I have a custom form inheriting from WagtailAdminPageForm and I want to validate an m2m model field (ClusterableModel). Right now I am using the clean() method on my form class. def clean(self): cleaned_data = super().clean() my_field_total_sum = 0 for form in self.formsets['my_field'].forms: if form.is_valid(): cleaned_form_data = form.clean() my_field_total_sum += cleaned_form_data.get('my_value') if total_sum > 100: form.add_error('my_value', 'More then 100 is not allowed') return cleaned_data This works fine until I add and/or remove some inline panels in the admin interface and save my page as a draft and try to validate again. Because self.formsets['my_field'].forms still contains already removed forms and never gets reset to the actual amount of inline panels in the admin. So, is it possible to (re-)set self.formsets['my_field'].forms to the actual amount inline panels visible in the admin interface? Or should I validate elsewhere anyways? -
could not convert string to float: '10,000' Using Django
How do i convert string to float in django? this is my views.py def UpdateFamilyIncomes(request): id = request.POST.get('id') Amount_From = int(float(request.POST.get("Amount_From"))) Amount_To = int(float(request.POST.get("Amount_To"))) Family_Total_Income = FamilyTotalIncome.objects.get(id=id) Family_Total_Income.Amount_From = Amount_From Family_Total_Income.Amount_To = Amount_To this is my models.py class FamilyTotalIncome(models.Model): Description = models.CharField(max_length=500,null=True,blank=True) Amount_From=models.FloatField() Amount_To = models.FloatField() Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) this is my error -
how to bypass Django CSRF verification
for bypassing csrf verification I used csrf_exempt. when I use csrf_exempt in a view and when this function will call automatically login user logout. I cant understand the problem. if anyone knows please help me @csrf_exempt def checkout_done(request): cart_obj,cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.product.count()==0: return redirect('carts:home') login_form = LoginForm() guest_form = GuestForm() address_form = AddressForm() billing_address_form =AddressForm() billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id",None) billing_profile, billing_profile_created= BillingProfile.objects.new_or_get(request) address_qs = None if billing_profile is not None: if request.user.is_authenticated: address_qs = Address.objects.filter(billing_profile=billing_profile) order_obj,order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj) if shipping_address_id: order_obj.shipping_address =Address.objects.get(id=shipping_address_id) del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address = Address.objects.get(id=billing_address_id) del request.session["billing_address_id"] if shipping_address_id or billing_address_id: order_obj.save() if request.method == "POST": "check that order is done" is_done = order_obj.check_done() if is_done: order_obj.mark_paid() request.session['cart_items'] = 0 del request.session['cart_id'] entry_obj = Entry.objects.filter(eCart=cart_obj) for objects in entry_obj: objects.active = False objects.save() #entry_obj.save() return redirect("carts:checkout_done") cart_obj ,new_obj = Cart.objects.new_or_get(request) products = cart_obj.product.all() entry_obj = Entry.objects.filter(eCart=cart_obj) quentity_obj = Entry.objects.filter(eCart=cart_obj,active=True) return render(request, "carts/checkout_done.html", {}) -
Django initial form values from db query in views
I'm trying to set initial values in form for editing within views. For example i want to edit book that is allready stored in database setting initial values from database query. Is it possible in django ? For instance: views.py: from .models import Book from .forms import BookForm def edit_book(request,book_id): query_book=Book.objects.get(pk=book_id) Book_form_to_edit =BookForm(initial=query_book) context={ 'book_form':Book_form_to_edit, } return render(request,'edit_book.html',context) Thank you in advance. -
custom Django Rest Framework serializer to look up field for POST request
I have a serializer and I want it to get a field from another model for POST requests. Below is an example of what I'm trying to do (code taken from this tutorial: https://www.youtube.com/watch?v=h48Fxecu7EY) class BlogPostSerializer(serializers.ModelSerializer): username = serializers.SerializerMethodField('get_username_from_author_table') class Meta: model = BlogPost fields = ['title', 'author_id', 'username'] def get_username_from_author_table(self, author_id): return Author.objects.get(id=author_id).username And my BlogPost model has the following fields: title, username. Is it possible to create this serializer for a POST request? I haven't been able to get it to work, and I'm seeing that SerializerMethodField is only for GET requests in other posts. -
Django - (Restrict content from blocked users) Cannot unpack non-iterable ManyRelatedManager object
Hey guys I want the view to not show contents of blocked users, but I am getting an error like this: How can I restrict the content from not showing in the template? Please have a look at the views. TypeError at /videos/all_videos/ cannot unpack non-iterable ManyRelatedManager object Request Method: GET Request URL: http://127.0.0.1:8000/videos/all_videos/ Django Version: 3.0.5 Exception Type: TypeError Exception Value: cannot unpack non-iterable ManyRelatedManager object views class AllVideoView(ListView, LoginRequiredMixin): model = VideoPost template_name = 'videos/users/all_video_view.html' paginate_by = 20 def get_context_data(self, **kwargs): context = super(AllVideoView, self).get_context_data(**kwargs) current_user = self.request.user video_list = VideoPost.objects.exclude(current_user.profile.blocked).order_by('-post_date') paginator = Paginator(video_list, self.paginate_by) page = self.request.GET.get('page') try: videos = paginator.page(page) except PageNotAnInteger: videos = paginator.page(1) except EmptyPage: videos = paginator.page(paginator.num_pages) context = { 'page':page, 'videos':videos, } return context I understood one thing that I called the video_list wrong. can anyone tell me how to properly do that? Thanks -
Celery worker takes tasks fairly
guys. I'm working on celery worker. And I have some questions. I use 4 celery workers with concurrency 3. They are working for same job. They are looking at same queue. when I make task, I make 4 tasks at once. but each tasks takes different time. It is like this: [task1,task2,task3,task4] task1 : takes 10s task2 : takes 30s task3 : takes 50s task4 : takes 70s It is sent to same queue which workers are looking at. when I creates multiple sets of tasks, I expected this: Worker1: task1, task4,.... Worker2: task2, task3,... Worker3: task3, task2,... Worker4: task4, task1,... So that each workers works fairly enough But What I actually experiencing is: Worker1: task1, task1, task1,.... Worker2: task2, task2, task2,... Worker3: task3, task3, task3,... Worker4: task4, task4, task4,... Because of this situation, when some workers work hard, the other workers do nothing. I tried to add priority to tasks, and use additional options for celery worker, but it didn't help. here is command lines when i activate celery worker. celery -A django-project worker -n worker01 -Q task_queue -l DEBUG -O fair --prefetch-multiplier 1 --concurrency=3 celery -A django-project worker -n worker02 -Q task_queue -l DEBUG -O fair --prefetch-multiplier 1 … -
How to pass javascript object as URL to django server
I have add_to_cart button in my html. When it is clicked, I want to take selected content and send it to my views.py. I have created an ajax request and I wish to send item object through URL to my views.py. Keep in mind that inside item, toppings and extra are NodeList. And I am using Django. add_to_cart.addEventListener("click", ()=>{ const item = { "item_name": document.querySelector("#itemname").textContent, "quantity" : document.querySelector("#quantity").value, "price" : document.querySelector("#price").dataset.price, "size" : document.querySelector(".size:checked").value, "toppings" : document.querySelectorAll(".topping:checked"), "extra" : document.querySelectorAll(".extra:checked") } const request = new XMLHttpRequest(); request.open('GET', `/cart_item/${item}`, true); request.onload = () => { const data = JSON.parse(request.responseText); if (data.success){ window.location.href = `http://127.0.0.1:8000/cart/cart_item/${item}`; } else{ window.location.href = "http://127.0.0.1:8000/user/login"; } } request.send(); return false; }) in my urls.py urlpatterns = [ path("", views.index, name="cart"), path("cart_item/<item>", views.cart_item, name="cart_item") ] And in views.py def cart_item(request, item): if not request.user.is_authenticated: print("okay") messages.error(request, "Please login first to add to cart.") return JsonResponse({"success": False}) return JsonResponse({"success": True}) Above is what I tried to do, but I get this error Not Found: /cart_item/[object Object] I have also tried to search on Google the correct way to do this but could not find a satisfactory explanation. If you have a solution or an explanation on how to pass … -
Cannot create container for service app: source is not directory
When I run docker-compose -f docker-compose.test.yml up -d I'm getting the below error. Below is how my docker-compose.test.yml file looks like version: "3.8" services: db: image: postgres:12.3 ports: - "5432:5432" env_file: - ./env/.env.dev.db volumes: - postgres_data:/var/lib/postgresql/data/ networks: - backend app: build: context: . dockerfile: ./docker/test-env/app-docker/Dockerfile args: - REACT_APP_API_URL=http://127.0.0.1:8000 volumes: - app_static_files:/app/static - favicon:/app/front_end/app-frontend/build/favicon.ico command: > /bin/sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn -w 4 --bind 0.0.0.0:8000 app.wsgi " env_file: - ./env/.env.dev.db - ./env/.env.dev ports: - "8000:8000" depends_on: - db networks: - backend nginx: build: context: . dockerfile: ./docker/test-env/nginx/Dockerfile ports: - "80:80" - "443:443" volumes: - app_static_files:/project_static_files depends_on: - app networks: - backend volumes: postgres_data: app_static_files: favicon: networks: backend: And this is how my app docker file looks like. # BUILD FRONT END FROM node:12.17.0-alpine3.11 as frontend ARG REACT_APP_API_URL ENV REACT_APP_API_URL $REACT_APP_API_URL WORKDIR /app COPY ./app/front_end/app-frontend/ /app RUN npm install RUN npm run build # APPLICATION FROM python:3.8.3-slim ENV PATH="/app:${PATH}" WORKDIR /app RUN apt-get update && apt-get install -y gcc libxml2-dev libxmlsec1-dev pkg-config \ && apt-get -y install libsasl2-dev libldap2-dev libssl-dev libxmlsec1-openssl python3-dev COPY ./app/ /app COPY --from=frontend /app/build /app/front_end/noa-frontend/ RUN pip install -r production_requirements.txt --no-cache-dir RUN adduser --disabled-password app_user RUN chown -R app_user:app_user /app USER … -
Uploading ppt/pdf file Django
I am trying to upload slides in the Django site. I can see the name of the slide in the database but when I try to display those uploaded slide, only the name of the slides are displayed. I want to upload and display the actual slide to the user. This is the models class Slide(models.Model): Topic = models.CharField(max_length=100) sub_choices = ( ('Data structure','Data structure'), ('Software Engineering', 'Software Engineering'), ('AI', 'AI'), ('Big Data', 'Big Data'), ) Subject = models.CharField(max_length=100, choices=sub_choices, default= False) week = models.IntegerField() lectureSlide = models.FileField() This the view. def uploadSlides(request): if request.method == 'POST': if request.POST.get('Topic') and request.POST.get('week') and request.POST.get('lectureSlide') and request.POST.get('Subject'): post = Slide() post.Topic = request.POST.get('Topic') post.week = request.POST.get('week') post.lectureSlide = request.POST.get('lectureSlide') post.Subject = request.POST.get('Subject') post.save() return redirect('viewlectureslides') return render(request,'uploadlecture.html') HTML part <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Lecture slide</title> </head> <body> <form action="{% url 'uploadSlides' %}" method="post"> {% csrf_token %} Topic: <input type="text" name="Topic"> week: <input type="number" name="week"> <input type="file" name="lectureSlide" value="lectureSlide" id="lectureSlide"> <select name="Subject"> <option value="Data structure">Data structure</option> <option value="Software Engineering">Software E</option> <option value="AI">AI</option> <option value="Big Data">Big Data</option> </select> <input type="Submit" value="Post"> </body> </html> View to show slides def viewAISlides(request): contents = Slide.objects.all() subject = Slide.Subject if subject == 'Software Engineering' and … -
Django and jQuery, how to add a model form in an Ajax call?
I'm trying to create my edit button using an ajax call with jQuery. In other words I have created a button that open a modal form that give me the possibility to modify the data filled. But, actually, I have not been able to insert in my modal a form (ad example using crispy form) and to linked it to the ajax call. I will show my code so understand better. This is my table, with the button in the last column: <tbody> {% for element in elements %} <tr id="element-{{element.id}}"> <td class="elementConto userData" name="conto">{{element.conto}}</td> <td> <button class="btn btn-light p-0" onClick="editUser({{element.id}})" data-toggle="modal" data-target="#myModal"> </button> </td> So after I have created my modal in the following manner: <form id="updateUser"> <div class="modal-body"> <input class="form-control" id="form-id" type="hidden" name="formId"/> <label for="conto">Conto</label> <input class="form-control" id="form-conto" name="formConto"/> </div> </form> After that I have created the ajax call in the following manner: function editUser(id) { if (id) { tr_id = $("#element-" + id); conto = $(tr_id).find(".elementConto").text(); $('#form-id').val(id); $('#form-conto').val(conto); $("form#updateUser").submit(function() { var idInput = $('input[name="formId"]').val(); var contoInput = $('input[name="formConto"]').val(); if (contoInput) { $.ajax({ url: '{% url "crud_ajax_update" %}', data: { 'id': idInput, 'conto : contoInput, }, dataType: 'json', success: function (data) { All works perfectly, but I want … -
Django: Filter on 2 keys from a table
I have a small question: I have a Device model (id,name,..) I have a Sensor help class. A device has multiple sensors (1 to 3). Some sensors are broken. So I made a BrokenSensor class. When a device & sensor are in the class, I don't want to use them not in my calculations. So I thought to do this by a manager in django. But I don't know how I need to filter this in my queryset The table looks like Device_id, Sensor_id 1, 1 1, 2 4, 1 5, 2 class BrokenDeviceManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(brokensensor__exact=device_id, brokensensor__sensor=sensor) This is what I tried.. How can I filter on that table using a filter? -
Ajax won't render calendars on Django
I have this problem and it's killing me since I can't figure out the bug. Actually I have a page where my full calendar gets rendered properly, and I was trying to implement ajax call for showing active and not active calendars. And somehow, when I load the page without the ajax call(selectable.html), all calendars gets rendered, but after I try to switch from 'all' to active/not-active, I get only objects from the server without the proper rendering(the calendars are missing visually). Even tho when I inspect page sources I can see the calendars from the code. I tried with static files and everything, and I just can't find the solution. Basically, the ajax should just change one part of the html, leaving the js and css of full calendar alone. But somehow, it looks im losing the required files for rendering, im not sure. The problem is somewhere in the html page, since the ajax returns the objects properly on the server side. This is my function for calendars : def events(request): now = datetime.now() all_events = Events.objects.all() context = {} if request.is_ajax(): value = request.GET.get('value_from_the_user', None) if value == 'aktivni': context['calendars'] = Calendar.objects.filter(date_valid__gte=now).order_by('calendar_master__group', 'date_valid') print('active') elif value == … -
Docker Compose access postgres host without using "postgres"
So, basically i have this docker-compose.yml config: services: postgres: container_name: youtube_manager_postgres restart: always image: postgres:alpine environment: - POSTGRES_HOST_AUTH_METHOD=trust - POSTGRES_USER=admin - POSTGRES_PASSWORD=qwerty123 - POSTGRES_DB=ytmanager volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "0.0.0.0:5432:5432" django: container_name: youtube_manager_django restart: always build: context: ../ dockerfile: deploy/django/Dockerfile command: sh -c "poetry run python3 manage.py migrate && poetry run python3 manage.py collectstatic --no-input --clear && poetry run uwsgi --ini /etc/uwsgi.ini" ports: - "0.0.0.0:8000:8000" volumes: - staticfiles:/code/static - mediafiles:/code/media depends_on: - postgres My Django's database preferences are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'ytmanager', 'USER': 'admin', 'HOST': '0.0.0.0', 'PASSWORD': 'qwerty123', 'PORT': '5432', } } I wan't to use it in two ways: 1. Running docker-compose up -d postgres and then python3 manage.py runserver (actually, poetry run python3 manage.py runserver but for now it doesn't matter) during development. 2. Running docker-compose up during deployment. For now, it works fine with the 1 option, but when I'm execution docker-compose up I'm getting an error: youtube_manager_django | django.db.utils.OperationalError: could not connect to server: Connection refused youtube_manager_django | Is the server running on host "0.0.0.0" and accepting youtube_manager_django | TCP/IP connections on port 5432? If I'm changing Django database settings this way: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'ytmanager', … -
How to display the parent category as selected in django template?
Here I am trying to update category model but I got problem while displaying the already selected parent category in the template. Update works fine. what I want here is if the category A has parent B then in the edit template B should be displayed as selected parent otherwise there should be option to select one category as a parent from the dropdown list. models class Category(models.Model): parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) slug = models.SlugField(unique=True, max_length=50) title = models.CharField(max_length=255, unique=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) views class EditCategoryView(generic.UpdateView, SuccessMessageMixin): model = Category form_class = CreateCategoryForm template_name = 'edit_category.html' success_url = reverse_lazy('list_categories') slug_url_kwarg = 'slug' success_message = 'Updated Successfully.' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['categories'] = Category.objects.all() return context templates <label for="select" class="">Category Parent</label> <select name="parent" id="exampleSelect" class="form-control"> <option selected value="">Select</option> {% for category in categories %} {% if object.parent_id == category.parent_id %} <option value="{{object.parent_id}}" selected>{{category.parent.title}} </option> {% else %} <option value="{{category.pk}}">{{category.title}}</option> {% endif %} {% endfor %} </select> </div> -
Can I use my own custom names for celery configurations in django?
I am setting the following variables in my settings.py file CELERY_ACCEPT_CONTENT, CELERY_RESULT_BACKEND etc. Is there a way for me to use custom ones e.g MY_CELERY_RESULT_BACKEND? -
I can't create Question in python manage.py shell.(Django)
in models.py i have created class Question and then i want to create Question in models.py shell i am getting an error models.py from django.db import models, migrations class Question(models.Model): author = models.CharField(max_length = 20) title = models.CharField(max_length = 30) body = models.TextField(null = True, blank = True) rating = 0 category = models.CharField(max_length = 10) class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel ( name = 'question', fields = [ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('author', models.CharField(max_length=20)), ('title', models.CharField(max_length = 30)), ('body', models.TextField(null = True, blank = True)), ('rating', 0), ('category', models.CharField(max_length = 10)), ], ), ] shell >>> from f.models import Queston >>> first_question = first_question = Question(author = 'testUser', title = 'some question??', body = 'hey this is question body, category = 'some_category') File "<console>", line 1 first_question = Question(author = 'testUser', title = 'some question??', body = 'hey this is question body, category = 'some_category') -
How to show the category on the frontend with using django tag template?
I am the beginner of writing program and using Django, now I would like to display the category on the front-end. I have created a foreign-key which named “topic” as a category. It is successfully access to the topic(sub-category) and the post (by using pk)by entering URL. Although the URL config is work but I have no idea how to put it on the front-end by using template tag. I would like to create a catalog and when I clicked to the certain catalog then will show these posts which under the specific “topic”. I learned Django by the book “Django for beginners” and “Django for professional” however it does not cover such topic. And I watch online tutorial and I very confused and frustrated. (My Django version is 3.0.0) Thanks for your help :) The Article URL like that http://127.0.0.1:8000/django/1 Topic (FK) (Post PK) My Model from django.db import models from ckeditor.fields import RichTextField class Topic(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, default='self.name') def get_absolute_url(self): return reverse('topic', args=[self.slug]) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey('auth.User', on_delete=models.CASCADE) content = RichTextField() topic = models.ForeignKey(Topic, default=1, on_delete=models.SET_DEFAULT) def __str__(self): return self.title View from django.shortcuts import render from … -
Django 3 Using tags in an SVG-file
I am trying to use SVG icons in my Django-project and am having difficulties with custom fonts. This is (part of) my SVG-code: <defs> <style type="text/css"> @font-face { font-family: AR JULIAN; src: url('../fonts/ARJULIAN.ttf'); } </style> </defs> <rect width="600" height="600" x="0" y="0" fill="url(#MercuryGradient)" ></rect> <text x="50%" y="55%" dominant-baseline="middle" text-anchor="middle" font-family="AR JULIAN, serif" font-size="600" font-weight="bold" fill="rgba(255, 255, 240, 1)" >M</text> In this case the SVG displays the letter "M" in the font AR JULIAN. When I open the svg-file in the browser it does just that. But when I place it in my base.html it uses the standard browser-font. I believe the problem is in the line: src: url('../fonts/ARJULIAN.ttf'); I have tried replacing this line with a template tag as in: src: url("{% static 'fonts/ARJULIAN.ttf' %}") That did not work. And adding {% load static %} to the top of the page gave me an error. Any help is aprreciated. -
Django aggregation subquery in aggregation
What I'm trying to do is create an aggregation from multiple models, but I'm having trouble getting it to work as a single query. For example, if I have two models like: class DailyUsers(model.Model): date = models.DateField() shop_id = models.IntegerField() users = models.IntegerField() class DailySpend(model.Model): date = models.DateField() shop_id = models.IntegerField() amount = models.IntegerField() I can create the following aggregation: total_spend = models.DailySpend.objects.filter( date__range=["2020-01-01", "2020-01-05"], shop_id__in=[1, 2, 3], ).aggregate(total_spend=Coalesce(Sum("amount"), 0)) total_users = models.DailyUsers.objects.filter( date__range=["2020-01-01", "2020-01-05"], shop_id__in=[1, 2, 3], ).aggregate(total_users=Coalesce(Sum("users"), 0)) total_users["total_spend"] = total_spend["total_spend"] >> {"total_users": int, "total_spend": int} However, this uses two queries, and I'm wondering if I can go to a single query with Subquery? I've looked at the docs, as well as other related questions, but they seem to rely on foreign key relationships, which don't exist in my case. Is it still possible to reduce this to a single query? -
Add internationalization to Django URL with prefix of the language coming after the added prefix
I know how to add a general prefix to all urls thanks to this answer https://stackoverflow.com/a/54364454/2219080. But I want to have urls where we have the added prefix always coming before the language prefix (added by i18n_patterns ). from django.urls import include, path, re_path from django.views.generic import TemplateView from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path("grappelli/", include("grappelli.urls")), # grappelli URLS path("admin/doc/", include("django.contrib.admindocs.urls")), path("admin/", admin.site.urls), path("pages/", include("django.contrib.flatpages.urls")), re_path(r"^api-auth/", include("rest_framework.urls")), re_path(r"^accounts/", include("allauth.urls")), re_path(r"^indicators/", include("indicators.urls", namespace="indicators")), path("", TemplateView.as_view(template_name="landing.html"), name="landing"), ] if settings.URL_PREFIX: urlpatterns = [path(r"{}".format(settings.URL_PREFIX), include(urlpatterns))] E.g: Having this code above, I would like to have an url https://example.com/mycuteprefix/en/indicators/ instead of the usual https://example.com/en/mycuteprefix/indicators/. Whenever I apply internationalization to the first urlpatterns I get an error. For example if I try this one bellow: urlpatterns = [ path("grappelli/", include("grappelli.urls")), # grappelli URLS path("admin/doc/", include("django.contrib.admindocs.urls")), path("admin/", admin.site.urls), path("pages/", include("django.contrib.flatpages.urls")), re_path(r"^api-auth/", include("rest_framework.urls")), re_path(r"^accounts/", include("allauth.urls")), re_path(r"^indicators/", include("indicators.urls", namespace="indicators")), ] urlpatterns += i18n_patterns( path("", TemplateView.as_view(template_name="landing.html"), name="landing"), ) if settings.URL_PREFIX: urlpatterns = [path(r"{}".format(settings.URL_PREFIX), include(urlpatterns))] I have this error: urlpatterns = [path(r"{}".format(settings.URL_PREFIX), include(urlpatterns))] File "/home/username/.virtualenvs/roject/lib/python3.5/site-packages/django/urls/conf.py", line 52, in include 'Using i18n_patterns in an included URLconf is not allowed.' django.core.exceptions.ImproperlyConfigured: Using i18n_patterns in an included URLconf is not allowed. How to achieve that ? -
Django microservices
I am working on a web project which will be developed using django, django framework and python. the project will follow microservices architecture. But I am unable to find any resource on how will I implement django-microservice to the project. So I need advice on how can I implement django-microservice to my django project? -
django create abstractbaseuser model, error
I'm making my personal project. I'm trying to coding signup function. but not work. createuser is doing right. but when i runserver, and go signup.html page, input value, always same error. what is wrong with my code? model.py from django.contrib.auth.models import(BaseUserManager, AbstractBaseUser, PermissionsMixin) from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, username, userid, company, companycode, password=None): if not username: raise ValueError(_('Users must have an name!')) user = self.User( username=username, userid = userid, company= company, companycode = companycode, ) user.set_password(password) user.save() return user def create_superuser(self, username, userid, company, companycode, password): user = self.create_user( username=username, userid = userid, company = company, companycode = companycode, password=password, ) user.is_active = True user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=10, unique=True, verbose_name="이름") userid = models.CharField(max_length=100, unique=True, verbose_name="아이디") company = models.CharField(max_length=10, verbose_name="회사") companycode = models.CharField(max_length=100, verbose_name="회사코드") created_date = models.DateTimeField(auto_now_add=True, verbose_name="생성날짜") is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) class Meta: db_table = 'user' objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['userid', 'company', 'companycode'] def __str__(self): return self.username def get_full_name(self): return self.username def get_short_name(self): return self.username @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All … -
Django custom LoginView and AuthenticationForm won't process POST
I extended the AuthenticationForm and made a custom login form LoginForm. And for future customization, I extended the LoginView as CustomLogin. And added it as view in the urls.py for accounts/login/. The custom form renders. But when I log in, it doesn't do anything. It just shows the login form again with Your username and password didn't match. Please try again message. The username and password are correct though. What am I missing? Are there any good examples or documentation on extending the LoginView properly (preferable if the implementation is not a class-based view)? Here are my codes. /accounts/forms.py from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django import forms class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) username = forms.CharField( widget=forms.TextInput( attrs={ 'class': 'input', 'placeholder' :'bearclaw' } )) password = forms.CharField( widget=forms.PasswordInput( attrs={ 'class': 'input', 'placeholder': '#@$k0eldp' } )) /accounts/models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): email = models.EmailField(unique=True) def __str__(self): return self.username /accounts/urls.py from django.urls import path from . import views from .forms import LoginForm urlpatterns = [ path('login/', views.CustomLogin.as_view(), name='login'), path('dashboard/', views.dashboard, name='dashboard'), ] /project/urls.py urlpatterns = [ path('', include('core.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('books/', include('books.urls')) ] /accounts/views.py from django.contrib.auth.views import LoginView … -
How do I assign the testcases reviewer
I configed the email settings and could receive registration email, forgot-password email etc. successfully. But, I can not receive the review notification email when I input reviewer email. I still do not find any solution in the userguide. So How do I fix this?