Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a views function that will find the single desired instance from the database and send it to the template using Django
I am working on a library web app using Django. Right now a user can create as many libraries as they want and add books to the created libraries. The user is able to choose any library and view the contents of that table on a template. I would like the user to be able to jump to another template that has the full details of any book in the database. I am passing through a request with the pk and getting errors. Do I need to add anything about the library object in here? my views function currently: def single_detail(request, pk): book_details = get_object_or_404(AddBook, pk=pk) context = {'book_details': book_details} return render(request, 'library/details.html', context) AddBook is the name of the class that determines the attributes of the entry and i didn't manually add a primary key to it since with Django you don't have to. The user is already on the page where only the contents of the chosen library are displayed. I know my URL path needs to be this, but the whole app breaks when i have int:pk inside the details path. urlpatterns = [ path('', views.lib_home, name='homeLib'), path('create/', views.create_library, name='create'), path('add/', views.add_book, name='add'), path('<int:pk>/library/', views.your_library, name='libraryList'), path('details/<int:pk>', … -
Got stuck on a bug in posgresql using django, when i fix the bug and the re migrate nothing happens
i did mistake which is setting a True as a default value in a ArrayField(models.CharField(...)) which should be in characters only (the bug isn't the import part) so anyway when i fixed it then tried to migrate it got stuck on that bug and didn't reload, i even changed it to another database and nothing happened, it happened to me the last time and i just created another project i am tired of that, is there any solution to fix this? -
Django ModelForm and Objects id
I'm building forms with forms.ModelForm and I need to pass the Client id in this form. Models.py class DocumentTypeForm(forms.ModelForm): client = forms.IntegerField(widget=forms.HiddenInput(), initial=Client.pk) class Meta: model = DocumentType fields = [ 'code', 'name', 'client', ] Models.py class DocumentType(models.Model): code = models.CharField(max_length=10, verbose_name=_("Code")) name = models.TextField(verbose_name=_("Name")) client = models.ForeignKey( "Client", on_delete=models.CASCADE) That is returning AttributeError 'DocumentTypeView' object has no attribute 'object_list' -
Custom permissions in Django REST API don't raise any error even when print() function returns False in the terminal
I wrote a permission: class IsParticipant(permissions.BasePermission): def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): if isinstance(obj, Message): return request.user in obj.chat.chat_participants.all() elif .... return False I checked, conditions work correctly (now I need just the first if condition), the program enters the if condition, and returns False or True (I've written print() function, so it showed in terminal that program returns False of True depending on values). But it doesn't change anything, even if returns False, it doesn't forbid anything for user. It even doesn't raise any default error. Here is the view class (although I don't think it is necessary here): class WriteMessageCreateAPIView(generics.CreateAPIView): permission_classes = [IsAuthenticated, IsParticipant] serializer_class = WriteMessageSerializer #the model is named as 'Message' def perform_create(self, serializer): serializer.validated_data['author'] = self.request.user serializer.validated_data['chat_id'] = self.kwargs['pk'] return super(WriteMessageCreateAPIView, self).perform_create(serializer) So the questions are: Why the permission class doesn't do anything? How can I fix this issue? -
Can I delete old versioned staticfiles?
I am using Django with whitenoise and django-compression-middleware. When I do changes and run manage.py collectstatic I get new normal and compressed static files with new versions. After some changes the folder size gets too much. But when I delete all before running collectstatic I get the same version again so browser cache doesn't change and it runs the old code. How can I renew the cache with versioning by using collectstatic and also have less files in static folder? -
Is there a way to build dynamic models in Django?
I am currently building a project in Django, and I was wondering if is there a way to build a dynamic model. I want to create a model with a group of user, and the table structure is the following: Group Name User 1 User 2 User 3 User ... But I want to make users dynamic, I mean, if the group has only 2 users the model will only put 2 users fields in the model, and if the group has 10 user the model put 10 users fields in the model. Does someone know a way to do this? Is it even possible? I hope I made it clear enough for you guys! If you have any questions please post in the comments and I will answer as fast as I can. Sorry for the english tho! Not my main language. -
Django runserver command failed
I've been learning Python for a couple of months and a couple days ago i decided to learn one of Web frameworks. I found some tutorials on Django and it was looking really cool until i tried to use "runserver" command. As you can see i used the basic line "python -m django runserver manage.py" and got a lot of calls. I've just installed Django and i wasn't changing anything in it's scripts. I only started by creating a new project that worked perfectly with "python -m django startproject djangoLearn". Do you have any thoughts on how can i fix this problem? This problem prevents me from further learning beacuse i can't see my project. Thanks in advance. Hope y'all have a great day. Calls that i get while trying to run server: D:\Projects\djangoLearn>python -m django runserver manage.py Traceback (most recent call last): File "C:\Program Files\Python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Program Files\Python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\norml\AppData\Roaming\Python\Python39\site-packages\django\__main__.py", line 9, in <module> management.execute_from_command_line() File "C:\Users\norml\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\norml\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\norml\AppData\Roaming\Python\Python39\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\norml\AppData\Roaming\Python\Python39\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) … -
I wanna set time(second countdown in html page in Django. How can I do it?
I wanna create a Django project. Where I set some quiz's and set countdown, like (30sec, 3 min). User will need to solve during that end of the countdown. -
Multiple modals in template ruins layout and enters dark screen on post
I am using django and I am making update modals for each object in a for loop in my html. I am also making a new script for each update modal. The problem is that the layout of the table is scrambled. And everytime I update a object I get a dark screen like when opening a modal just without a modal. Can anyone help? Here is my html: <div id="authors-candidates-div"> <table id="authors-table" class="table"> <thead> <tr> <th class="text-center" scope="col">ID</th> <th class="text-center" scope="col">Name</th> <th class="text-center" scope="col">Name original language</th> <th class="text-center" scope="col">Extra info</th> <th class="text-center" scope="col">Update/ Link</th> </tr> </thead> <tbody> {% for author in authors.all %} <tr> <th class="text-center" scope="row">{{ author.pk }}</th> <td class="text-center">{{ author.name }}</td> <td class="text-center">{{ author.name_original_language }}</td> <td class="text-center">{{ author.extra_info }}</td> <td class="text-center"> <!-- Update author buttons --> <button type="button" id='init-btn{{ author.pk }}' class="btn btn-primary btn-danger" data-toggle="modal" data-target="#UpdateAuthorModal{{ author.pk }}" data-form-url="{% url 'author-proces' publication.pk author.pk %}"> <span class="fa fa-pencil"></span> </button> <!-- Modal --> <div id="UpdateAuthorModal{{ author.pk }}" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title col-md-10">Update Author</h5> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <div class="form-group"> <label for="id_name_t">Name</label> <input type="text" name="name" maxlength="100" value="{{ author.name }}" class="form-control name" id="id_name{{ author.pk }}"> <div class=""> </div> … -
Is there a way to define in Mypy a Django model reversed field?
Suppose you have the following simple models: class User(models.Model): name = models.CharField(max_length=10) class Article(models.Model): title = models.CharField(max_length=50) user = models.ForeignKey(User, related_name='articles') I'll have an auto generated field called articles in my User model. Now, it's not being inferred by Mypy of PyCharm so the IDE warns me about non existing field. Is there a way to define in Mypy that field? -
i am unable to change profile pic in django
views.pyI created a profile form in models.py for and form.py to update it but all thing got updated expect profile picture models.py -
Django, CSS is loading, however images and js return a 404
I am creating a Django website and have created a login pages for the website. When I run this on the development server the CSS for the page loads but the images and JavaScript are returning a 404 error. but they are in the same assets folder. Folder Structure: settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'assets')] Login.html: <div class="h-center"> <img class="logo" src="{% static 'assets/base/img/logo/logo.jpg' %}"> </div> I don't understand why it is only loading the CSS files. -
Django - How to use Pagination with filter function?
I am trying to use Pagination with the Django Filter function, But I am getting this error. http://127.0.0.1:8000/product_search/?page=2&search=e Cannot use None as a query value product = Product.objects.filter(productName__contains=name) Here is The view.py function def searchProduct(request): name = request.POST.get("search", None) try: product = Product.objects.filter(productName__contains=name) paginator = Paginator(product, 2) page = request.GET.get('page') page_product = paginator.get_page(page) if page_product: context = { 'searchResults': page_product, 'name': name } return render(request, "Amazon/searchResult.html", context) else: return render(request, "Amazon/searchResult.html", {'message': "No Product Found"}) except Product.DoesNotExist: return HttpResponse("Page Not Found") Here is HTML/Jinja code <nav aria-label="..."> {% if searchResults.has_other_pages %} <ul class="pagination justify-content-center"> {% if searchResults.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ searchResults.previous_page.number }}&search={{ name }}" tabindex="-1"> Previous</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" tabindex="-1">Previous</a> </li> {% endif %} {% for i in searchResults.paginator.page_range %} {% if product.number == i %} <li class="page-item active"> <a class="page-link" href="#">{{ i }}</a> </li> {% else %} <li class="page-item"> <a class="page-link" href="?page={{ i }}&search={{ name }}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if searchResults.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ searchResults.next_page_number }}&search={{ name }}">Next</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">Next</a> </li> {% endif %} </ul> {% endif %} </nav> I have a rough … -
How to use a list field in django
lets say we have model which is an exam (am making an educational website), and the exam has a list of people who have done it, the question is what filed type should i use? class Exam(models.Model): difficulty = models.CharField(max_length=10, choices=[('ez','easy'),('hrd', 'hard')]) module = models.CharField(max_length=10, choices=[('math','math'),('physics', 'physics')]) completed_by = ???????????? (lets assume that there an other module callded user and i want this field to be a list of that users) ` -
How to design database for online examination
I'm working on a project using Django, MySQL in which I need to store the information about the Students and information about the Courses, Subjects, Questions, Result and etc. My goal is to give the services to the students for giving online examinations to know how good they are at the particular Subject just like the JEE, IEEE. I have created these tables in my project : 1. Student_tbl : stuId(PK), name, email, password, mobile, course 2. Course_tbl : courseId(PK), Course_name 3. Subject_tbl : subId(PK), class_id(FK), Subject_name 4. Topic_tbl : topicId(PK), class_id(FK), subject_id(FK), Topic_name 5. Question_tbl : quesId(PK), subjectId(FK), topicId(FK), Question_text, Answer_text, Marks(per question i.e. 2marks for 1 question etc.) 6. Result_tbl : id(PK), studentId(FK), subjectId(FK), Total_Marks My Requirement is: Register the students in the Student_tbl Show them the test paper just like JEE or any other online exams Once they complete the test then based on the performance they can get result from the Result_tbl we're storing the info. Please help me out to achieve this features and also suggest me what the extra column with Foreign Keys or tables should be there , if I have committed any mistakes -
how can pass height and width to the imagekit templatetag?
views.py class imagess(ImageSpec): processors = [SmartResize(100,100)] format = 'JPEG' options = {'quality': 100} register.generator('main:imagess', imagess) index.html {% generateimage 'main:imagess' source=source_file %} this generates a image of height 100 x 100 how can pass/define a custom height and width for the generated image from the HTML file....like {% generateimage 'main:imagess' source=source_file height=1080 width=720 %} -
Django - Show history in admin working but only when actions take place in admin
In Django admin, when you are looking at a record there is a button called "history". When you click on this button, it tells you when the record was created and by whom and also each time a field was changed and by whom. I find this extremely useful. However, I noted that these only show up for actions that are done on the admin page. So when I change the record through a view, this is not displayed in that history. Is there an easy way to have my views store this information also so that it will all be visible from the admin page? Thanks so much in advance for your help. -
Filtered search for MultiSelectField in Django 3
Now that I change some choice fields into multi select fields for usability. When I set up the drop down filtering for sorting using iexact with the MultipleSelectField it is no longer supported. Is there a way to Filtered search for MultiSelectField using unique individual values to find both individual and multiple results. Desired functionality I am try to get to a drop down sort with only one choice of each decade for the multiple select fields that can find. Then the search to find single or multiple select results. Select decade 1950s ... 2000 2010 2020 Currently I was about the front end displays what is created for each new entry so if single of combination it creates a unique entry for each combo or single entry so its kind of ugly and messy. The .distinct() worked good when only one choice per choices but with many possibilities of combinations are now also unique. I assume the iexact no longer working for filtering. Select decade 1950s, 1960s, 1970s ... 2000 2010, 2020 2020 act / views.py # SEARCH BASED-KEYWORD def search(request): act = Act.objects.order_by('-created_date') demographics_search = Act.objects.values_list('demographics', flat=True).distinct() defaultgenre_search = Act.objects.values_list('defaultgenre', flat=True).distinct() decade_search = Act.objects.values_list('decade', flat=True).distinct() genre_search = Act.objects.values_list('genre', … -
get result from Json string to dict in python django
I use serialize to get data in view. contract_posts = serializers.serialize('json', Contracts.objects.all()) Then I use json.loads get data, but I just get 1 by 1 case not all data from model. contract_posts = json.load(contract_posts)[0] print(contract_posts["fields"]) I want to get all data, I try to use for loop but it show error 'str' object has no attribute 'read' my for loop for i in range(100): contract_posts = json.load(contract_posts)[i] print(contract_posts["fields"]["contract"]) i+=1 I dont know how to get len json.load(contract_posts), so I use range 100 as an example number Please help me all -
Django generic class view
I'm new to Django, and I started to learn about the generic views. Indeed they're useful, the problem is I don't know for which purpose each view is used. So, Can somebody help with this? Psst. I read a lot and been searching for an article or post to explain them, but I couldn't find one. -
I am trying to install pip, virtualenv but it is displaying something else, which will be in the description below
traceback (most recent call last): File "/usr/local/bin/pip", line 11, in <module> load_entry_point('pip==21.0', 'console_scripts', 'pip')() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 489, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2843, in load_entry_point return ep.load() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2434, in load return self.resolve() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2440, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/Library/Python/2.7/site-packages/pip-21.0-py2.7.egg/pip/_internal/cli/main.py", line 60 sys.stderr.write(f"ERROR: {exc}") ^ SyntaxError: invalid syntax -
Accessing ID of the latest a django model file upload
I have a django model as below: class excel_upload(models.Model): my_excel_file = models.FileField() I only every have one file uploaded to it. Because i delete the previous one. However i am accessing the path to the file via the ID. The problem with this is that when I delete the old file and upload the new file the id counter for the file needs to increase in order for me to access the newly uploaded file. Does anyone know how i can update automatically pull the latest uploaded file? How i am currently accessing it is by: the_uploaded_excel_file = excel_upload.objects.get(id=11) As you can see this is the 11th time have had to change the id number. -
Django update model instance asynchronously
My website has a button to check notifications as a drop down while still remaining on the same page. I would like to update the field unread of every notification from Trueto False of that user when the button is clicked, without having to change or update the page. I have been looking into Celery to solve this, but before digging to deep I would like to ask the community on what the best practice is to solve this type of functionality. -
why object field changed in api get request?
i want test my api so i wrote test and run my test that works well.but when i run another irrelevant (GET) API my previous test do not work and have strange behavior When the following code is executed from another api: api1 query_set = (Project.objects.all() .annotate( name=Substr( Cast(TruncMonth("created_at"), output_field=CharField()), 1, 7 )) .values("name") .annotate(slug=Concat(V("en-"), "name")) .order_by("name") .distinct() ) return Response( data=ProjectArchiveListSerializer(query_set, many=True).data, status=status.HTTP_200_OK, ) i see this behavior from test: in test of api2 print(Project.objects.all().values('overview','title','text',"slug")) response = self.client.get("/api/v1.0.0/projects/project/pslug-1/") print(Project.objects.all().values('overview','title','text',"slug")) and object field changed like this: output of api test2 <MultilingualQuerySet [{'slug': 'pslug-1', 'overview': 'ov-project-1', 'text': 'text-project-1', 'title': 'project-title1'}]> <MultilingualQuerySet [{'slug': 'pslug-1', 'overview': '', 'text': '', 'title': ''}]> can help me why did this happen and what should I do? -
Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x053A7E68>
I'm trying to create a shopping cart api with django rest framework. I created my view and serializer and urls . but when I want to test my api with postman i have this error: Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x053A7E68>. I want to add a product to my cart. my authentication system is token authentication. I'll pass the token in the header of the request but still I have that error. i will share my code here: serializers class OrderItemSerializer(serializers.ModelSerializer): product = serializers.SerializerMethodField() final_price = serializers.SerializerMethodField() class Meta: model = OrderItem fields = ( 'id', 'product', 'quantity', 'final_price' ) def get_product(self, obj): return ProductSerializer(obj.item).data def get_final_price(self, obj): return obj.get_final_price() class OrderSerializer(serializers.ModelSerializer): order_items = serializers.SerializerMethodField() total = serializers.SerializerMethodField() class Meta: model = Order fields = ( 'id', 'order_items', 'total', 'coupon' ) def get_order_items(self, obj): return OrderItemSerializer(obj.products.all(), many=True).data def get_total(self, obj): return obj.get_total() #views: class AddToCartView(APIView): def post(self, request, *args, **kwargs): slug = request.data.get('slug', None) if slug is None: return Response({"message": "Invalid request"}, status=HTTP_400_BAD_REQUEST) product = get_object_or_404(Product, slug=slug) order_item, created = OrderItem.objects.get_or_create( product=product, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if …