Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deserializer two Models in django?
i'm sending two serializer models to api.py file... it is sending successfully but how to de-serializer both models in api.py views.py from django.http import HttpResponse, response from api.serializer import ResultsDNSerializer, ClassesExamMaxMarksSerializer, ResultSerializer, BlogPostsSerializer from rest_framework.renderers import JSONRenderer def ShowStudentResultAPI(request, id,eid): # Here id is Unique id of ResultDelcareNotice's Model and eid is ePunjabID of student Result_Delcare_Data = ResultsDeclareNotice.objects.filter(ID=id).first() Get_SessionCode = Result_Delcare_Data.SessionCode Get_AnnResultCode = Result_Delcare_Data.AnnResultCode Get_MonthCode = Result_Delcare_Data.MonthCode # Here AnnualResults is Model and here just we are fetching data stu_Data = AnnualResults.objects.get(SessionCode=Get_SessionCode,AnnResultCode=Get_AnnResultCode,MonthCode=Get_MonthCode,EID=eid) ResultDataTerm1 = AnnualResults.objects.filter(SessionCode=Get_SessionCode,AnnResultCode=Get_AnnResultCode,MonthCode=Get_MonthCode,EID=eid).first() StudentClassTerm1 = ResultDataTerm1.ClassCode Class_MaxMarksData = ClassesExamMaxMarks.objects.get(SessionCode=Get_SessionCode, ClassCode=StudentClassTerm1,AnnResultCode=Get_AnnResultCode) serializer = ResultSerializer(stu_Data) json_data = JSONRenderer().render(serializer.data) serializer_class_marks = ClassesExamMaxMarksSerializer(Class_MaxMarksData) json_data_class_marks = JSONRenderer().render(serializer_class_marks.data) Serializer_list = [json_data, json_data_class_marks] return HttpResponse(Serializer_list) import requests URL = "http://localhost:8000/api/result/1/4474239/" req = requests.get(url = URL) data = req.text print(data) -
Django ORM filter model where all relation have value equals to
Lets say that I have two models: class Worker(models.Model): name = models.CharField(max_length=100) class Task(models.Model): worker = models.ForeignKey(Worker) name = models.CharField(max_length=100) I would like to retrieve all workers where ALL tasks are called "dig". But I dont want workers that have only one Task called "dig". I've tried using filter and exclude with Q, like this: Worker.objects.filter(task__name='dig').exclude(~Q(task__name='dig')) But it didn't work, it don't remove those that have only one task like that. I could iterate over worker and tasks to find it, but is there any way to make this query using only orm? -
Django for each form input has its error message below it
I want to add error message for each input not all messages below each others if there is more than one message any help ? context = { 'error': False } if not email: messages.add_message(request, messages.ERROR, "Enter an Email", extra_tags='not_email') context['error'] = True I tried using extra_tags but also it viewed all the messages -
Django channels + Postgresql: Real-Time Database Messaging
I am currently developing an app with Django and PostgreSQL. Often, new information is sent to database (sometimes one time a day, sometimes over 30000 times a day). I have an UI (vue.js) and I want to see the data from the database showing to the client in real time. Currently I am using Django Channels. I implemented websocket and used psycopg2 library to listen to notifications from postgresql triggers. My consumer looks like this: class WSConsumer(WebsocketConsumer): def connect(self): self.accept() #the whole table is sent to the client after the connection self.send(json.dumps(ClientSerializer(Client.objects.all(), many=True).data)) #connecting to database conn = psycopg2.connect(dbname='...', user='...') conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) curs = conn.cursor() curs.execute("LISTEN update_clients_table;") #then I listen to any new data in this table and send it to the client while True: if select.select([conn],[],[],5) == ([],[],[]): print("Timeout") else: conn.poll() while conn.notifies: notify = conn.notifies.pop(0) print("Got NOTIFY:", notify.pid, notify.channel, notify.payload) message = notify.payload self.send(message) def disconnect(self): self.close() This is an example of handling changes in 1 table. I have 20 tables in total, and around 100 clients that can connect to the websocket. My question: is it a good way of building real-time app with Django and PostgreSQL? Is it simple, convenient, secure? Are there other ways to build … -
Could not parse the remainder: '(0,10)' from 'range(0,10)' with python
I have a problem with my template especially at the line: {% for j in range(0,10) %} I get the error: Could not parse the remainder: '(0,10)' from 'range(0,10)' -
how do I save form data from a different url template
how do I not save the form data until the transaction is done which is in a different URL, if the shipping form and the payment options were to be in the same URL then there wouldn't be this problem but it's not so how do I go about this? thx! views.py def checkout(request): if request.method == 'POST': form = ShippingForm(request.POST) if form.is_valid(): new_shipping = form.save(commit=False) new_shipping.customer = customer new_shipping.order = order #how do I not save the data until the transaction is successful new_shipping.save() return redirect('store:checkout_shipping') else: form = ShippingForm() else: form = ShippingForm() context = {"form": form} return render(request, 'shop/checkout.html', context) def checkout_payment(request): return render(request, 'shop/checkout_payment.html', context) urls.py path('checkout', views.checkout, name="checkout"), path('checkout_payment', views.checkout_payment, name="checkout_payment"), forms.py class ShippingForm(forms.ModelForm): address_one = forms.CharField(max_length=200) address_two = forms.CharField(max_length=200) -
Django favourite permission
how to configure permissions to receive favorites only of the user who added, and the favorites of other users could not be read models.py class Task(models.Model): user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') title = models.CharField(max_length=100) text = models.TextField(max_length=10000) class Favourite(models.Model): task_id = models.ForeignKey(Task, on_delete=models.CASCADE, blank=True, null=True, related_name='favourites',name='taskId') user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') views.py class FavouriteUserView(generics.ListAPIView): serializer_class = FavouriteReceivingSerializer pagination_class = MyCursorPagination permission_classes = (IsAuthor,) def get_queryset(self): return Favourite.objects.filter( userInfo_id=self.kwargs.get('pk')).select_related('userInfo').order_by('userInfo_id') permissions.py class IsAuthor(BasePermission): def has_permission(self, request, view): if request.method in SAFE_METHODS: return True return request.user and request.user.is_authenticated def has_object_permission(self, request, view, obj): return obj.userInfo == request.user -
Django drf-yasg swagger required header LOCALE parameter for every route
Is it possible to make header locale parameter required for every URL in application. Can i achieve it to set it up in global configuration or in every view method and if yes how can i do this? -
What is the best practice to store big sparse matrices in a django project?
I am finishing a public transport project that is using Dijkstra's algorithm. The algorithm is using adjacency matrices, with amount of nodes exceeding thousands -> propably going to scale this 10-100x, my matrices are sparse - <10% of non-zero values. The data is supposed to be updated once a day and is read-only. Since each of these values are evaluated multiple times per search, right now, I store non-zero values in the database, then create a matrix and save it as json file(n-lists of n-values), which is open and read every time the algorithm is run. What is the best practice to store and load this type of data? Should I store non-zero values the same way and just create sparse matrices with numpy and save it as HDF5 files? Would the HDF5 files introduce reading latency? I would like the final project to consist of 20-50k nodes, grouped into 1-5k matrices for each city and to be able to withstand something along the lines of a search a second. -
TypeError: Object of type Restaurant is not JSON serializable!!! Please tell me I am writing tests for drf, I get such an error
class CreatePizzaTestt(APITestCase): def setUp(self): self.restaurant = Restaurant.objects.create(name='Print', address='1') Restaurant.objects.create(name='Print12', address='1') self.valid = { 'restaurant': self.restaurant, 'pizza': 'Muffin', 'cheese': 'Muffin', 'dough': 'Pamerion', 'ingredient': 'White' } def test_restaurant_create(self): response = self.client.post( reverse('create_pizza'), self.valid) self.assertEqual(response.status_code, status.HTTP_201_CREATED) -
Django filter qs contains filename not working with underscores
my goal is to filter if the name of an uploaded document contains a search (a simple string from an input field submitted by the user). Strangely this works for long substring but not for short ones. Example My filter query is the following: Tab.objects.filter(document__file__icontains=search) where Tab is in simplest form a Model class like: class Tab(models.Model): name = models.CharField(max_length=50) and Document is another Model class wit a relation to Tabs and a file field. class Document(models.Model): tab = models.ForeignKey(Tab, on_delete=models.CASCADE) file = models.FileField(upload_to=custom_location) Weird behavior I've uploaded a file called example_test_123.pdf and if my search = example_test or test_123.pdf it results in a hit like expected. However, if search = test the filter doesn't find the file. Is this behaviour known or am I missing something here? Is it possible that the built-in name file is doing some trouble? Thanks. (Django 3.2.9 and Python 3.6.8) -
Using django templates to try to display an image
I'm trying to get an image to display on my webpage. I created a static folder in journal and a media folder within that to store my images. I have then attempted to display this image with the following code in my base.html file which i've used at my general template. <img src="{% static "journal/media/Solirius_logo.jpg" %}" alt="Logo" /> But PyCharm is telling me the tag is not closed referencing the start of the url path.Image on webpage -
Python 3.10/Django 3.2.7: No module named 'MySQLdb'
This week I started working home and tried installing my project on my PC but it won't work. I cloned the git repo, installed MySQL Workbench and Server and stuff, installed Visual C++ stuffs and loads of modules from my requirements.txt. But when I try to run ./manage.py migrate it spits out this: $ py manage.py migrate Traceback (most recent call last): File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\db\backends\mysql\base.py", line 15, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\lisa-\projects\register\manage.py", line 22, in <module> main() File "C:\Users\lisa-\projects\register\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\lisa-\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\lisa-\projects\register\venv\lib\site-packages\django\contrib\auth\models.py", line 3, … -
django token authentication not working properly
Hi Everyone i have configure token authentication in my project, when i post username and password on postman token are generating but when i added this token to access my api respose then getting [Authentication credentials were not provided.] models.py from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) settings.py INSTALLED_APPS = [ 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'api.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication' ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework_datatables.renderers.DatatablesRenderer', ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework_datatables.filters.DatatablesFilterBackend', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework_datatables.pagination.DatatablesPageNumberPagination', 'PAGE_SIZE': 100, } urls.py from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('login',obtain_auth_token,name="login") ] #api for response views.py class HisaabViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset=WeeklyData.objects.all() serializer_class=HisaabSerializer -
Slurm web interface
i'm working on a project for my company, and i'm trying to do a web interface in order to integrate different tools like Slurm, Zabbix, Nagios, etc... The first thing i'm trying to do is to integrate Slurm to give to a user the possibility to submit jobs, see the resources allocated and other infos. I think the best method to to achive this is program my web interface to dialogate with the RestAPI of Slurm and get all the infos to display and submit jobs with that. What do you think about that? There are other better choices to do that? -
extra select field not returning from django-rest serializer's create() method
Django==3.1.5 djangorestframework==3.12.2 I want to sort with the order_by() method for a dynamically calculated field. This field is "is_active". I added this field in ActivityModelManager class as below. "is_active" field does not appear in the data returned from the serializer's create method. But the data returned from the serializer's update method is coming. managers.py class ActivityModelManager(models.Manager): def get_queryset(self): qs = super().get_queryset() today = datetime.datetime.today().date() qs = qs.extra(select={'is_active': 'start_date <= %s AND %s < finish_date'}, select_params=(today, today)) return qs model.py class ActivityModel(TimestampAbstractModel): name = models.CharField(max_length=255) start_date = models.DateField() finish_date = models.DateField() vacancy = models.PositiveIntegerField(validators=[MinValueValidator(limit_value=1)]) objects = ActivityModelManager() def __str__(self): return self.name serializers.py class ActivitySerializer(serializers.ModelSerializer): is_active = serializers.BooleanField(read_only=True) class Meta: model = ActivityModel fields = [ 'id', 'name', 'start_date', 'finish_date', 'vacancy', 'is_active' ] read_only_fields = [ 'id', 'is_active' ] import datetime from dateutil.relativedelta import relativedelta from my_app.models import ActivityModel from my_app_serializers import ActivitySerializer ############# #creating ############# start_date = datetime.datetime.today.date() finish_date = start_date + relativedelta(months=1) data = { "name" : "Activity name", "start_date" : start_date, "finish_date" : finish_date, "vacancy" : 60 } serializer = ActivitySerializer(data=data) serializer.is_valid() ret_val = serializer.save() ##################################################### #ret_val variable has not contain "is_active" field. ##################################################### ########### #updating ########## instance = ActivityModel.objects.create( name = "Activity Name" start_date = start_date, finish_date = … -
Align Navbar items
I'm having this weird glitch that doesn't align the Navbar items (Navbar preview) I tried fixing it manually by adding margin and padding but I wasn't successful due to my lack of Bootstrap knowledge #cart-icon{ width:25px; display: inline-block; margin-left: 15px; margin-right: 20px; } #cart-total{ display: block; text-align: center; color:#fff; background-color: red; width: 10px; height: 25px; border-radius: 50%; font-size: 14px; } <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'store' %}"> Luffy </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-item nav-link active" href="#">Store</span></a> </div> </div> <div class="form-inline my-2 my-lg-0 mr-auto"> <a href="#"class="btn btn-warning">Login</a> <a href="{% url 'cart' %}"> <img id="cart-icon" src="https://stepswithcode.s3-us-west-2.amazonaws.com/m1-prt4/6+cart.png"> <p id="cart-total">0</p> </a> </div> </nav> how can I fix this? -
Django middleware runs twice because of request to jsi18n
Running an extremely simple piece of middleware on django 3.2, I display notifications to users before every page loads. The code to do this looks like his: from django.contrib import messages class ChangeNotifierMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): messages.add_message(request, messages.INFO,"test") response = self.get_response(request) The issue however, is just like in Django: custom middleware called twice, this middleware is executed twice per request. This only happens in the django admin interface, and not because of requests to the favicon, but because of requests to /admin/jsi18n/. That makes the cause for this issue different (I did not specify any urls for jsi18n anywhere) The result of all this is that on the front-end of my side, i get a single notification saying "test", as it should be. On the backend/admin interface, I get two notifications saying "test". How can i make django middleware run only once before a page loads, is there a way to guarantee the code only runs once? -
Connect to OpenVPN in Django and nginx
I have a Django app that talks to a 3rd party API, however, in order for the requests to succeed, an OpenVPN tunnel must be oppened. Locally, I do that using the OpenVPN GUI which has the certificate, however I'm not sure how to do the same thing when the app is deployed in a Docker container. I've tried importing the certificate in the store, but that doesn't work. Should I open the connection every time I want to send a request to the 3rd party API? -
Django error: The Items could not be created because the data didn't validate
I get the following error: ValueError at /create-items/ The Items could not be created because the data didn't validate., and can't find out what the issue is... Views.py def createMulitpleItemsPage(request): currency = '€' ItemFormSet = modelformset_factory(Items, form=CreateItemFormset, extra=1) qs = Items.objects.none() user = request.user.profile formset = ItemFormSet(request.POST or None, queryset=qs, form_kwargs={'user': user}) # Create multiple items if request.method == 'GET': user = request.user.profile ItemFormSet = modelformset_factory(Items, form=CreateItemFormset, extra=1) qs = Items.objects.none() formset = ItemFormSet(request.POST or None, queryset=qs, form_kwargs={'user': user}) context = {'formset': formset} if request.method == 'POST': print('printing POST: ', request.POST) print('printing Errors: ', formset.errors) if formset.is_valid(): formset = CreateItemFormset(user=request.user.profile, data=request.POST) parent = formset.save(commit=False) parent = formset.save() for form in formset: newitems = form.save(commit=False) newitems.user = request.user.profile newitems.save() return redirect('items') return render(request, 'base/mass_create_items.html', context) Forms.py class CreateItemFormset(ModelForm): def __init__(self, user, *args, **kwargs): super(CreateItemFormset, self).__init__(*args, **kwargs) qs = Categories.objects.filter(user=user) self.fields['item_category'] = ModelChoiceField(queryset=qs) class Meta: model = Items fields = ['item_name', 'item_category', 'item_start_date', 'item_end_date', 'item_purchase_price', 'item_rest_value'] Models.py class Items(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) item_name = models.CharField(max_length=200, null=False, blank=False) item_category = models.ForeignKey(Categories, null=True, blank=True, on_delete=models.SET_NULL) item_created_at = models.DateTimeField(auto_now_add=True, null=True, blank=False) item_updated_at = models.DateTimeField(auto_now=True, null=True, blank=False) item_start_date = models.DateField(null=True, blank=False) item_end_date = models.DateField(null=True, blank=False) item_purchase_price = models.FloatField(null=True, blank=False) item_rest_value = models.FloatField(default=0, null=True, … -
What are the best methods to create migrations on an already started project?
I have a medium sized project in my hands, with about 20 models, some many2many fields. I tried with --fake, recreating the migrations, deleting django_migrations etc etc. Every time I have problems involving existing fields. Obviously I can't delete the data inside, but I find myself unable to add a field or share the code because all my collaborators obviously have different migrations. Do you know methods to apply on an already started project? -
How to update django model automatically on due date?
I am trying to create a task manager app in Django. Tasks have a due date and is_complete status. class Task(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=30) expire_date = models.DateField() is_completed = models.BooleanField(default=False) At the time of the task creation, the users should choose the automatically rescheduling option for certain days in case the task is either completed or expired. How can I automatically reschedule the task for the number of days the user has chosen? -
Print dict in Django Template
I have a dict defined like that: table_data = [{'aircraft': <Aircraft: P28A I-ASTV>, 'row_data': [{'colspan': 2, 'booking_obj': <Booking: I-ASTV 2022-03-11 08:00:00 09:00:00>}, {'colspan': 4, 'booking_obj': <Booking: I-ASTV 2022-03-11 09:00:00 11:00:00>},...}]}] I am printing in my template with some like that: {% for row in table_data %} <tr> <th class="bg-primary border border-info">{{row.aircraft.registration}}</th> #This is working correctly {% for c, b in row.row_data %} <td colspan="">{{b}}</td> #This line just prints booking_obj {% endfor %} </tr> {% endfor %} but what I am trying to achieve is to display the actual key value (like, for example, the booking date), instead in my template I just see either colspan or booking_obj. I already tried with something like: {% for c, b in row.row_data.items %} <td colspan="">{{b}}</td> #This line just prints booking_obj {% endfor %} but it didn't work. Is there any way I can access the dict value properly? -
Make non-model field disabled or readonly in djnago admin based on condition
i have model, admin and form for it. But there is a field in my form that is not in the model and i'm doing some custom action with that field. I want this field to be readonly or hidden or disabled for users without some permissions, but django doesn't allow me to dynamically set any of these attributes. My model: class PromocodePool(TimeStampedModel): start = models.DateTimeField() end = models.DateTimeField(null=True, blank=True) Form: class PromocodePoolForm(forms.ModelForm): promocodes = forms.FileField(widget=AdminFileWidget, required=False) # this field is non-model class Meta: model = PromocodePool fields = '__all__' Admin: @admin.register(PromocodePool) class PromocodePoolAdmin(admin.ModelAdmin): form = PromocodePoolForm list_display = ("get_start", "get_end") readonly_fields = (<some fields, tuple>) @admin.display(description="Start date") def get_start(self, obj): return _date(obj.start, formats.DATE_FORMAT) @admin.display(description="Start date") def get_end(self, obj): return _date(obj.end, formats.DATE_FORMAT) def get_readonly_fields(self, request, obj=None): if not request.user.has_perm("promocode.custom_permission"): self.readonly_fields += ("promocodes",) # this doesn't work return self.readonly_fields Im getting this error: Unable to lookup 'promocodes' on PromocodePool or PromocodePoolAdmin or PromocodePoolForm Btw if i rename my form, error text stays the same because the real "finish" form generates via django's ModelFormMetaclass and is called PromocodePoolForm and this form is not my form described above. Is there any way to dynamically disable this field? If it's matters, im using python … -
How to implement Two Factor Authentication in Django rest framework in social authentication?
In my Django project, I use DRF Social OAuth2 to do social authentication. Now my question is how to implement Two Factor Authentication when a user login by social authentication.