Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Project : 'dict' object has no attribute 'code'
I retrieved a list of products via an API, then I use django-shopping-cart to generate my cart But I have an error 'dict' object has no attribute 'code'. the error is at this line : if product.code == code ,while there is indeed the code attribute in the dict def cart_add(request,code): url='http://myapi/Product/GetProducts' x=requests.get(url) content=x.json() all_products=content['products'] for product in all_products : if product.code == code : cart=Cart(request) cart.add(product = product.code) return render(request,'shop/deatil.html') At the API level, the dictionary specification is of the form: dict = { "products": [ { "code": "4mlk2", "designation": "kaka" }, { "code": "455ml", "designation": "koko" }, .... ] } -
Django button click gets triggered but not updating model
I tried to upload the image several times, for some reason it just won't upload. I will explain in detail - This table is on my django template.It will display data from a model called "WorkOut". This page has a form above this table for manual data input. Three fields in the table are going to be dynamic, that is where the issue is. In the picture you will see the "Start Time" field that says none. I want to fill this field with a button click. Idea is to click the button, that will trigger a views.py function and that will update the model and then display on this page. Once I do this successfully I will add the end time and do some calculations after. I added a small form in the for loop to generate the button- <td> <form method="get"> <input type="submit" class="btn" value="Start Time" name="start_time"> </form> </td> Here is the views function that it is suppose to trigger- def index_2(request): if(request.GET.get('start_time')): time=datetime.now().strftime('%H:%M:%S') WorkOut.objects.update(start=time) products=WorkOut.objects.all() context={'products': products} return render(request, 'myapp/index.html', context) This page is the index and no separate url for the button click. I don't think I need one. Here is the main index views: def … -
getting error with _set in Django Query-Set, object has no attribute
I use _set to make ManyToMany relationship between customer and Service but endup having Error: AttributeError at /customer/1/ 'carOwner' object has no attribute 'serviceOrderX_get' Is there anyone who want to help me.. models.py ... class carOwner(models.Model): name_X = models.CharField( max_length=150, null=True) email_X = models.CharField( max_length=150, null=True) phoneNo_X =models.CharField( max_length=150, null=True) def __str__(self): return self.name_X class serviceOrderX(models.Model): CATEGORES = (...) carName_X = models.CharField( max_length=150, null=True) carNO_X = models.CharField( max_length=150, null=True) carOwner_X = models.ManyToManyField(carOwner) catagores_X = models.CharField(max_length=200,null=True,choices=CATEGORES) price_X = models.IntegerField( null=True) service_X = models.ManyToManyField(orderService) def __str__(self): return str(f'{self.carName_X} , {self.carNO_X}') views.py ... def CustomerX(request , pk): customersX = carOwner.objects.get(id=pk) cuter = customersX.serviceOrderX_get.all() contX = { 'customer' : cuter , } return render(request, 'customer.html' , contX) -
Django HttResponse has no attr status_code, but docs have :)
I'm using default django httpresponse, like this: return HttpResponse("Validation Error", status_code=400) And i got exception like "HttpResponse has no attribute status_code". But in the docs we have info about this attr (docs link) If we look at source code, we can see: class HttpResponse(HttpResponseBase): ... def __init__(self, content=b'', *args, **kwargs): super().__init__(*args, **kwargs) # Content is a bytestring. See the `content` property methods. self.content = content ... Not explict usage of status_code, let's look parent's init: class HttpResponseBase: def __init__(self, content_type=None, status=None, reason=None, charset=None, headers=None): ... if status is not None: try: self.status_code = int(status) except (ValueError, TypeError): raise TypeError('HTTP status code must be an integer.') if not 100 <= self.status_code <= 599: raise ValueError('HTTP status code must be an integer from 100 to 599.') self._reason_phrase = reason And here in params we can see status. If we back to my example, correct version of this looks: return HttpResponse("Validation Error", status=400) And my question is: "Is there place in docs where was talk about status of HttpResponse and if not, how i can make issue or bring this info to django-developers?" The way I see it, it's not obvious enough. -
Unable to login to Django admin with Custom superuser
I am developing a school management system where I am creating custom user by extending User model using AbstractUser. I am able to create the superuser using custom user model but whenever I am trying to login using custom superuser account Django gives the following error Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. This is my customUser model class CustomUser(AbstractUser): ADMIN = "1" STAFF = "2" STUDENT = "3" Email_to_User_Type_Map = { 'admin': ADMIN, 'staff': STAFF, 'student': STUDENT } user_type_data = ((ADMIN, 'Admin'), (STAFF, 'Staff'), (STUDENT, 'Student')) user_type = models.CharField( default=1, choices=user_type_data, max_length=10) Below function represents creating custom user function def create_customUser(username, email, password, email_status): new_user = CustomUser() new_user.username = username new_user.email = email new_user.password = password if email_status == "staff" or email_status == "student": new_user.is_staff = True elif email_status == "admin": new_user.is_staff = True new_user.is_superuser = True new_user.is_active = True new_user.save() please help -
TypeError at /form Field 'roof_age' expected a number but got ('1',)
TypeError at /form Field 'roof_age' expected a number but got ('1',). My model.py file from django.db import models # Create your models here. class Details(models.Model): name = models.CharField(max_length=25) roof_age = models.IntegerField() email = models.EmailField() phone = models.IntegerField() address = models.TextField(max_length=100) monthly_bill = models.IntegerField() HOA = models.BooleanField(default=True) battery = models.BooleanField(default=True) foundation = models.BooleanField(default=True) roof_type = models.CharField(max_length=20) availability = models.DateTimeField() bill = models.FileField(upload_to='uploads/%d/%m/%y/') class Meta: verbose_name = 'details' verbose_name_plural = 'details' def __str__(self): return self.name My views.py file def form(requests): if requests.method == 'POST': name=requests.POST['name'], roof_age=requests.POST['roof_age'], email = requests.POST['email'], phone = requests.POST['phone'], address = requests.POST['address'], monthly_bill = requests.POST['monthly_bill'], HOA = requests.POST['HOA'], battery = requests.POST['battery'], foundation = requests.POST['foundation'], roof_type = requests.POST['roof_type'], availability= requests.POST['availability'], bill = requests.POST['bill'] details = Details( name = name, roof_age = roof_age, email = email, phone = phone, address = address, monthly_bill = monthly_bill, HOA = HOA, battery = battery, foundation = foundation, roof_type = roof_type, availability= availability, bill = bill ) print(name, roof_age, email, phone, address, monthly_bill, HOA,battery, foundation, roof_type, availability, bill) print("The data has been save to db") details.save() return render(requests, 'baskin/form.html') The print statement was giving the results in form of tuples Now I'm getting TypeError: Field 'roof_age' expected a number but got ('1',). How can I … -
Django admin panal
When adding an element it gives an error in POST and when reading the elements it gives an error in the GET views.py When manually adding the item here, the addition process is completed successfully without any errors from django.shortcuts import render from django.http import HttpResponse from .models import Feature # Create your views here. def index(request): feature1 = Feature() feature1.name = 'More Fixed' feature2 = Feature() feature2.name = 'Clean Mode' feature3 = Feature() feature3.name = 'Reatready' feature4 = Feature() feature4.name = 'More...' features = [feature1, feature2, feature3, feature4] return render(request, 'index.html', {'features': features}) def counter(request): text = request.POST['text'] amount_of_words = len(text.split()) return render(request, 'counter.html', {'amount': amount_of_words}) models.py from django.db import models class Feature(models.Model): name = models.CharField(max_length=200) admin.py Here I added the python link to HTML from django.contrib import admin from myapp.models import Feature admin.site.register(Feature) index.html {% load static %} <div class="col-xl-3 col-lg-3 col-md-3 col-sm-12 padding_right0"> <ul class="easy"> <li class="active"><a href="#">Easy to cutomize</a></li> {% for feature in features %} <li><a href="#">{{feature.name}}</a></li> {% endfor %} </ul> </div> POST Error: This happens when you add the item in the name field and press save Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/myapp/feature/add/ Django Version: 4.1.1 Python Version: 3.10.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
why not able to see new column for full name?
i am trying to concatinate values of f_n and l_n, display as fullname column, display the fullname values character length, and display fullname length less than 12, display names as ascending order from django.db import models class c1(models.Model): f_n=models.CharField(max_length=100) l_n=models.CharField(max_length=100) des=models.TextField() python manage.py shell In [1]: from django.db.models.functions import Concat In [2]: from django.db.models import Value as V In [3]: from temp1app.models import c1 In [4]: result=c1.objects.annotate(fullname=Concat('f_n',V('('),'l_n',V(')'))) In [5]: result Out[5]: <QuerySet [<c1: c1 object (1)>, <c1: c1 object (2)>, <c1: c1 object (3)>]> -
What is best practice when using dumpdata --natural-key?
When using dumpdata, Django recommends using natural_key() to serialize objects that refer to Permission or ContentType: --natural-foreign Uses the natural_key() model method to serialize any foreign key and many-to-many relationship to objects of the type that defines the method. If you’re dumping contrib.auth Permission objects or contrib.contenttypes ContentType objects, you should probably use this flag. See the natural keys documentation for more details on this and the next option. This means that rather than dumping foreignkey contentype with pk=1, it is dumped as: "content_type": [ "myapp", "mymodel" ], Why would you not always use --natural-key? What use cases are there where --natural-key would be inappropriate? -
Check if object parent user == request.user on child object create/update
class Parent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE, related_name='childs') I want to check if parent object user is request.user. Wanna figure out how to do it properly in DRF. -
How to show pandas graph to html file? [duplicate]
How to show pandas graph to html file? I have generated the bar graph using below code, data = [{'index': 0, 'Year_Week': 670, 'Sales_CSVolume': 10}, {'index': 1, 'Year_Week': 680, 'Sales_CSVolume': 8}, {'index': 2, 'Year_Week': 700, 'Sales_CSVolume': 4}, {'index': 3, 'Year_Week': 850, 'Sales_CSVolume': 13}] df = pd.DataFrame(data) df.set_index('index', inplace=True) img = sns.barplot(data=df, x='Year_Week', y='SalesCSVolume') output of the code in screenshot below, Now, I want to show this graph in my test.html file. Can anyone help me to sort out this issue -
How to make dropdown with <options> tag in html from choices in django model?
I have authentication app with models: LIVING_COUNTRIES = [ ('AFGANISTAN', 'Afganistan'), ('ALBANIA', 'Albania'), ('ALGERIA', 'Algeria'), ('ANGORRA', 'Andorra'), ('ANGOLA', 'Angola')] class Employee(models.Model): first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) username = models.CharField(max_length=30, blank=True) email = models.EmailField(max_length=140, blank=True) # phone_number = PhoneNumberField(null=True) date_of_birth = models.DateField(blank=True, default='1929-22-22') education = models.CharField(max_length=50, blank=True) country_living = models.CharField(max_length=50, choices=LIVING_COUNTRIES, default='UNITEDSTATESOFAMERICA', blank=True) created_at = models.DateTimeField(auto_now_add=True, blank=True) password = models.CharField(max_length=30, null=True) Now I want to display country_living field in my html form. I have tried like this: <select name="category" id="id_category"> {% for category in living_countries.country_living %} <option value="{{ category.country_living }}">{{ category.country_living }</option> {% endfor %} </select> def get(self, request): context = {} living_countries = models.Employee.objects.all() context['living_countries'] = living_countries return render(request, 'authentication/employee_register.html', context) But it doesn't work. Does anyone know how to access and display this field? -
Django rest framework doesn't display all fields and doesn't apply pagination
I don't have any idea what is causing this problem. Django rest framework doesn't display all fields when I want to post data, it also doesn't apply pagination. Here is code: views.py class BookApiList(APIView): def get(self, request, format = None): books = Book.objects.all() serializer = BookSerializer(books, many = True) return Response(serializer.data) def post(self, request, format = None): serializer = BookSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) class BookApiDetail(APIView): def get_object(self, name): try: book = Book.objects.get(title = name) return book except: raise Http404 def get(self, request, name, format = None): book = self.get_object(name) serializer = BookSerializer(book) return Response(serializer.data) def put(self, request, name, format = None): book = self.get_object(name) serializer = BookSerializer(book, data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) def delete(self, request, name, format=None): book = self.get_object(name) book.delete() return Response(status = status.HTTP_204_NO_CONTENT) models.py class Book(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, null = True, blank = True) image = models.ImageField(default = "Nana.jpg", upload_to = 'images/', null = True, blank = True) title = models.CharField(max_length = 150, unique = True) author = models.CharField(max_length = 100) category = models.CharField(max_length = 100) description = models.TextField(max_length = 5000, null = True, … -
most amount of field of day django
i want list the most amounts of field of model for each day for example this be my model: class Topic(Model.models): title= models.Charfield(max_lenth=40) total_responses= models.PositiveIntegerField() date= models.DateTimeField(add_now=True) i imported Max before in my views.py and this is my query set: query= Topic.objects.values('date','total_responses').order_by('-date').aggregate(Max('total_responses')) i send this query to template but it returns all models! but i just need max amount of each day models -
Why my password is not resetting in a Django application?
I have a forget password section in my project. A user can reset his/her password by providing the email address associated with the user's account. The whole process works fine for Django's built-in reset password form but does not work for my custom HTML template. Here I am providing my HTML template for this. {% if validlink %} <div style="margin: 15% 30% 0% 35%; border-top-right-radius: 10px; border-top-left-radius: 10px;" class="border border-primary"> <div class="text text-light border" style="background-color: rgb(0, 162, 255); border-top-right-radius: 10px; border-top-left-radius: 10px;"> <h2 style="text-align: center;">Change Password</h2> </div> {% if message %} <div class="text-danger">{{ message }}</div> {% endif %} <div style="margin: 10px 10px 10px 10px;"> <form method="POST"> {% csrf_token %} <input type="hidden" class="hidden" autocomplete="username" value="{{ username }}"> <div class="form-group"> <label>New Password</label> <input class="form-control" type="password" name="new_password" placeholder="Password must be at least 8 characters" required> </div> <div class="form-group"> <label>Confirm Password</label> <input class="form-control" type="password" name="confirm_password" placeholder="Password must be matched" required> </div> <div style="margin-top: 1rem;"></div> <input type="Submit" class="btn btn-primary"> </form> </div> </div> {% else %} <h5>Sorry, link is not valid!</h5> {% endif %} The main problem is, that my form can't find any user name. How do I pass the user name who is resetting his/her password? -
my django project is throwing an value error
my django project is throwing a value error the format of the date is correct but its showing that it does not match the error is : time data 'Sept. 19, 2022' does not match format '%b. %d, %Y' can anyone help me with this ? -
Making an authenticated user's form that can be edited in django
I am making a medical website, and I wanted to add a feature where the user could add their medical history in a description box. The website renders the main page only when the user has successfully signed in. So what I wanted to do is that they can write their medical history and when in the future they want to change something in it they can edit it in that same description box, as it always shows what you have submitted and is the same for a user. But in my case when I submit it just makes more new descriptions. #models.py class History(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) disc = models.TextField(blank=True) #views.py def history(request): his = History(user = request.user) form = HistoryForm(request.POST or None, instance=his) if request.method == "POST": if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() return redirect('/index') return render(request, 'history.html', {'form': form}) #urls.py path('history', views.history, name='history'), #forms.py class HistoryForm(ModelForm): class Meta: model = History fields = ('disc',) labels = { 'disc' : 'History' } Widget = { 'disc': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Write your medical history here...'}), } Also, (attrs=....) is not working, neither class nor placeholder. #history.html <form class="mx-5 mt-5" method="POST" action=""> {% csrf_token %} {{form.as_p}} <button … -
Axios making request to different url
heyy guys, I'm new here hope everyones doing well, currently i'm working on an e-commerce website stack: Django + DRF for backend and react/redux for front, I stumbled into a problem, axios is making request to fetch data to a wrong url. if you look at App.js below you would see that second route which renders ProductPage component is "/product/:id" function App() { return ( <Router> <> <main style={{ height: '90vh' }}> <Header /> <Routes> <Route path="/" element={<HomePage />} exact /> <Route path="/product/:id" element={<ProductPage />} /> </Routes> </main> <Footer /> </> </Router> ); } I've also implemented redux, my action looks like this: export const listProductDetails = (id) => async dispatch => { try { dispatch({ type: PRODUCT_DETAILS_REQUEST }); const { data } = await axios.get(`api/products/${id}`); dispatch({ type: PRODUCT_DETAILS_SUCCESS, payload: data }); } catch (error) { dispatch({ type: PRODUCT_DETAILS_FAIL, payload: error.response && error.response.data.message ? error.response.data.message : error.message, }); } }; please look at the url axios is making request to. I also have a proxy in my package.json file: { "name": "frontend", "proxy": "http://127.0.0.1:8000", so axios should be making request to "/api/products/2" for example but for some reason the request is made to "product/api/products/2" any feedback at all would be … -
`pip install` Gives Error on Some Packages on cpanel
Some packages give errors when I try to install them using pip install. This is the error when I try to install djoser, but some other packages give this error as well: ps: im trying to install libraries in a virtual envirement on cpanel. $ pip install djoser==2.1.0 Collecting djoser==2.1.0 Using cached djoser-2.1.0-py3-none-any.whl (46 kB) Collecting social-auth-app-django<5.0.0,>=4.0.0 Using cached social_auth_app_django-4.0.0-py3-none-any.whl (24 kB) Collecting django-templated-mail<2.0.0,>=1.1.1 Using cached django_templated_mail-1.1.1-py3-none-any.whl (4.7 kB) Collecting djangorestframework-simplejwt<5.0.0,>=4.3.0 Using cached djangorestframework_simplejwt-4.8.0-py3-none-any.whl (70 kB) Requirement already satisfied: asgiref<4.0.0,>=3.2.10 in /home/qcmouhxi/virtualenv/milestone2/3.9/lib/python3.9/site-packages (from djoser==2.1.0) (3.5.2) Collecting coreapi<3.0.0,>=2.3.3 Using cached coreapi-2.3.3-py2.py3-none-any.whl (25 kB) Collecting itypes Using cached itypes-1.2.0-py2.py3-none-any.whl (4.8 kB) Collecting uritemplate Using cached uritemplate-4.1.1-py2.py3-none-any.whl (10 kB) Collecting requests Using cached requests-2.28.1-py3-none-any.whl (62 kB) Collecting coreschema Using cached coreschema-0.0.4.tar.gz (10 kB) Preparing metadata (setup.py) ... done Requirement already satisfied: django in /home/qcmouhxi/virtualenv/milestone2/3.9/lib/python3.9/site-packages (from djangorestframework-simplejwt<5.0.0,>=4.3.0->djoser==2.1.0) (4.1.1) Collecting pyjwt<3,>=2 Using cached PyJWT-2.5.0-py3-none-any.whl (20 kB) Collecting djangorestframework Using cached djangorestframework-3.13.1-py3-none-any.whl (958 kB) Collecting social-auth-core>=3.3.0 Using cached social_auth_core-4.3.0-py3-none-any.whl (343 kB) Collecting six Using cached six-1.16.0-py2.py3-none-any.whl (11 kB) Collecting oauthlib>=1.0.3 Using cached oauthlib-3.2.1-py3-none-any.whl (151 kB) Collecting python3-openid>=3.0.10 Using cached python3_openid-3.2.0-py3-none-any.whl (133 kB) Collecting defusedxml>=0.5.0rc1 Using cached defusedxml-0.7.1-py2.py3-none-any.whl (25 kB) Collecting requests-oauthlib>=0.6.1 Downloading requests_oauthlib-1.3.1-py2.py3-none-any.whl (23 kB) Collecting cryptography>=1.4 Using cached cryptography-38.0.1.tar.gz (599 kB) Installing build dependencies ... … -
Why does Express serve static files using middleware instead of other ways?
I'm a Django developer. In Django we use an application to serve staticfiles. Then I found that in Express we use a middleware. Could anyone explain what are the pros and cons of both methods? -
How to avoid insertion of new row of same data in Mysql database when i press next or save button of forms in Django
My project has 4 forms in which i have a back,next and save button at the bottom. Everytime I press next or save button, a new row is added in database of the same data. How can I avoid that and can edit/update the same row when I changed the data in form. admission is 1st form personalinfo is 2nd form academic is 3rd form achievements is the 4th form Here is my views.py I am only pasting the code for 1st form as rest all are the same from django.http import HttpResponse from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import logout from django.contrib.auth.models import User from django.conf import settings from django.shortcuts import redirect from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from usersite.forms import admissionForm,personalinfoForm,academicForm from usersite.models import admission as admission2 from usersite.models import personalinfo as personalinfo2 from usersite.models import academic as academic2 from django.contrib.auth.models import User @login_required def admission(request): if request.user.is_authenticated: user = request.user print(user) form = admissionForm() #admission1 = admission2.objects.get(user=2) try: admission1 = admission2.objects.filter(user=user).latest('pk') except: admission1 = admission2.objects.filter(user=user) #admission1 = admission2.objects.all() return render(request,'admission.html', context={'form': form , 'admission1': admission1}) #return render(request,'admission.html', context={'form': form) else: return redirect('unauthorised') @login_required def submit_admission(request): if request.user.is_authenticated: user = request.user … -
I am trying to implement individual upload cancel using blueimp-jquery-fileupload in Django
have been trying to implement individual image file upload using blueimp_jquery_fileUpload. How can i get this done?. If i am to upload a single image, and cancel it, it does get cancelled however if its multiple images, it all cancels out. This is my template code: {% extends 'shared/base_profile.html'%} {% load static %} {% load crispy_forms_tags %} {% block title %} Upload Property Pictures {% endblock title %} {% block content %} <div class="row"> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <!-- {% if form %} --> <!-- {{ form|crispy }} --> <!-- <div class="col"> {{ form.pictures }} </div> --> <!-- {% endif %} --> <div class="form-group"> <label>Select file to upload.</label> <input type="file" class="form-control" id="fileupload" placeholder="Select file"> </div> <input type="submit" value="Upload" id="submit" class="btn btn-success"> </form> <div id="uploaded_files"></div> <!-- <div class="col-sm-9 m-auto"> </div> --> </div> {% endblock content %} This is my javaScript code: 'use strict'; $(function (){ function previewDataDetail(img,imgSize,imgName){ return ` <div class="col-sm-12" id="progress_img"> <img src="${img}"> <span>${imgSize}</span> <div class="value_hold" style="display:none"> <p id="preview_name">${imgName}</p> </div> <button class="btn btn-dark">Cancel</button> <div class="progress"> <div class="progress-bar progress-bar-striped progress-bar-animated" id="progress_bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style= "width:100%"></div> </div> </div> ` } function abortUpload(e){ e.preventDefault(); var template = $(e.currentTarget).closest( '#progress_img' ), data = template.data('data') || {}; data.context = data.context … -
django-filters and HTMX: Trigger a Filter on Multiple Views at Once
I have a simple app where I want to have a single filter dynamically update the queryset in two different Views at the same time. In this example, the user can filter based on city/country/continent and I'd like to dynamically update (1) the table showing the relevant objects in the model, and (2) the leaflet map to plot the points. I think the main issue here is that I need to trigger an update to the filter queryset on multiple 'views' at the same time and not sure how to structure my project to achieve that. Or if that's the right way to think about the problem. I'm trying to have a filter work with{% for city in cityFilterResults %} iterator in two different views at the same time. How can I achieve having two different views update based on a Filter using HTMX? index.html: (Note: My expected behaviour works if I switch the hx-get URL between either the table or the map. But they don't filter together and this is the issue I'm stuck on.) <body> <h3>Filter Controls:</h3><br> <form hx-get="{% url '_city_table' %}" hx-target="#cityTable"> <!-- <form hx-get="{% url '_leaflet' %}" hx-target="#markers"> --> {% csrf_token %} {{ cityFilterForm.form.as_p }} <button … -
djangorestframework does not work when django channel is applied :((
I am developing a chatting app that allows social login. While developing all restapi functions, including social login functions, and developing chat customers using channel libraries, there was a problem with social login. This code is chatcustomer using websocketcunsumer. enter code hereimport json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import * class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name .... this is setting for channel INSTALLED_APPS = [ 'channels', ] ASGI_APPLICATION = 'project.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } routing.py in project root from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) asgi.py import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() application = get_default_application() routing.py in chatapp from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] this is social login views.py @api_view(['POST']) def authenticate_kakao(request): access_token = request.data["access_token"] code =request.data['code'] """ Email Request """ print("process1") profile_request = requests.get( "https://kapi.kakao.com/v2/user/me", headers={"Authorization": f"Bearer {access_token}"}) print("process2") profile_json = profile_request.json() kakao_account = profile_json.get('kakao_account') email = … -
Django get id from model
how can I get id from just created model so that it can be used in item_name column. I was thinking about sth like this: class Items(models.Model): item_id = models.AutoField(primary_key=True) item_name = models.CharField( max_length=100, default="Item #{}".format(item_id) )