Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Comment mettre à jour mon stock lorsque je modifie une vente
I am trying to update my inventory after modifying a sale. When I register a new sale, the code works perfectly but when I make a modification on the quantity sold, the stock update is not done Please help me immediately. Excuse me for my crooked English, I am French speaking lol. here is my code. Models.py class Sale(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, verbose_name="Produit") client = models.ForeignKey( Customers, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Client") commercial = models.ForeignKey( CustomUser, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Commercial(e)") sale_quantity = models.PositiveIntegerField( default=None, blank=True, null=True, verbose_name="Quantité vendu") class Meta: verbose_name = 'Vente' verbose_name_plural = 'Ventes' ordering = ['-id'] def __str__(self): return self.product.item_name View.py # SALE CREATE @login_required(login_url="/login/") def sale_create(request): form = SaleCreateForm(request.POST or None) template_name = "moonvisions/add_sale.html" if form.is_valid(): sale = form.save() product = sale.product product.quantity -= sale.sale_quantity product.save() messages.success(request, 'Enregistré avec succès !') return redirect('/marketing/sale_list') context = { "form": form, } return render(request, template_name, context) # UPDATE SALE @login_required(login_url="/login/") def update_sale(request, id): # command = Stock.objects.all() sale = Sale.objects.get(pk=id) form = SaleCreateForm(instance=sale) template_name = 'moonvisions/add_sale.html' if request.method == 'POST': form = SaleCreateForm(request.POST, instance=sale) if form.is_valid(): instance = form.save(commit=False) instance.save( messages.info(request, 'Modifié avec succès !') return redirect('/marketing/sale_list') context = {'form': form} return render(request, template_name, context) -
Button in bootstrap form doesn't submit text from imput
I'm exercising an easy project in Django. I have a problem with the bootstrap button. The button generally works, because it gets over csrf_token to my home view in the request object but it doesn't submit data from my input, and here is my question. Why? My form: <form class="d-flex" action="{% url 'home' %}" method="post"> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="your new task" aria-label="Search"> <button value="Send" type="submit" class="btn btn-outline-secondary" name="no_dalej">Add to list</button> </form> The request object looks like this: <QueryDict: {'csrfmiddlewaretoken': ['fJNmnuulcaNB7SETFNagSFfsfiynOCwyw0LMoALPSlEcYFnxqIFMxPm7VliUylwm'], 'no_dalej': ['']}> Any ideas? -
Postman POST request returning None in django
I'm trying to send POST requests using postman to an API in a django server. The API is an APIView : class LoginView(APIView): template_name = 'login.html' from_class = LoginForm def post(self, request, format=None): data = request.data username = data.get('username', None) password = data.get('password', None) print(username) and here is the postman request in the joint image The problem is I'm always getting None username and password. Please if you can spot the problem can you guide me. -
Django objection creation failing due to FOREIGN KEY constraint failure (IntegrityError )
My website has a comment section where user can leave comments on a product . The comments on the product page will be stored in a model called 'ProductReview'. Here is the code for the model : class ProductReview(models.Model): product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE) name = models.CharField(blank=True,max_length=20) stars = models.IntegerField() content = models.TextField(blank=True) date_added = models.DateTimeField(auto_now_add=True) created_by = models.OneToOneField(User, on_delete=models.CASCADE) Now the view associated with the model are as follows Note:The entire view isnt relevant to the error. The part relevant to the saving comment is the second 'request.POST' which I have denoted with a python comment using # : def product(request, category_slug, product_slug): cart = Cart(request) product = get_object_or_404(Product, category__slug=category_slug, slug=product_slug) if request.method == 'POST': form = AddToCartForm(request.POST) if form.is_valid(): quantity = form.cleaned_data['quantity'] cart.add(product_id=product.id, quantity=quantity, update_quantity=False) messages.success(request, 'The product was added to the cart') return redirect('product', category_slug=category_slug, product_slug=product_slug) similar_products = list(product.category.products.exclude(id=product.id)) # this part is for saving of the user comments to productreview model if request.method == 'POST': stars = request.POST.get('stars', 3) content = request.POST.get('content', '') name = request.POST.get('name', '') created_by = request.user review = ProductReview.objects.create(product=product, name=name, stars=stars, content=content, created_by=created_by) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # this marks the end of the code relevant to saving the user comment if len(similar_products) >= … -
Passing Editable Fields as validated_data method of Django-Rest-Framework Serializer
I'm writing a contacts service in Django-REST-Framework. I have a Contact Model and a PhoneNumber Model which has a foreignKey field that shows which contact does it belong to. Here are my models: class ContactModel(models.Model): firstname = models.CharField(max_length=50, blank=False) lastname = models.CharField(max_length=50, blank=False) class PhoneNumber(BaseModel): country_code = models.CharField(max_length=VERY_SHORT_STRING_SIZE, blank=False) phone_number = models.CharField(max_length=SHORT_STRING_SIZE, blank=False, null=False) label = models.CharField(max_length=NORMAL_STRING_SIZE, blank=True, default='') related_contact = models.ForeignKey(to='ContactModel', on_delete=models.CASCADE) I want to make a CRUD api for my Contacts. I have a ModelViewSet and a ModelSerializer for that. serializer codes is as follows: class ContactSerializer(serializers.ModelSerializer): phonenumber_set = PhoneSerializer(many=True, required=False) class Meta: model = ContactModel fields = '__all__' class PhoneSerializer(serializers.ModelSerializer): class Meta: model = PhoneNumber fields = ['id', 'country_code', 'phone_number', 'label'] As it's been specified here I should override update and create methods in order to update and create PhoneNumbers of my Contact. The Problem is that if I override those functions I have to use them like this: class ContactSerializer(serializers.ModelSerializer): ... def create(self, validated_data): # some code for creating both PhoneNumber and Contact def update(self, instance, validated_data): # some code for updating both PhoneNumber and Contact and unfortunatly, 'validated_data' argument doesn't bring the 'id' of my PhoneNumber objects, beacause 'id' fields are AutoFields and AutoFields will … -
Data retrieve from database to template in Django as a popup window
I am developing a form that can retrieve all the lists of data from database to popup window in Django template. I want to select a specific record and display it in the html file that popup window is contained, and add a button to redirect to edit the values of that record. -
Django gets 'None' from POST-request
I sending info by fetch to my django server, but django gets None instead of values in the object POST-request GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest; fetch(`http://127.0.0.1:8000/computerAnswer/`,{ method:'POST', body:JSON.stringify({value: 'value', deleted:[], answer:'computerAnswer'}) }).then((response) => { return response.json(); }) .then((json) => { console.log(json.msg); }).catch((error) => { console.log("now is " + error); }); Views.py @csrf_exempt def computer_answer(request): print(request.POST.get('value')) print(request.POST.get('deleted')) print(request.POST.get('answer')) data = {'msg': ''} value = 0 deleted_cities = 0 answer_of_computer = 0 if request.method == 'POST': value = request.POST.get('value') deleted_cities = request.POST.get('deleted') answer_of_computer = request.POST.get('answer') if value == '' or value is None: data['msg'] = '-1' return JsonResponse(data) data['msg'] = citiesGame.game(value, deleted_cities, answer_of_computer) return JsonResponse(data) when print is triggrerd, the None is printed. This request goes from app on React-native. The views.py works for sure if you make a request from host on which the real backend is located, but from the application it doesn't work(as in "about:blank" chrome) -
Why RelatedObjectDoesNotExist is thrown when trying to add an entery from the django admin?
In my models, I have the ImageAlbum model and Image model. In the Image model, I have a ForeignKey field to the ImageAlbum. This code is actually recommended from this article. class ImageAlbum(models.Model): def __str__(self): return str(self.pk) class Image(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to=get_upload_path) default = models.BooleanField(default=False) thumbnail = models.ImageField(upload_to=get_thumbnail_path, default='default/default_thumbnail.jpg') album = models.ForeignKey(ImageAlbum, on_delete=models.CASCADE) I registered the models in the admin and the Image form looks like that: And after I hit save, the following exception occurs: -
Celery workers multiply infinitely with multiprocessing Billiard
Good day to you. I just recently started to delve into the celery and ran into a problem. I am trying to asynchronously check the proxy by running 8 threads inside one task, which is executed every 3 hours. I would like to use one worker with 8 child processes for this, or 8 workers with one process on each. But now I put a lot of workers after several iterations of the script and only one thing helps to kill all the processes of the select. How to properly configure the celery tasks or my script in this case? Logs file looks like: [2021-04-27 16:50:00,285: WARNING/ForkPoolWorker-6] Started at 2021-04-27 16:50:00.285149 [2021-04-27 16:50:00,289: WARNING/ForkPoolWorker-6] CREATE POOL 8 processes [2021-04-27 16:50:00,320: WARNING/ForkPoolWorker-6:1] START PROCESS NUMBER 0 [2021-04-27 16:50:00,321: WARNING/ForkPoolWorker-6:2] START PROCESS NUMBER 1 [2021-04-27 16:50:00,321: WARNING/ForkPoolWorker-6:3] START PROCESS NUMBER 2 [2021-04-27 16:50:00,321: WARNING/ForkPoolWorker-6:4] START PROCESS NUMBER 3 [2021-04-27 16:50:00,322: WARNING/ForkPoolWorker-6:5] START PROCESS NUMBER 4 [2021-04-27 16:50:00,323: WARNING/ForkPoolWorker-6:6] START PROCESS NUMBER 5 [2021-04-27 16:50:00,324: WARNING/ForkPoolWorker-6:7] START PROCESS NUMBER 6 [2021-04-27 16:50:00,325: WARNING/ForkPoolWorker-6:8] START PROCESS NUMBER 7 [2021-04-27 16:50:00,468: WARNING/ForkPoolWorker-6:5] CON ERR: 94.154.158.234:12333, 407 [2021-04-27 16:50:00,720: WARNING/ForkPoolWorker-6:4] CON ERR: 173.254.206.36:80, 404 [2021-04-27 16:50:00,777: WARNING/ForkPoolWorker-6:1] CON ERR: 54.213.157.85:80, 404 [2021-04-27 16:50:00,794: WARNING/ForkPoolWorker-6:3] OK: 159.8.114.34:8123, … -
I am asking for help in my django rest framework project with addition features post like, unlike, user activity endpoint
What I need to achieve. *Post like, Post unlike, analytics how many likes were made from some specific day to day, API should return aggregated by day. User activity an endpoint that will show when user was login last time and when he made a last request to the server *. What I already achieve. Using two models User, Post, user login, register, and post creation. Implemented JWT token authentication My code in app 'api': models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) post_like = models.ManyToManyField(User) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title serializers.py from rest_framework import serializers from .models import Post class PostSerialization(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'url', 'content', 'title', 'date_posted', 'author'] views.py from rest_framework import viewsets, permissions from .models import Post from .serializations import PostSerialization class PostSetView(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerialization permission_classes = [permissions.IsAuthenticated] urls.py from django.urls import path, include from rest_framework import routers from .views import PostSetView router = routers.DefaultRouter() router.register(r'posts/', PostSetView) urlpatterns = [ path('', include(router.urls)) ] In root directory 'network_api': settings.py """ Django settings for network_api project. Generated by 'django-admin startproject' using … -
query a manytomany realted field
I have a model like the following: GRN Model: class GrnItems(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE) item_quantity = models.IntegerField(default=0) item_price = models.IntegerField(default=0) label_name = models.CharField(max_length=25, blank=True, null=True) class Grn(models.Model): reference_no = models.CharField(max_length=500, default=0) inward_date = models.DateTimeField(blank=True, null=True) items = models.ManyToManyField(GrnItems) How can I query the GrnItems to get item_quantity which has product = 5 and connected to grn = 103? -
Why does not django send emails?
I have connected my website to database in sql server DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'name', 'USER': 'user', 'PASSWORD': '', 'HOST': 'DESKTOP-\SQLEXPRESS', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } And copied the code for password reset EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'n@gmail.com' EMAIL_HOST_PASSWORD = '' Now every page is working, but I am not receiving any letters. However, when a had embeded django database everything was working(a month ago). May it be connected with the microsoft database or the problem is not in that? -
Write console log to a file in Django
I have following configuration for logging in my project. I don't have any clue where all the log is writing. I have to check authentication failure logs, But I don't know where to check. Event syslog is not updating anything. Please help me to push all console logs to a file. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, 'stream_to_console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler' }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'django_auth_ldap': { 'handlers': ['stream_to_console'], 'level': 'DEBUG', 'propagate': True, }, } } -
Not able to access data of field ID with formControlName `ids` or `ID` in angular
I just started leaning Angular with Django as backend and i am facing this problem when i add formControlName="ID" or formControlName="ids" in mypage.component.html it din't send data to backend but when i change formControlName to other or anything it sends data is there any reserved keywords in angular? here is my mypage.component.html ID field code <div class="form-group row"> <label class="col-sm-3 col-form-label">ID</label> <div class="col-sm-8"> <input type="text" formControlName="material_id" class="form-control" id="Adtitle" placeholder="Round,Rectangle etc."> <small class="form-text text-muted"> Entering the ID if applicable </small> </div> </div> and this is in my mypage.component.ts this.createPostForm = new FormGroup({ material_id : new FormControl(''), }); my code is working fine when i put material_id or any other words but when i put ID or ids it din't get data from form. -
Not Found: /1/${url}data
I want to show a list of question on my quiz.html templates... Here is my views.py def quiz_data_view(request,pk): quiz = Quiz.objects.get(pk=pk) questions = [] for q in quiz.get_questions(): answers = [] for a in q.get_answers(): answers.append(a.text) questions.append({str(q):answers}) return JsonResponse({ 'data' : questions, 'time' : quiz.time, }) Here is my js file...in my js file i used ajax... const url = window.location.href const quizBox = document.getElementById('quiz-box') let data $.ajax({ type: 'GET', url: "${url}data", success : function(response){ // console.log(response) data = response.data data.forEach(el=>{ for(const [question,answers] of Object.entries(el)){ quizBox.innerHTML +=` <hr> <div class="mb-2"> <b> ${question}</b> </div> ` } }); }, error : function(error){ console.log(error) } }) here is my urls.py from django.urls import path from .views import ( QuizListView,quiz_view,quiz_data_view ) app_name='quizes' urlpatterns = [ path('',QuizListView.as_view(),name='main-view'), path('<int:pk>/',quiz_view,name='quiz-view'), path('<int:pk>/data/',quiz_data_view,name='quiz-data-view'), ] Here is my models.py from django.db import models # Create your models here. DIFF_CHOICE = ( ('easy','easy'), ('medium','medium'), ('hard','hard'), ) class Quiz(models.Model): name = models.CharField(max_length=120) topic = models.CharField(max_length=120) number_of_question = models.IntegerField() time = models.IntegerField(help_text="Duration in Minutes") required_score_to_pass = models.IntegerField(help_text="Required Score to Pass in %") difficulty = models.CharField(max_length=6,choices=DIFF_CHOICE) def __str__(self): return f"{self.name}-{self.topic}" def get_questions(self): self.question_set.all()[:self.number_of_question] class Meta: verbose_name_plural = 'Quizes' and here is my quiz.html....and here i want to show my question list {% extends "base.html" … -
How can I reuse a DRF class-based views POST method?
Now I want to reuse the post method of BundleList. Either I find out the absolute URL and use requests.post(URL) to send a request. The 2nd way is to reuse by return BundleList.as_view()(request) in a view function. But I can't set request.data = data. Request data is immutable. When I try to use url = reverse_lazy(BundleList.as_view(), request=request) print(f"{url = }") It just gives me: NoReverseMatch at /generateSampleBundle/ Reverse for 'my_app.views.BundleList' not found. 'my_app.views.BundleList' is not a valid view function or pattern name. The BundleList is a class-based view with get and post method. drfurlpatterns = [ # DRF URL endpoints path('bundles/', views.BundleList.as_view()), ] Can anyone help me out? -
why am I not able to see data with older date in my django project?
I have written a small views through Django rest framework to populate database table data in between two different date range. Below is the code snippet: from rest_framework.generics import ListAPIView from rest_framework import permissions from .models import Revenue from .serializers import DataListSerializers import datetime class DataListView(ListAPIView): serializer_class = DataListSerializers pagination_class = None queryset = Revenue.objects.all() permission_classes = [permissions.AllowAny] def get_queryset(self): start_date = datetime.date.today() end_date = start_date + datetime.timedelta(days=6) time_filter = self.queryset.filter(date__range=(start_date, end_date)) ser = DataListSerializers(time_filter, many=True).data return ser After this I have manually entered the data in the database through admin page. So, those data are of current date. Now, I imported a CSV file in the SQLite which has data from the year 2017, and the file was uploaded successfully. There after when I refreshed the admin page, it crashed and I could see error as shown below: return datetime.date(*map(int, val.split(b"-"))) ValueError: day is out of range for month With this I assume that the over ridden logic written in the 'get_queryset' method is not optimal. Please suggest the optimal solution for the use case. Thank you. -
Chrome extension requests with CSRF token
I have an extension that makes requests through the background page to my django server. I need to include the CSRF token for any POST requests, however when I do that I still get 403 error, because there is no Referer header in the request. Now I know the Referer header is set automatically by the browser, but in case of extension background page it is not set at all. There are two workarounds for this: using CSRF exempt on django or blocking the request to set the Referer header in the extension (using webRequestBlocking permissions), but I don't want to use either of them. Is there anything else I can do to resolve this either on client or server side? -
How do I overcome this? [closed]
Used to have a project which has been completed and deleted from my machine. Anytime I start a new project and run the server, the urls references the urls in the old project which has been deleted throwing an error in my current project. How do I fix this? -
I am having problem with the django and constantly getting error i.e. "local variable 'form' referenced before assignment"
I am having this error "local variable 'form' referenced before assignment". I am not sure what's wrong with the code . The form does not load and the if the form is assigned to different variable and used then the page loaded but the form does not load The model class from django.db.models.aggregates import Max from django.db.models.base import Model from django.db.models.fields import CharField # Create your models here. class Work(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='workimages/') summary =models.CharField(max_length=100) def __str__(self): return self.name class Contact(models.Model): name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=50, null=True) message = models.CharField(max_length=1000, null= True) def __str__(self): return self.name the view fucntion of the problem is posted below from .models import * from .forms import * # Create your views here. def home (request): work = Work.objects.all() if request.method == "POST": form = Contactform(request.POST or None) if form.is_valid(): form.save() context ={ 'work':work,'form':form,} return render(request, 'mysite/index.html',context) The template <form method="POST"> {% csrf_token %} <div class="row margin-bottom-small center-xs"> <div class="col-md padding-small"> {{ form }} </div> <div class="col-md padding-small"> <!-- <textarea placeholder="Your Message" name="" rows="8" class="margin-bottom-small"></textarea> --> <input type="submit" value="Submit"> </div> </div> </form> This default django forms in used bu from django import forms from django.db.models import fields from django.forms.forms import … -
pass custom queryset to django rest framework nested serializer
I have serializers in the following format: CounterPartyCompanySerializer: class CounterPartyCompanySerializer(serializers.ModelSerializer): class Meta: model = ClientCompany fields = ( "id", "company_name", "address_line1", ) extra_kwargs = { "id": { "read_only": False, "required": False, }, } CounterPartySerializer: class CounterPartySerializer(serializers.ModelSerializer): company = CounterPartyCompanySerializer() class Meta: model = Client fields = ( "id", "company", "client_name", ) extra_kwargs = { "id": { "read_only": False, "required": False, }, } and GiftAndEntertainmentSerializer: class GiftAndEntertainmentSerializer(serializers.ModelSerializer): counter_party = CounterPartySerializer() class Meta: model = GiftAndEntertainment fields = ( "id", "gift_type", "receipt_type", "counter_party", "value", ) Case-I :: It works when I do the following: result_list = GiftAndEntertainment.objects.all() serializer = GiftAndEntertainmentSerializer( result_list, many=True, context={"request": request} ) But, it doesn't work when I pass the custom queryset like: result_list = GiftAndEntertainment.objects.values( "gift_type", "receipt_type", "counter_party", "value" ).annotate( total=ExpressionWrapper(Sum("value"), output_field=DecimalField()) ) serializer = GiftAndEntertainmentSerializer( result_list, many=True, context={"request": request} ) Here, "gift_type","receipt_type" and "counter_party" are ForeignKey mapped entities and the queryset passes the primary-key id of these entities. I thought the serializer will convert the pk to its corresponding entities like its doing in the case-I but that is not happening automatically. Any help here would save my life. I have spent an entire day trying to achieve this but failed every-single time. -
Django filters for a ManyToMany field
I'm trying to build a filtering system for a list of posts. All the posts have an author/user and an account where they are posted. The post model has 2 ForeignKeys with the Author/User model and with Account model. The Author/User model has a ManyToMany relationship with the List model (the list model is like tags, categories, etc. for the users, and a user can belong to multiple lists at the same time). I want to filter the posts by lists, for example, I want to filter all the posts that belong to users who belong to the "Cars" list or the "Cars and Family" list at the same time (here I'm trying to say that I'd like to filter posts by one list or more, like to show all the posts that belong to users who belong to "Cars" list, or to "Cars and Family" lists). I'm not sure how can I filter a QuerySet of a model by a ManyToMany field of a ForeignKey field. I'll put my models, filters, views, and HTML to show what I've made so far. models.py # List model represents the lists that will hold the authors/users grouped and will be used for … -
EOF while scanning triple-quoted string literal while creating a TextField value for a django model. (how to correctly concat strings)
this is the model i am creating: class Notification(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="notifications") text = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) The "text" field is giving me issues. This is how i am trying to create an instance: Notification.objects.create(user=instance.post.owner, text=instanse.user.username + ' liked your post') "instance.user.username" is a CharField. What is the correct way of adding that to a string? -
contents in <form> tag is not displayed in server
I'm learning django framework currently. Everything went well till last night. From this morning the contents inside the <form> tag is not being displayed once the page is rendered through django code. Till last night it was working good and I didn't manipulate the code. I tried restarting the server many times, it didn't help. I opened the .html externally (not from django), it works fine, but not through django. Part of html code goes as, <div class="w3-top"> <div class="w3-bar w3-white w3-padding w3-card" style="letter-spacing:4px;"> <a href="#home" class="w3-bar-item w3-button">A simple TO-DO list using Django</a> <!-- Right-sided navbar links. Hide them on small screens --> <div class="w3-right w3-hide-small"> <a href="#about" class="w3-bar-item w3-button">About</a> <a href="#contact" class="w3-bar-item w3-button">Contact</a> </div> <div class="w3-right w3-hide-small"> <form action="enter/login"> <input type="submit" class="w3-bar-item w3-button" value="Login"/> </form> </div> </div> </div> and the result of this is, The Login button is missing which is inside the form, I found the Login button till last night and I can't find this from this morning. This is a single example and I have 3 <form> tags in my page and nothing is displayed when I run this in the localhost server. But externally this works good. -
Django urls.py update from using url to path
I am importing and upgrading a legacy Django app into my Django 3.2 project. The old app used Django 1.x url, I need to upgrade, using path instead. Here is the old code: urlpatterns = patterns( 'blog.views', url(r'^$', 'blogs', name='blogs_url'), url(r'^new-post$', 'new_blog_post', name='new_blog_post_url'), url(r'^upload-image$', 'upload_image', name='upload_image_url'), url(r'^uploaded-images$', 'uploaded_images', name='uploaded_images_url'), url(r'^edit/(\d+)/([^/]+)$', 'edit_blog_post', name='edit_blog_post_url'), url(r'^([^/]+)$', 'blog', name='blog_url'), url(r'^([^/]+)/(\d+)/([^/]+)$', 'blog_post', name='blog_post_url'), ) urlpatterns += patterns('', url(r'^(?P<blog_slug>[^/]+)/rss$', AllPostsFeed(), name='blog_rss_url')) Here is my changed code: urlpatterns = [ path('', blogs, name='blogs_url'), path('new-post', new_blog_post, name='new_blog_post_url'), path('upload-image', upload_image, name='upload_image_url'), path('uploaded-images', uploaded_images, name='uploaded_images_url'), path('edit/(\d+)/([^/]+)', edit_blog_post, name='edit_blog_post_url'), path('([^/]+)', blog, name='blog_url'), path('([^/]+)/(\d+)/([^/]+)', blog_post, name='blog_post_url'), path('(<slug:blog_slug>[^/]+)/rss', AllPostsFeed(), name='blog_rss_url') ] Although, I have removed most of the regex patterns (at least those starting or terminating strings, there are still remaining (e.g. from the edit/* route onward). What would be the correct parameter formulation for these (potentially incorrect) lines?: path('edit/(\d+)/([^/]+)', edit_blog_post, name='edit_blog_post_url'), path('([^/]+)', blog, name='blog_url'), path('([^/]+)/(\d+)/([^/]+)', blog_post, name='blog_post_url'), path('(<slug:blog_slug>[^/]+)/rss', AllPostsFeed(), name='blog_rss_url')