Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OSError: Unable to load weights from pytorch checkpoint file while configuring AWS EC2
I'm working on a chatbot project that uses DialoGPT, and Django back-end. I've saved the model through save_pretrained method in my colab environment and decided to load them through the following codes in my settings.py tokenizer = AutoTokenizer.from_pretrained('microsoft/DialoGPT-medium') model = AutoModelForCausalLM.from_pretrained("bot/static/friends_model") The friends_model folder contains config.json and pytorch_model.bin. The point I am stuck is that when I run the server locally in django, the chatting works perfectly fine without any errors, but when I try to runserver in a linux ec2 environment, I bump into an OSError mentioned in the title. I git cloned a git repository, and used scp to transfer my model in the local environment to the server(EC2). My wildest guess is something went wrong during the transfer. I'm using a Windows OS, Python 3.9 and Pytorch 1.9.0 for all the environments I am programming (including virtual ones). Can anyone help me out? Many thanks in advance! -
Django queryset more simpel
is there a way to combine those 2 lines of code? a = terminal.provisioning_set.first() b = a.usergroup.id the result is coming from: terminal = Terminal.get_object(terminal_id, request.user) I like to see something like this: result = terminal.provisioning_set.first(usergroup.id) -
ModuleNotFoundError: No module named 'None'
I tried pip install none and the installation was successful, After trying to do python manage.py runserver the same error still occurs. -
Mongodb aggregation in Python : cannot pickle 'SSLContext' object
I need to find count of same groups (like count of same colour products or same price products) and I try to do aggreagtion using '$group'. result = collection.aggregate( [ { "$group" : {"_id":group_aggregation_format, "count": {"$sum":1}} } ]) print(result) group_aggreagtion_format is a data like {'title': '$title', 'colour': '$colour'} Then I get this error | INFO:dill:# T4 web_1 | D2: <dict object at 0x7efec3bfbe40> web_1 | INFO:dill:D2: <dict object at 0x7efec3bfbe40> web_1 | T4: <class 'pymongo.client_options.ClientOptions'> web_1 | INFO:dill:T4: <class 'pymongo.client_options.ClientOptions'> web_1 | # T4 web_1 | INFO:dill:# T4 web_1 | D2: <dict object at 0x7efec3c13dc0> web_1 | INFO:dill:D2: <dict object at 0x7efec3c13dc0> web_1 | T4: <class 'pymongo.common._CaseInsensitiveDictionary'> web_1 | INFO:dill:T4: <class 'pymongo.common._CaseInsensitiveDictionary'> web_1 | # T4 web_1 | INFO:dill:# T4 web_1 | D2: <dict object at 0x7efec3b84f00> web_1 | INFO:dill:D2: <dict object at 0x7efec3b84f00> web_1 | D2: <dict object at 0x7efec3a79240> web_1 | INFO:dill:D2: <dict object at 0x7efec3a79240> web_1 | # D2 web_1 | INFO:dill:# D2 web_1 | D2: <dict object at 0x7efec3bbfc40> web_1 | INFO:dill:D2: <dict object at 0x7efec3bbfc40> web_1 | # D2 web_1 | INFO:dill:# D2 web_1 | # D2 web_1 | INFO:dill:# D2 web_1 | T6: <class 'pymongo.auth.MongoCredential'> web_1 | INFO:dill:T6: <class 'pymongo.auth.MongoCredential'> web_1 | # T6 … -
How to change the default empty-field error message of Django Form fields
I want to change the default error message of empty fields. i mean this message: and i want to have a text below the "phone number" field that appears if user doesn't type exactly 11 numbers (text will show by typing a character and will disappear by 11 numbers) and is there a way to disable the button if the above conditions are not met? this is forms.py: class LoginForm(forms.Form): phone_number = forms.CharField( label='Phone number', label_suffix=':*', widget=forms.TextInput( attrs={ 'class':'form-control', 'id':'user_phone_number', } )) password = forms.CharField( label='Password', widget=forms.PasswordInput( attrs={ 'class':'form-control', 'id':'user_password', } ) ) def clean_phone_number(self): phone_number = self.cleaned_data.get('phone_number') qs = User.objects.filter(phone_number=phone_number) if not qs.exists: raise forms.ValidationError('This is an invalid phone number') return phone_number this is views.py: def login_view(request): form = LoginForm(request.POST or None) if form.is_valid(): phone_number = form.cleaned_data.get('phone_number') password = form.cleaned_data.get('password') customer = authenticate(request, phone_number=phone_number,password=password) if customer != None: # request.customer == customer login(request, customer) return redirect("/") else: # attempt = request.session.get('attempt') or 0 # request.session['attempt'] = attempt + 1 request.session['invalid_user'] = 1 return render(request, 'authentication/login.html',{'form':form}) this is the template: {%extends '_base.html'%} {%block title%}Login{%endblock title%} {% block content%} <form action="" method="post"> {%csrf_token%} {{form.as_p}} <button type="submit" class="btn btn-success">Login</button> </form> {% endblock content%} Thanks in advance -
How to fix RecursionError for Django Storages SFTPStorage?
I am trying to move my Django file storage to an external server, connected via ethernet to a small local network. This local network is not connected to the internet. I am using django-storages SFTPStorage for my file fields now. The server runs fine, but upon a file upload attempt, I get the following error: Performing system checks... System check identified no issues (0 silenced). August 20, 2021 - 13:23:22 Django version 3.2.4, using settings 'smartlab.settings' Starting ASGI/Channels version 3.0.3 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Traceback (most recent call last): File "/home/smartlab/larc-smartlab/venv/lib/python3.9/site-packages/storages/backends/sftpstorage.py", line 115, in _mkdir self._mkdir(parent) File "/home/smartlab/larc-smartlab/venv/lib/python3.9/site-packages/storages/backends/sftpstorage.py", line 115, in _mkdir self._mkdir(parent) File "/home/smartlab/larc-smartlab/venv/lib/python3.9/site-packages/storages/backends/sftpstorage.py", line 115, in _mkdir self._mkdir(parent) [Previous line repeated 2 more times] File "/home/smartlab/larc-smartlab/venv/lib/python3.9/site-packages/storages/backends/sftpstorage.py", line 114, in _mkdir if not self.exists(parent): File "/home/smartlab/larc-smartlab/venv/lib/python3.9/site-packages/storages/backends/sftpstorage.py", line 151, in exists self.sftp.stat(self._remote_path(name)) File "/home/smartlab/larc-smartlab/venv/lib/python3.9/site-packages/storages/backends/sftpstorage.py", line 87, in sftp self._connect() File "/home/smartlab/larc-smartlab/venv/lib/python3.9/site-packages/storages/backends/sftpstorage.py", line 61, in _connect self._ssh.load_host_keys(known_host_file) File "/home/smartlab/larc-smartlab/venv/lib/python3.9/site-packages/paramiko/client.py", line 127, in load_host_keys self._host_keys.load(filename) File "/home/smartlab/larc-smartlab/venv/lib/python3.9/site-packages/paramiko/hostkeys.py", line 101, in load e = HostKeyEntry.from_line(line, lineno) File "/home/smartlab/larc-smartlab/venv/lib/python3.9/site-packages/paramiko/hostkeys.py", line 364, in from_line key = ECDSAKey(data=decodebytes(key), validate_point=False) File "/home/smartlab/larc-smartlab/venv/lib/python3.9/site-packages/paramiko/ecdsakey.py", line 163, in __init__ key = ec.EllipticCurvePublicKey.from_encoded_point( File "/home/smartlab/larc-smartlab/venv/lib/python3.9/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py", line 191, in from_encoded_point if not isinstance(curve, EllipticCurve): File "/usr/lib/python3.9/abc.py", line … -
JSON parse error in ajax script using Django Rest framework
I am using django rest framework.My views response is ok but when i submit my view using ajax it gives me an error json parse error. Here is my views.py file: @api_view(['GET', 'POST']) @parser_classes([JSONParser]) def signup(request, format=None): if request.method == 'POST': data = JSONParser().parse(request) username = data.get('username') first_name = data.get('first_name') last_name = data.get('last_name') email = data.get('email') password = data.get('password') gender = data.get('gender') birth_date = data.get('birth_date') serializer = UserSerializer(data=data) if serializer.is_valid(): user = User.objects.create_user(username=username,first_name=first_name,last_name=last_name,email=email,gender=gender,birth_date=birth_date) user.set_password(password) user.save() data = {'result': 'success', 'message':'You have registered successfully now you can login'} return Response(data=data, status=201) elif not serializer.is_valid(): data = { 'result': 'error', 'message':serializer.errors} return Response(data=data) if not request.user.id and request.method == 'GET': return render(request, 'sessionauthapp/signup.html') My ajax js script: var frm = $('#signupform'); var token = '{{csrf_token}}'; $('#signupform').on('submit', function(e) { e.preventDefault(); $.ajax({ headers: { "X-CSRFToken": token }, url: '/signup/', type: 'post', data: $(this).serialize(), dataType: "json", contentType: "application/json", success: function(data) { console.log(data); }, error: function(data) { } }); return false; }); My ajax script gives me an error like json parse error but my views response is ok. My ajax script gives me an error like json parse error but my views response is ok. Hi, I am using django rest framework.My views response is … -
django forloop.counter not working as list index
I have a for loop that renders some include blocks in a template. {% for terminal in terminals %} {% if terminal.category %} {{forloop.counter0}} {% include 'app/terminal&location/modals/confirm_delete_modal.html' with obj=terminal url='tb-terminal-delete'%} {% include 'app/terminal&location/modals/update_terminal_modal.html' with obj=terminal form=tb_terminal_update_forms.{forloop.counter0} %} <tr class="text-center"> <td class="txt-oflo">{{ terminal.terminal_name }}</td> <td class="txt-oflo">{{ terminal.terminal_id }}</td> <td class="txt-oflo">{{ terminal.room.room_name }}</td> <td class="txt-oflo">{{ terminal.create_time }}</td> <td class="txt-oflo">{{ terminal.create_user }}</td> <td> <button class="btn btn-lg" data-toggle="modal" data-target="#{{ terminal.id }}"> <span> Remove </span> </button> <button class="btn btn-lg ml-4" data-toggle="modal" data-target="#update_{{terminal.id}}"> <span> Update </span> </button> </td> </tr> {% endif %} {% endfor %} Am I passing the forloop.counter0 correctly? If I do form=tb_terminal_update_forms.1 or form=tb_terminal_update_forms.2 it works, how do I pass the counter? -
Django DeleteView derived CBV is deleting my object without showing confirm delete page
I am using Django 3.2 I have a model Foo, and I have written a CBV to allow for deletion. This is what my CBV looks like: /path/to/foo/view.py class FooDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Foo slug_url_kwarg = 'identifier' slug_field = 'identifier' success_url = reverse_lazy('homepage') def get_object(self, queryset=None): identifier = self.kwargs[self.slug_field] return self.model.objects.get(identifier=identifier) def test_func(self): photo = self.get_object() return self.request.user == foo.owner def post(self, request, *args, **kwargs) -> HttpResponse: foo = self.get_object() foo.delete() return super().post(request, *args, **kwargs) /path/to/foo/templates/foo/templates/foo_confirm_delete {% extends 'base.html' %} {% load static %} {% block page_title %}Foo deletion Confirmation {% endblock %} {% block content %} <form action="{% url 'myapp:foo-delete' %}" method="post">{% csrf_token %} <div class="form-group"> Are you sure you want to delete this item?<br> <br> <strong>{{ object }}</strong> {{ form.errors }} <br> <br> <input type="hidden" name="confirm_delete" value="confirm_delete"> <p> <input type="submit" class="btn btn-primary">Delete</input> <a href="../">Cancel</a> </p> </div> </form> {% endblock content %} Why is my foo_confirm_delete.html form not being displayed to give me a chance to cancel - before the object is deleted? How do I fix this? -
data-traget attribute undefined in django templates and Jquery
Am trying to access the data-target value , it was working but then it stopped unexpectedly, below is my html " <div class="loan-pending" id='loan-pending-{{loan.loan_id}}' data-target="loan-pending-data-{{loan.id}}" data-query-loan-id="loan={{loan.id}}"> {% trans 'Loan Applications' %}: {{loan.loan_id}} </div> Then, this is the jquery : const loanPendingData = $(`#loan-pending-data-${loanID}`); I also tried , the following : const loanPendingData = $(this).data('target'); but no luck , what causes this in django and jquery ? -
How to receive data who was sent by me - websocket | django
I work on a chat in django with django-channels I would like to receive the data who was sent by me -
Angular + Django Backend. How to Log in base on user types in Django
Im facing a problem on how to integrate user permission like if the is_superuser is False, then log in to Author component and if Superuser is True, log in to Admin Component in Angular. I hope someone can help What I want, 1) If the is_superuser is True in django, then log in to a Admin component / admin dashboard 2) If the is_superuser is False in django, then log in to a Author component / Author dashboard -
Utils in models: acceptable or not?
Have a look at the static method get_raster_image. Of course it is a utility. class RasterImage(models.Model): raster_original = models.ImageField(upload_to=omnibus.utils.model_utils.UploadManager.get_upload_to, verbose_name=images_general.OriginalsFileNames.RASTER_ORIGINAL.value, validators=[ images.validators.RasterImageValidator. validate_file_name_according_to_pattern, images.validators.FileValidator. validate_if_file_name_already_occupied, ] ) @staticmethod def get_raster_image(an_id: str) -> RasterImage: result = RasterImage.objects.get(pk=an_id) return result To avoid imports I usually use apps.get_model(). I avoid imports like the plague. And frankly speaking, at first I placed get_raster_image in the utils subdir. But then I was afraid: even a possibility of circular import is a nightmare for me. Right now to get an instance of RasterImage I'll have to write: raster_image_model = apps.get_model(app_label="images", model_name="RasterImage") raster_image_model.get_raster_image(an_id=1) But, please, keep in mind that once I had to discard an almost finished project and rewrite it from the scratch. Just because at some late stage a circular import appeared and I failed to cope with it. Could you tell me whether it is acceptable or a complete garbage? What is the correct way to organize such an utility? -
Many to many field form inline add, remove and edit
There are already quite a few questions (1, 2, etc.) about this but without (good) answers. Working code I have one model for an employee and another one for business hours. I want to link them with a many-to-many relationship. For this I would like to create a form to add, remove and edit them. So far, I'm only able to select them from the list of all relationships. models.py class WeekdayHour(models.Model): """Model representing a business hours in for specific weekdays.""" WEEKDAYS = [ (1, _("Monday")), (2, _("Tuesday")), (3, _("Wednesday")), (4, _("Thursday")), (5, _("Friday")), (6, _("Saturday")), (7, _("Sunday")), ] weekday = models.IntegerField(choices=WEEKDAYS) from_hour = models.TimeField() to_hour = models.TimeField() class Employee(models.Model): """Model representing a user employee.""" name = models.CharField(max_length=50) business_hours = models.ManyToManyField('WeekdayHour', through='WeekdayHourEmployee') class WeekdayHourEmployee(models.Model): weekday_hour = models.ForeignKey('WeekdayHour', on_delete=models.RESTRICT) employee = models.ForeignKey('Employee', on_delete=models.RESTRICT) class Meta: unique_together = ('weekday_hour', 'employee') The reason for using the intermediate table is to define the unique together constraint. Next I define the form in the following way. forms.py class EmployeeForm(ModelForm): # define the specific widget for the business hours business_hours = forms.ModelMultipleChoiceField( queryset=WeekdayHour.objects.all(), widget=forms.CheckboxSelectMultiple ) class Meta: model = Employee fields = ('name', 'business_hours') So far I have a form displaying the business hours that looks … -
Overwrite a Django Material Admin template and keep it inside Project Folder
I'm working with Django Material Admin framework. I want to overwrite a template(example: clearable_file_input.html) and place the overwritten template in the project folder to get the updated functionality of the template while running the project. Where do I need to place that updated template inside the project? What are all the changes (if there is any like updating settings.py file) that I need to do for automatically fetching the updated template but not the original template? Example Scenario: I want to update the functionality of opening a link (of TabularInline Model) when it's clicked. I want to open the link in another tab when it's clicked. So, I got to know that I need to update the clearable_file_input.html and I successfully updated that. Now I need to figure out where do I need to place this file inside my project to get the updated functionality. I don't want to update the original template present in the path: "./local/lib/python3.7/site-packages/material/admin/templates/admin/widgets/clearable_file_input.html" I want to place the updated template in project so that while running the project, the updated template is taken rather than the original template present in the previously specified path. What do I need to do for this functionality to work? -
How to use AJAX based autocompletion with html form and django
I want to do a stock management system in django. I don't have any code yet relevant for the problem I want to ask. So bear with my explaination: I have a working django project with a working REST API. The database for example contains a "Component" model/table that holds all the components that can be stored. The "Stock" Model holds the Stock entries of how many components are stored where. These entries hold a foreign key to the component. Currently I'm trying to make a "new Stock" Form that allows me to create a new entry in the "Stock" table. To specify the component foreign key, I would usually use a dropdown select and let django fill in the possibilities (ChoiceField). Similar to how it's done in the admin panel. The main problem is: The component table is huge: >10000 Entries. I cannot simply add all the possibilities to the webpage. Therefore, I want to use a standard text field (?) with an autocomplete dropdown, that will use the REST API to query the results. However, I do not really find a way to fill out the HTML form. My best guess is to search the components via the … -
Authenticate with Google OAuth2 in unit test in Python Django
I'm working on a Django project that uses Google OAuth2 to authenticate users. It's the first time I work with OAuth2 authentication, so my knowledge of Google OAuth2 is from the resources I found in the web today. In writing unit tests for the application I need to authenticate in it, and I don't know how to do it inside a unittest.TestCase test suit. How to authenticate to the application using Google OAuth2 in unit tests suits? -
Image between text in Django
I'm trying to figure out how I can place an image between text in a blog post in Django. I first thought of using something like the urlize filter ({ blog.body | urlize }) that would allow me to include a link for the image on the text body and then render the image on the post, but alas there is no filter for that. Or at least not that I know of. I then realized it would be much more preferable if I could place the image inside the admin panel itself, in the form of an inline command, like it is done here: https://pythonhosted.org/django-inline-media/ What is an easy implementation of this that wouldn't require me using the whole package there? Any help is greatly appreciated. -
Calling functions in a django app from url
Consider the domain example.content.com. Now I want that content.com part to point to my django web application, and that example part to point to specific functions in my views.py folder, so that I can call different functions in my views.py by changing that example part. Is there any way to achieve this? Any help is appreciated. Thankyou! -
There are 2 same querysets in context for the ListView
I am wondering why there are 2 same querysets in the context: object_list and massage_list. Did I do something wrong? I could find massage_list only in urls path('work/', MassageListView.as_view(), name='massage_list') class MassageListView(ListView): def get_queryset(self): return Massage.objects.filter(time_of_receipt__year=now().year, time_of_receipt__month=now().month) def get_context_data(self, *, object_list=None, **kwargs): context = super(MassageListView, self).get_context_data(**kwargs) month_salary = 0 for i in context['object_list']: month_salary += i.price context['month_salary'] = month_salary context['form'] = MassageForm() print(context) return context printed context {'paginator': None, 'page_obj': None, 'is_paginated': False, 'object_list': <QuerySet [<Massage: 2021-08-11 12:00:00+00:00>, <Massage: 2021-08-14 12:00:00+00:00>]>, 'massage_list': <QuerySet [<Massage: 2021-08-11 12:00:00+00:00>, <Massage: 2021-08-14 12:00:00+00:00>]>, 'view': <myapp.views.MassageListView object at 0x7f2e166200a0>, 'month_salary': 13800, 'form': <MassageForm bound=False, valid=Unknown, fields=(client;price;count;time_of_receipt)>} -
django REST framework group by in nested model
I am new to django rest framework. i have a nested model for saving orders of a restaurant. now when i send a GET request i get below response; [ { "menu": { "id": 1, "food_name": "food1" }, "user": { "id": 49, "username": "A" } }, { "menu": { "id": 1, "food_name": "food1" }, "user": { "id": 63, "username": "B" } } ] but i want to group users with the same menu like this: [ { "menu": { "id": 1, "food_name": "food1", "users": { "1": { "id": 49, "username": "A" }, "2": { "id": 63, "username": "B" } } } } ] here is my code: models.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) menu = models.ForeignKey(Menu, on_delete=models.CASCADE) views.py class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer serilizers.py class OrderSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() menu = MenuSerializer() class Meta: model = Order fields = ['id', 'user', 'menu'] thanks -
draft.js showing "require is not defined" error when used without a react app
I want to make a react.js component inside my django application which will allow me to 1) have a rich text editor 2) the ability to edit the style of some text when the user types. For the first feature, i don't understand how i need to import EditorState inside my template. It shows this error Uncaught ReferenceError: require is not defined at this line: import {Editor, EditorState} from 'draft-js'; -
How to show backend stream data in the front-end in django
I have a django app that recieve an value from the client and do some processes in the backend and this process takes time and i want to show to the user the live process output. in the backend i'm using subprocess.Popen and then i'm using yield to return stream data. and in the views.py I'm using StreamingHttpResponse() to show stream data. my problem is where, when the process is starting, the live results are shown in the blank page, but i want to show the live data at current page and in a terminal window. and after the process is finished, i want to show the Download button to the user, to download the result as pdf. everything in building PDF file and download page works perfect and my file is builing in the /media directory. and before my problem, i did that and client could download the result pdf. but now, i want to add live-stream to the app to show the process.\ here is my current views.py which run perfect in the new blank page. @login_required(login_url='/login/') def dir_s(request): if request.method == 'GET': return render(request, 'app/dir_s.html', {'form':IpsForm()}) elif request.method == 'POST': try: global ip, user_name, function_name form = … -
Edit form is not showing data of tags with tags input
I am building a Blog App and I am building a tagging functionality in a Blog Post , So I used django-taggit. Then i used bootstrap's tags input library. BUT when I try to edit blogpost with bootstrap's tags input then previously saved tags are not showing, And when I try to show using {{ form.tags }} then they are showing but not in HTML's input tag. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') tags = TaggableManager() views.py def edit_blog_post(request,blogpost_id): post = BlogPost.objects.get(id=blogpost_id) user = post.user if request.method != 'POST': form = UpdateBlogPost(request.POST or None, request.FILES or None, instance=post) else: form = UpdateBlogPost(instance=post, data=request.POST, files=request.FILES) if form.is_valid(): form.save() return redirect('mains:home') context = {'form': form} return render(request, 'edit_blog_post.html', context) edit_blog_post.html <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form }} </table> <button type="submit">Save Changes</button> </form> </div> When i use this then it is showing saved tags BUT {{ form.title }} <input class='form-control' id="choices-text-remove-button" type='text' name='tags' /> When i try this then saved tags are not showing. Then i tried value = '{{ form.tags }}' BUT this was not showing tags but with some glitches. I also tried rendering-fields-manually BUT it is also not showing. Any help … -
Authenticate user with User model, where I created user table in phpmyadmin and connected with django. Then migrated it to app
I'm new to django. I try to make login user with authentication, but my model refers to table in phpmyadmin. I connected DB and made migration but when I try login it do not authenticate with my phpmyadmin table. I just want to know how to authenticate with the phpmyadmin user table and login into the website.