Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django display attribute of intermediary entity through parent entity
I am trying to reference an attribute from the Material_Requisition_Items intermediary entity through the Material_Requisition.reqItems ManytoManyField and have it displayed on HTML; however, it references the Item parent entity instead. Is there a way to reference attributes from the intermediary entity through the parent in Django HTML? models.py [Intermediary Entity] class Material_Requisition_Items(models.Model): reqID = models.ForeignKey("Material_Requisition", on_delete=models.CASCADE) itemID = models.ForeignKey('item.Item', on_delete=models.CASCADE) ... itemQuantity = models.PositiveIntegerField(default=0, null=True) [Parent Entity] class Material_Requisition(models.Model): ... reqItems = models.ManyToManyField( Item, through="Material_Requisition_Items", through_fields=('reqID', 'itemID'), related_name="mat_req_items" ) requisition_detail.html {% for item in object.reqItems.all %} <td>{{ item.itemID.itemName }}</td> <td>{{ item.itemQuantity}}</td> {% endfor %} views.py class RequisitionDetailView(LoginRequiredMixin, generic.DetailView): model = Material_Requisition template_name = "requisition/requisition_detail.html" context_object_name = "requisition" -
Request updating the state with an invalid payload in Django unit tests
a small question about Django unit tests. I'm only just starting out with Django so apologies if this might sound like a beginner question. But how can I test a scenario where I'm updating a state with an invalid payload in Django, with different fields missing each time? And then the request is rejected with a message this the request was invalid? My test code: def test_invalid_state_payload(self): # Given user = self.admin_user self.client.force_login(user) integration = AccountFactory(name="account", enabled=True, provider=str_to_kebab_case("account")) # When payload = { "enable_personal_payment_profile": True, "payment_profile_settings": [ { "payment_profile_id": "Some random ID", "send_to": "booker", }, { "payment_profile_id": "Another random ID", "send_to": "payment_profile_contact", }, ], } response = self.client.post( f"{self.url}/account/update_state", data=json.dumps(payload), content_type="application/json" ) # Then assert response.status_code == status.HTTP_200_OK # This is how far I have gotten with this. I'd like to assert that one of the # fields is missing and it raises an error but not entirely sure how to do this Help would be much appreciated. Thank you :) -
Django using mongodb _id
I want to use mongodb's self generated objectID, removing the django generated ID. How do I do this and will it cause an error that I don't know in the future? My ID line in models.I deleted this ID.: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) I will using mongo ID: _id:ObjectId("4864gh937m3oy3xa412w16a8") -
Django/Python - radio button value: check depending on model value & submitting value to view
I have an issue: I have a model that says whether autoreply (to send email automatically) is on or off. The model (that contains only 1 row) looks like this: class AutoSendMail(models.Model): auto = models.BooleanField(default=False) manual = models.BooleanField(default=True) the model contains only 1 row, with the default as above with auto = False and manual = True Now, what I want is that in the frontend: 2 radio buttons with "auto" and "manual" when either auto or manual is True, the radiobutton is checked The user can change this setting: they can choose to go to auto setting, click the submit button > this new value for auto is True will be send to views.py where it is used to change the first row in the AutoSendMail model. What I have so far is: mailindex.html <form action="" method="post" class="card"> {% csrf_token %} <div class="card-body"> <div class="form-group text-right"> <label class="form-label">Send E-mail Automatically</label> <input type="radio" name="autoapprove" value="On"> Manual <input type="radio" name="autoapprove" value="Off"> Auto </div> <div class="card-footer text-right"> <a href="{% url 'core:auto_send' %}" class="btn btn-secondary btn-sm">Submit</a> </div> </div> </form> views.py class AutoSendView(generic.TemplateView): model = AutoSendMail extra_context = {"mailbox_page": "active"} context_object_name = 'auto_send' template_name = 'core/mailbox/mailindex.html' def get(self, queryset=None, **kwargs): new_setting = AutoSendMail.objects.get(id=1) if … -
how can i implement admin login and logout using django rest framework?
i have been given a task to authenticate admin login programmatically and logout as well. I am able to to do login but on logged out when i check which user i am logging out it says AnonymousUser. How can i make sure i log out current user which is logged it. I am using django rest framework and testing it on postman @api_view(["POST"]) def adminLogin(request): if(request.method=="POST"): username = request.data["username"] password = request.data["password"] authenticated_user = authenticate(request,username=username, password=password) if authenticated_user != None: if(authenticated_user.is_authenticated and authenticated_user.is_superuser): login(request,authenticated_user) return JsonResponse({"Message":"User is Authenticated. "}) else: return JsonResponse({"message":"User is not authenticated. "}) else: return JsonResponse({"Message":"Either User is not registered or password does not match"}) @api_view(["POST"]) def adminLogout(request): print(request.user) logout(request) return JsonResponse({"message":"LoggedOut"}) -
django model structure (database structure)
I have one model many to one current state of this as follows: class A(models.Model): a_field = models.CharField() class B(models.Model): c_field = models.CharField() class C(models.Model): c_field = models.CharField() and they are related to D model class D(models.Model): a_field = models.ForeignKey(A) b_field = models.ForeignKey(B) c_field = models.ForeignKey(C) here there may be more related fields to the D model my questions are that is it a good database structure? or should I just do this class D(models.Model) object_id = models.IntegerField() in here there will be no related fields I will just save the ID can anybody answer to this question please? -
Understanding Django coming from R Shiny?
First of all, my apologies if this isn't the best place to ask this. My question isn't looking for an opinion of which one is better, but rather understanding what is going on as I am completely lost. I am familiar with R Shiny and its concept of reactivity, just writing a whole HTML page with the objects linked to functions all in one go. I am now trying to understand Django, but it has proven quite difficult for me throughout the tutorials. Background: Deployed basic apps internally at company using Shiny - the apps use authentication, collect data, push/pull to AWS S3, one linked to SQL database as well. Use HTML, SCSS and Javascript with Shiny. Know python to do Machine learning with it, now I am wanting to translate one of my apps to Django. In Shiny, I can literally use functions that will generate HTML and CSS once the app is running. I can describe "make a div here, with a button inside it, when the user presses it, change the background color of the div, wait 5 seconds and go back to original color". Shiny will then generate the HTML and use reactivity to check if …