Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST for Django API but require multiple inputs while my model only have 1 field that is able to take in inputted data
I am facing a issue right now on API post for @api_view[('POST'). I have the following codes: models.py class Job(models.Model): datetime = models.DateTimeField(default=timezone.now) combinedparameters = models.CharField(max_length = 1000) serializers.py class JobSerializers(serializers.ModelSerializer): class Meta: model = Job fields = ['combinedparameters'] As you can see there is only 1 field. But i dont know how to set up my @api_view['(POST)'] to do the same thing as my html because my html for this looks like this: Upon clicking the save button, I have to get the individual inputs from the textbox, textarea, dropdown box and convert it into the following : Example - {'device': 177, 'configuration': {'port_range': 'TenGigabitEthernet1/0/1,TenGigabitEthernet1/0/2,TenGigabitEthernet1/0/3,TenGigabitEthernet1/0/4,TenGigabitEthernet1/0/5', 'port_mode': 'Access', 'port_status': 'Disabled', 'port_param1': 'Test\r\n1\r\n2\r\n3', 'port_param2': 'Test\\n1\\n2\\n3'}} But how do I do the same thing in my API view if it doesnt follow how my html look like with so much input areas? -
Why graphene enum returns value instead key for my ENUMS key?
When i post data it return the value of the enum For example when i choose PL it returns the "Poland".I want to get the key of the enum instead of the value. I need PL instead of "Poland. Here is the code **This is my models** class Candidate(models.Model): class CountryChoices(models.TextChoices): PL = "Poland" DK = "Denmark" FI = "Finland" ---------- **This is my enums** class CandidateCountry(graphene.Enum): PL = "Poland" DK = "Denmark" FI = "Finland" residence_country = models.CharField( max_length=100, choices=CountryChoices.choices, null=True, blank=True) ---------- -
Django Rest Framework how to request [GET, POST, PUT, PATCH] from two different projects?
Here, I have two different services(Projects) running, Project A = Auth Server (which manages project auth-system) Project B = Products CRUD (Project A checks the credentials, then users can do crud Project B) Is there any example or document regarding this type of problem? Is there any way of communicating between the two projects? How can we fetch data from other projects or other project's endpoint and can check in Project B. -
Jinja template groupby sorting issue
In this code block, I have grouped by headings. But I want to sort the titles in array index order. Not alphabetically. {% set list = widget.attributes.faq_item %} {% for title_group in list|groupby('value.main_title') %} <h2 class="account-sss__title">{{title_group.grouper}}</h2> {% for item in title_group.list %} <a href="#" class="account-sss__list--link js-link"> {{item.value.question}} </a> <div class="account-sss__content js-account-sss__content"> {{item.value.answer}} </div> {% endfor %} {% endfor %} -
Refused to apply style because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled
Hello guys i'm working in a django project I get this error in all pages of my website here is my project organisation in base.html file i import css like this <link href="{% static '/store/css/bootstrap.min.css' %}" rel="stylesheet" type="text/css"/> <link href="{% static '/store/css/business-casual.css' %}" rel="stylesheet" type="text/css"/> thank you -
How to implement url template loading of django in javascript?
I have built a chat app like WhatsApp using Django channels, redis and websockets. It includes features like private and public chat. The user also can send images in chat. The UI is designed such that the sender's message is on the right hand side and the receiver's message is on the left hand side. What I want? I want to add a feature such that the user can delete each and every text message. I have added a delete button (looks like circle containing cross symbol) after each chat. The delete action is happening only after refreshing the page. I want it to happen without refreshing the page. Therefore, I want to add url template loading in javascript but it is not working. It is showing errors like "Could not parse the remainder" (django error) or "$ is not defined" (javascript error). I have tried all the solutions mentioned here. My code in room.html This code is of Group Chat {% block content %} <br><br> {% include 'message.html' %} <div class="container mb-5" style="max-width: 600px;"> <form> <div> <label class="h4 pt-5">Public Chatroom</label> <div class=" border border-primary border-2" placeholder="Chat Screen" id="chat-text" style=" height: 400px; overflow-y: scroll;"> {% if group_messages %} {% for … -
Is it possible to host a django project on firebase ? if yes please share the steps?
Is it possible to host a django project on firebase ? if yes please share the steps ? -
how to get new data at run time from django?
I am working on a Django project with ReactJs frontend. I have to built a simple chat application in that project where users can communicate with each other. in django views I have following function to read messages Views.py class MessagesListAPI(GenericAPIView, ListModelMixin ): def get_queryset(self): condition1 = Q(sender=15) & Q(receiver=11) condition2 = Q(sender=11) & Q(receiver=15) return Messages.objects.filter(condition1 | condition2) serializer_class = MessagesSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) this gives me all the messages between user 11 and user 15. on frontend I am getting these messages from rest Api by calling above function frontend const chatApi = axios.create({ baseURL: 'http://localhost:8000/chat/' }) const getMessages = async() => { let data = await chatApi.get(`MessageRead/`).then(({data})=>data); setMessages(data); } I am calling this function in an onClick event of button. and displaying the messages by maping messages array. problem is that at the time when these messages are open to the user. at that time if a new message(data) is added in database. I have to press that button again and call getMessages function again to display that message. Is there a way to automatically get that new message(record) without calling this function again by pressing a … -
how can we add sqlformat.exe in path and django-admin.exe in path?
Installing collected packages: sqlparse, pytz, asgiref, django WARNING: The script sqlformat.exe is installed in 'C:\Users\Slug\AppData\Roaming\Python\Python310\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: The script django-admin.exe is installed in 'C:\Users\Slug\AppData\Roaming\Python\Python310\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. -
Fail to serve static files in deployed Django app (Docker, gunicorn, whitenoise, Heroku)
I have built a Django REST API which serves JSON responses only. My problem is, in production (deployed on Heroku with debug=False) the app does not seem to serve relevant static files needed for the proper styling of the admin interface (only use case for static files). Note, in development (localhost with debug=True) the admin interface is properly styled. Going to the admin route at the deployed (Heroku) address, the content is delivered but without any styling. The browser developer tools indicate that style sheets could not be loaded due to a 500 error code. Django logging output reveals the below detail. django.request ERROR Internal Server Error: /static/admin/css/base.1f418065fc2c.css Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/secure_my_spot/custom_middleware/request_logging.py", line 30, in __call__ print(f"Content: {response.content}") File "/usr/local/lib/python3.8/site-packages/django/http/response.py", line 407, in content raise AttributeError( AttributeError: This WhiteNoiseFileResponse instance has no `content` attribute. Use `streaming_content` instead. I have gone into the Heroku dyno and verified that the static files, which cause the 500 error, are in fact in the static_root as per Django's settings.py. I have been spending a significant amount of time scouring the internet for clues as to what might cause the files to not … -
Multiple models in a queryset and/or multiple serializers for one View?
Say I have a Foo model and a Bar model: # models.py class Foo(models.Model): foo_title = CharField() class Bar(models.Model): bar_title = CharField() # serializers.py class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ["foo_title"] class BarSerializer(serializers.ModelSerializer): foo = FooSerializer() class Meta: model = Bar fields = ["bar_title"] If I want to return a Foo and a Bar model, I have to set up and call two views: # urls.py path("foo/<pk>/", FooView.as_view()) path("bar/<pk>/", BarView.as_view()) # views.py class FooView(generics.RetrieveAPIView): serializer_class = FooSerializer lookup_field = pk class BarView(generics.RetrieveAPIView): serializer_class = BarSerializer lookup_field = pk And then combine the two data results on my front-end. Is it possible to create one View that has multiple models in the queryset and/or multiple serializers? How can I make only one call to my API backend to return the data of different serializers with different models? e.g. Something like # urls.py path("foobar/<foo_pk>/<bar_pk>", FoobarView.as_view()) # views.py class FoobarView(generics.ListAPIView): pass -
How to horizontally align buttons in different elements
I have 3 buttons in different divs with different content. I would like all the divs to be the same height and to horizontally align the 3 buttons. Below is an image that shows the current page, and the desired page with the styling I'd like to achieve. But I just added margins manually in the dev console, so it's not using best practice (see the below image to see how it looks on an Ipad, not very good). And here is what it looks like on ipad (because i just manually added margin-top to each div). Does anyone know the proper way to achieve this? Below is the code: <html> <head> <meta content="width=device-width, initial-scale=1" name="viewport" /> <style> @import url(https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css); @import url(https://fonts.googleapis.com/css?family=Raleway:400,500,800); @import url(https://fonts.googleapis.com/css?family=Montserrat:800); .snip1214 { font-family: 'Raleway', Arial, sans-serif; color: #000000; text-align: center; font-size: 16px; width: 100%; max-width: 1000px; margin: 40px 0 40px 0; } /* MOBILE CUSTOMIZATIONS */ @media screen and (max-width: 767px) { .snip1214 .plan { width: 90%; margin: 0 auto; margin-bottom: 90px; background-color: #ffffff; } } @media screen and (min-width: 768px) { .snip1214 .plan { min-height: 350px; max-height: 350px; margin: 0; width: 33%; float: left; background-color: #ffffff; border: 1px solid rgba(0, 0, 0, 0.1); } .plan-select … -
the value 0.01 not retrieving in python django
model.py class Memopayment(models.Model): tp = models.DecimalField(max_digits=5, decimal_places=3) example.html <td>{{ m.tp|floatformat:3 }}</td> I have entered 0.01 in entry.html but the value retrieved is 0.000 instead of 0.010 Please help me in solving the issue. -
Django - Support query parameter list
I am in the process of migrating a NodeJS backend to a Django backend (DRF). There are some legacy API's I have to support for older app versions. One of them involves reading a list in the query params. "/questions/?questionIds[]=abc&questionIds[]=xyz" I know this is not the way Django handles list in query params but I still have to support it for legacy reasons. When I try to read this using request.query_params["questionIds"] it gives me an error django.utils.datastructures.MultiValueDictKeyError: 'questionIds' Is there any way in which I could support this or is it not possible using Django? -
Django Select from a Subquery
I want to query with window function and then do some group by aggregation on the subquery. But I couldn't make it with ORM method. It will return aggregate function calls cannot contain window function calls Is there any way to make a query like SQL below without using .raw() SELECT a.part_id, AVG(a.max_count) FROM ( SELECT part_id, MAX(count) OVER (PARTITION BY part_id ORDER BY part_id) AS max_count FROM table_one ) a GROUP BY a.part_id -
AttributeError: 'AnonymousUser' object has no attribute '_meta' Django channels
I am trying to login users in django channels and its throwing AttributeError: 'AnonymousUser' object has no attribute '_meta' My Consumer class LoginConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_name = "login_room" self.room_group_name = "login_group" await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() await self.send(json.dumps({"message": "connected to login socket"})) async def receive(self, text_data): self.json_data = json.loads(text_data) await login(self.scope, await self.query()) await database_sync_to_async(self.scope["session"].save)() async def query(self): await self.get_user_from_db() @database_sync_to_async def get_user_from_db(self): user = User.objects.get(username=self.json_data["username"]) return user async def disconnect(self, code): print("disconnected") await super().disconnect(code) My login view def login_user(request): if request.user.is_anonymous: if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("index") else: messages.error(request, "invalid username or password") return redirect("login") return render(request, "login.html") else: return redirect("index") My js file const username = document.querySelector(".username"); const password = document.querySelector(".password"); const socket = new WebSocket("ws://localhost:8000/ws/auth/login"); const button = document.querySelector("button"); button.addEventListener("click", (e) => { if (password.value !== "" && username.value !== "") { socket.send( JSON.stringify({ username: username.value, password: password.value, }) ); } }); Full Traceback: Exception inside application: 'AnonymousUser' object has no attribute '_meta' Traceback (most recent call last): File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, … -
Where are the Django and python files?
I'm new to Django and Python, i'm coming from Laravel. I'm working on a Windowsmachine. My Laravel project has tons of folders (vendor etc.) and is >100 MB my Django project is <50kB. In the end i want to upload my Django project to a webserver. But i'm curios where the Djangofiles on my computer are located, and how deployment works. (what are the essential parts/files compared to laravel (Project Folder + DATABASE) which i've to transfer) Is the DjangoFramework similar like a Javascript file, which i can put i my project folder or get it via linking? -
Django Rest framework, violates not-null constraint DETAIL
I have a question about my serializers. I have the following structure, summarizing. Consists of 3 models and a CreateAPIView view B contains OneToOneField = A C contains ForeingKey = B (many = True) [{List Image}] I don't understand much, how to perform create method in nested serializer. class A (serializer.ModelSerializer): class Meta: model = A class B (serializer.ModelSerializer): A = CreateASerializer () # OneToOneField to A C = CreateBSerializer (many = True) # ForeingKey to B List [{}] class Meta: model = B class C (serializer.ModelSerializer): class Meta: model = C #Can I separately create the Create method for each serializer? # For instance: class A (serializer.ModelSerializer): class Meta: model = A def create (self, validated_data): return models.A.create (** validated_data) class B (serializer.ModelSerializer): A = CreateASerializer () # OneToOneField C = CreateBSerializer (many = True) # ForeingKey List [{image}] class Meta: model = B fields = ('A', 'detail', 'C') def create (self, validated_data): A_data = validated_data.pop ('A') C_data = validated_data.pop ('C') date1 = models.B.objects.create (**validated_data) date2 = models.C.objects.create (**validated_data) for f in A_data: models.A.objects.create (date1=date1, **f) for nu in C_data: models.C.objects.create (date2=date2, **nu) return ? class C (serializer.ModelSerializer): class Meta: model = C def create (self, validated_data): C_data = … -
How to implement pagination in Django
I would like to implement pagination in my custom jsonresponse function. But I have no idea on how would i implement this. This is the code of my function. Any inputs will be a great help. Thank you. def json_response(data = {}, message = 'successful!', status = 'success', code = 200): data_set = {} status = 'success' if code == 200 else 'error' if status == 'success': data_set['code'] = code data_set['status'] = status data_set['message'] = message # data_set['data'] = data.data try: data_set['data'] = data.data except TypeError: data_set['data'] = json.dumps(data) except AttributeError: data_set['data'] = data else: data_set['code'] = code data_set['status'] = status data_set['message'] = message return JsonResponse(data_set, safe=False, status=code) -
Due to a loop before pagination Django paginator takes too much time. How can I solve this problem?
I was asked to map the object customer. I was trying to do the pagination before the loop but I don't know how to do it, because I think that you need to pass all the data to the paginator when creating. This is my view I think the problem is that when I call the function "get_customer_view_data" it runs the loop inside this function and I believe this happens everytime I change page on the paginator, causing the delay class CustomersView(AdminStaffRequiredMixin, TemplateView): template_name = 'customers/tables.html' def get(self, request, activeCustumers, *args, **kwargs): controller = CustomerViewController() date1 = request.GET.get('date1', 1) date2 = request.GET.get('date2', 1) customer_view_data = controller.get_customer_view_data(activeCustumers, date1, date2) page = request.GET.get('page', 1) paginator = Paginator(customer_view_data, 10) try: customers_data = paginator.page(page) except PageNotAnInteger: customers_data = paginator.page(1) except EmptyPage: customers_data = paginator.page(paginator.num_pages) context = {'object_list': customers_data, 'num': len(customer_view_data)} return render(request, self.template_name, context) And this is my controller where I map the data: class CustomerViewController(object): def get_customer_view_data(self, get_active_custumers,date1,date2): data = [] dates = self.set_dates(date1, date2) if get_active_custumers == 1: obj = Organization.objects.filter(organizationmainapp__application__appinfoforstore__status=2, deleted=False, status=True, to_deleted=False) else: obj = Organization.objects.all() for o in obj: customer_view_data = Customer() customer_view_data.Organization_id = o.id customer_view_data.Organization_name = o.name try: customer_view_data.monthly_price_plan = o.organizationmainapp.application.applicationselectedplan.price_plan.monthly_price except Exception as e: print(e) try: if … -
Printing multiple items using serializer
@api_view(['GET']) def selected_device(request,pk=None): if pk != None: devices = Device.objects.filter(pk=pk) devicedetail = DeviceDetail.objects.filter(DD2DKEY=pk) cursor = connection.cursor() tablename= "dev_interface_" + str(pk) cursor.execute(f"SELECT interface FROM {tablename} ") righttable = cursor.fetchall() devserializer = DeviceSerializers(devices, many=True) devdserializer = DeviceDetailSerializers(devicedetail, many=True) interfaces = [] for i in righttable: interfaces.append(i[0]) for i in interfaces: data =[{"interface": i}] interserializer = InterfaceSerializers(data, many = True) results = { "device":devserializer.data, "device_details" : devdserializer.data, "interface":interserializer.data, } return Response(results) In interfaces, I have the following ['G0/1', 'TenGigabitEthernet1/1/3', 'TenGigabitEthernet1/1/5', 'TenGigabitEthernet1/1/20', 'TenGigabitEthernet1/1/21', 'TenGigabitEthernet1/1/22', 'TenGigabitEthernet1/1/23', 'TenGigabitEthernet1/1/24', 'TenGigabitEthernet1/1/25', 'TenGigabitEthernet1/1/26'] But the above codes just print the last item in interface, how do I ensure it to print everything in interface? -
How to pass value into another model based on conditional statement [Django]
I want to create a countdown timer target that will be added into date_target model, using override save method in models.py, the time will countdown differently based on it's variety. import datetime class CustomerVariety(models.Model): variety = models.CharField(max_length=100, null=True) def __str__(self): return self.variety class Customer(models.Model): cardnumber = models.CharField(max_length=15, null=False) name = models.CharField(max_length=100, null=False) date_in = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) date_target = models.DateTimeField(auto_now_add=False, null=True) variety = models.ForeignKey(PerihalPermohonan, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.pk: if self.variety == "Priority Customer": self.date_target = self.date_in + datetime.timedelta(days=3) elif self.variety == "Secondary Customer": self.date_target = self.date_in + datetime.timedelta(days=5) super(Customer, self).save(*args, **kwargs) when i pass value into form and save it, why date_target models doesn't full fill the value ? -
Django / React - JWT Auth: How to persist token in-memory OR utilize httpOnly cookie in request
How can I use my access token either (1) through persisting it in-memory or (2) utilizing httpOnly cookies with my React app? Context Pretty confused with this right now. I'm using dj-rest-auth and djangorestframework-simplejwt for authentication. When I call the login endpoint from my backend, I get the refresh_token and access_token + set-cookie for both of these. This is fine. Attempt 1 When I try to utilize the token with an Authorization header on another page, it's undefined. This means there's a flaw with my AuthContextProvider (probably because I'm using a state variable that resets it). AuthContext const AuthContext = React.createContext({ token: '', isLoggedIn: false, login: (token) => { }, logout: () => { }, refreshToken: () => { }, }); export const AuthContextProvider = (props) => { const [token, setToken] = useState(); const userIsLoggedIn = !!token; const loginHandler = (token) => { setToken(token); } const logoutHandler = () => { setToken(null) } const contextValue = { token: token, isLoggedIn: userIsLoggedIn, login: loginHandler, logout: logoutHandler, } return ( <AuthContext.Provider value={contextValue}> {props.children} </AuthContext.Provider> ); }; export default AuthContext; Using authContext.token (authContext being the local variable from useContext), the token is undefined on any other page. Attempt 2 Ok, so the token … -
Accessing matching entry of two models using ForeignKey
I have three models: a Game model, a Distributor model and a Relation model. The Relation model has two ForeignKeys. One linking to Game model and other to Distributor model. I need to access on template (on the same view) the data from the Game model and from the Relation model for the matching entry. Models.py class Game(models.Model): name = models.CharField(max_length=100, unique=True) class Distributor(models.Model): dist = models.CharField(max_length=30, unique=True) class Relation(models.Model): game = models.ForeignKey('Game', on_delete=models.CASCADE) distributor = models.ForeignKey('Distributor', on_delete=models.CASCADE) Views.py class GameDetailView(DetailView): model = models.Game context_object_name = 'game_detail' template_name = 'gamesDB/game_detail.html' def get_context_data(self, **kwargs): context = super(GameDetailView, self).get_context_data(**kwargs) context.update({ 'game_status': models.Relation.objects.all() }) return context I think my view isn't right. But I can't find the way to make it work. How can I access on template the data from the Relation model for the matching game added on the Game model? Thanks in advance. -
Why Django Updating object not triggering at first time?
I have two function. My first function updating an Boolean filed True to False. My first function working properly but my second function not updating object False to True. If I try two time then second time my second function updating object False to True. I am not understanding why it's not updating at first time? here is my code: function1 #this function working properly views.py def ForgetPassword(request): if request.method == "POST": .....my others code profile_obj = UserProfile.objects.get(user=user_obj) profile_obj.email_confirmed = False profile_obj.save() .....my others code function2 #this function not working properly If I try two time then second time my this function updating object False to True: class ChangePassword_link(View): #my others code.... if user is not None and account_activation_token.check_token(user, token): profile_obj = UserProfile.objects.filter(user=user).update(email_confirmed = True) messages.success(request, ('Your account have been confirmed. Now you can login')) return redirect('members:change-password-page') else: messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.')) return redirect('members:change-password-page') #my others code....