Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: int() argument must be a string during migrating django model
I am facing a problem after I add a new field as a foreign key: In the beginning, My models was this: class Book(models.Model): title = models.CharField(max_length=150) Later, I have added a foreign-key field for author and my models these belelow: class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): title = models.CharField(max_length=150) author = models.ForeignKey(Author, on_delete=models.CASCADE) After i add new foreign key, i run pythion3 manage.py makemigrations command and it guides me to insert so 1 or 2, I insert 1 and then add timezone.now() later, i tried to run python3 manage.py migrate command, but it throws me following error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' I am not getting how fix this error, can anyone help me to fix this error? Even i am not getting how add new foregin key fields after i run a few makemigrations, Can anyone suggest me in this case? -
Template cannot evaluate database queryset django
I am running through this wired issue. I hope I can describe it well. The case: Suppose that I am having the following types or identifiers: classes = ['classa','classb','classc','classd'] and I am also having for each of the above class, these two subclasses: subclasses = ['suba','subb'] Now, I am going to retrieve data points from the databased filtered on those classes and sub classes using a function in my model name it get_data_filtered(a,b) as follows: context['custom-data'] = ( {c: {subc: self.get_object().get_data_filtered(c,subc)} for c in classes for subc in subclasses}) When printing this context to the console on the view level, everything is fine. However, when passing it to the template and accessing it there, no data is retrieved! When viewing the template using Django Debug Toolbar, the template context shows this: context['custom-data']:'<<triggers database query>>' The syntax in the template level is similar to: {% for i in custom-data.classa.suba %} .... {% endfor %} My analisis I think the queryset never got evaluated this way. I also tried to put .all() and list(...) but getting nothing useful! Can the queryset got evaluated this way? If there is a better way to achieve such task please advice. Django version: 2.2 -
At least 1 field out of 3
I have Book model, with PDF, FB2 and EPUB fields. pdf = models.FileField( verbose_name = "Book file in PDF", null = True, blank = True, validators = [validators.validate_book_ext] ) fb2 = models.FileField( verbose_name = "Book file in FB2", null = True, blank = True, validators = [validators.validate_book_ext], ) epub = models.FileField( verbose_name = "Book file in EPUB", null = True, blank = True, validators = [validators.validate_book_ext], ) All what i want, is, at least one of them should get file. If no one has file, ValidationError should be raised. I already made some sort of validation in overriden save() method: if all(file_.name is None for file_ in [self.pdf, self.fb2, self.epub]): # check that at least one file is uploading raise ValidationError( "At least 1 book file should be uploaded!" ) But, i think there is should be something that looks nicer and works better. It would be nice, if you help me to find multiupload field, or how to "link" them together. List item -
How to pass all request query params to custom filter class in Django-filters?
I am a newbie in Python-Django. I am writing a very simple web app using Postgres DB. I have a modal name Student which have an array field subjects. from django.contrib.postgres.fields import ArrayField class Student: SUBJECT_CHOICES = ( ('science', 'science'), ('math', 'math'), ) name = models.charField(max_length=50) subjects = ArrayField( models.CharField(max_length=20, choices=SUBJECT_CHOICES), default=list ) Now I am using the django-filter library (https://django-filter.readthedocs.io/en/master/index.html) to filter out results. I am writing a custom filter for the subject field which is given below from django_filters.filters import MultipleChoiceFilter class ArrayFilter(MultipleChoiceFilter): def filter(self, qs, value): // filter logic // filter_qs = some_logic(qs, value) return filter_qs Django filter class look like class StudentFilter: subjects = ArrayFilter( field_name='subjects', lookup_expr='contains', ) class Meta: modal = Student Now I want to send queryParams by using & in query as http://127.0.0.1:8000/?subjects=science&subject=math. This work as expected. The value that receives in filter method are ['science', 'math']. If I send some params that are not part of SUBJECT_CHOICES, then the filter method didn't get call. http://127.0.0.1:8000/?subjects=science&subject=history. In this case, the filter won't work, since history is not valid choice. But I want to call filter function in this situation also. If I extend ArrayFilter from Filter (from djang_filter.filters import Filter) instead of MultipleChoiceFilter. … -
Djnago. Create composite primary key
I want create composite promary key like {id, projectt_id}. I remove old tables(all). when i do: python manage.py makemigrations I have a mistake: AssertionError: Model mdm.Group can't have more than one AutoField. change my model: id = models.AutoField(db_index=True, primary_key=False) and add composite primary key as constraints = [ models.UniqueConstraint( fields=['id', 'project_id'], name='unique_group_project' ) ] From docs: By default, Django gives each model the following field: id = models.AutoField(primary_key=True) This is an auto-incrementing primary key. If you’d like to specify a custom primary key, just specify primary_key=True on one of your fields. If Django sees you’ve explicitly set Field.primary_key, it won’t add the automatic id column. Each model requires exactly one field to have primary_key=True (either explicitly declared or automatically added). I just don't understand the problem. If I add AutoField, It's necessarily must PK. How I can resolve problem with Autofield id and composite PK (id, project_id)? -
How to get "nearest" element using django filter or someway
How to get "nearest" element using django filter or someway currently i'm getting Specific_Place | Start_Time(period) 101 | 7 101 | 8 101 | 9 102 | 7 102 | 8 102 | 9 I want to print only nearest "Start_time"(period) like below how should I solve this problem? Specific_Place | Start_Time(period) 101 | 7 102 | 7 This is my django code models.py---------------------------- class Study(models.Model): Number_id = models.CharField(max_length=10) Name = models.CharField(max_length=32) Grade_Point = models.FloatField(default=None) Time = models.CharField(max_length=10) Prof_Name = models.CharField(max_length=10) Class_People = models.IntegerField(default=None) Day = models.CharField(max_length=1) Start_Time = models.IntegerField() End_Time = models.IntegerField() Place = models.ForeignKey(PlaceName, on_delete=models.CASCADE) Specific_Place = models.ForeignKey(Specific, on_delete=models.CASCADE) views.py----------------------------------------- places = "Prime" empty_lecture_in_list=["101","102"] empty_lecture = Study.objects.filter( Place=places, Specific_Place__in=empty_lecture_in_list Day=4, #0~6 mon(0), tues(1), wed(2)... sun(6) Start_Time__gt=132 #this 132 means Time -> 132/12 -> 11 o'clock ) for aa in empty_lecture_in: print(aa.Specific_Place) print(int(aa.Start_Time/12-8)) # this means period -
I want to change the Django list output format
I want to change the Django list output format. I want to change the output format of list The view code is as follows: def team_todo_list(request, team_name): print("team_name : ", team_name) teamId = TeamInfo.objects.get(team_name = team_name).id team_leader_name = TeamInfo.objects.get(team_name = team_name).leader.username print("team_leader_name : ", team_leader_name) team_member = TeamMember.objects.filter(team=teamId) classification_list = Classification.objects.all() team_name= team_name member_array = [] for member in team_member: # print(member.member.id) # nomad_coder, terecal member_array.append(member.member) team_todo_list = Todo.objects.filter(author__in=member_array) print('team_todo_list : ' , team_todo_list) print('team_member : ' , team_member) return render(request, 'todo/team_todo_list.html', { "team_todo_list":team_todo_list, "team_member_list":team_member, "classification_list":classification_list, "team_name":team_name, "team_leader_name": team_leader_name }) The template code is: <table class="table table-bordered" id="todo_list"> <tr> <td>check</td> <td>class</td> <td>manager</td> <td>title</td> <td>remaining time</td> <td>deadline</td> </tr> {% if team_todo_list.exists %} {% for p in team_todo_list %} <tr> <td> <input type="checkbox" id="{{p.pk}}" class="td_check"> </td> <td>{{p.classification}}</td> <td>{{p.author}}</td> <td> <a href="" id={{p.id}} class="title_for_list"> {{p.title}} (<font color="blue"> from {{p.director}}</font> ) </a><br> <a class="badge badge-pill badge-dark" href="{% url "todo:todo_edit" p.id %}">modify</a> </td> <td> {% if p.dead_line %} {{p.remaining_time}} {% else %} {% endif %} </td> <td>{{p.dead_line}}</td> </tr> {% endfor %} <tbody id="tbody_todo"></tbody> {% else %} <tr> <td colspan="5"> <h4>there is no article</h4> </td> </tr> {% endif %} </table> Currently in this format current I want to change it like this. after Thanks for telling … -
The view blog.views.search didn't return an HttpResponse object. It returned None instead
I have the search view : def search(request): if 'q' in request.GET and request.GET['q']: query = request.GET.get('q') results_list = Post.objects.filter(Q(title__icontains=query) | Q(content__icontains=query)) paginator = Paginator(results_list, 4) page = request.GET.get('page') try: results_list = paginator.page(page) except PageNotAnInteger: results_list = paginator.page(1) except EmptyPage: results_list = paginator.page(paginator.num_page) context = { 'title':query , 'results_list': results_list, 'query': query, 'page' : page, } return render(request,'blog/search_results.html',context) the first four search results appear in page 1 but when i move to the next page I got the error message "The view blog.views.search didn't return an HttpResponse object. It returned None instead. " -
Django mixed data between executions
I'm running Django over Apache with mod-wsgi in a Docker Container. When a request is processed by the view and executes a model method, everythins is ok, but when a second request is send, it's like it uses the same model instance from the past execution with the same variable values. For example, when the first file is uploaded, it sets correctly it uploaded path, but when the second file is uploaded, it uses the last upladed path and add the new name to it. This also happens with other methods. class MediaFile(UploadedFile): """ Media File class. Accepts only files with ALLOWED_FORMATS. Store files in FILE_PATH. """ ALLOWED_FORMATS = ['BMP', 'PNG', 'TIFF', 'MP4', 'OGG', 'WEBM', '.AVI'] FILE_PATH = 'images/media/' name = models.CharField(max_length=200, null=False, blank=False, verbose_name='Name') total_frames = models.IntegerField(null=True, blank=True, default=0, verbose_name='No of Frames') upload = models.FileField(upload_to=FILE_PATH, validators=[FileExtensionValidator(ALLOWED_FORMATS)], help_text='Formats permitted: %s' % (', '.join('.' + format.lower() for format in ALLOWED_FORMATS)), verbose_name='File Uploaded' ) def save(self, *args, **kwargs): if not self.pk: self.name = hashlib.sha1((os.path.splitext(self.upload.name)[0] + str(time.time())).encode()).hexdigest() if self.create_folders(['FPGA', 'GPU', 'CPU']): self.upload.field.upload_to = os.path.join(self.upload.field.upload_to, self.name) else: return super().save(*args, **kwargs) self.send_file(['GPU', 'CPU']) -
django - setting a non-nullable field in pre_save
I'm trying to set a non nullable OneToOneField object (which hasn't been set) in the pre_save method. class A(Model): b = models.OneToOneField(B, on_delete=CASCADE) @staticmethod def pre_save(sender, instance, **kwargs): try: instance.b except RelatedObjectDoesNotExist: instance.b = B() instance.b.save() pre_save.connect(A.pre_save, A) Even though the B object gets created and stored in the database, I get this error as if the A object doesn't point to B django.db.utils.IntegrityError: NOT NULL constraint failed: app_a.b_id If I set null=True in the field definition, of course I don't get the NOT NULL constraint failed error. But still, the A object doesn't store the reference to the B object. I'm guessing this is because in the original A object there is no B reference, so when save is executed somehow it doesn't think it should save the b property. Any ideas how to do this? -
New .py script not able to import Django app
I have created a file to hold all of my chart creation in my Django app. Upon importing the app, the script fails. Am I supposed to register the new file somewhere in the Django framework? The new file is housed correctly in the file tree. It is in the main app where my views.py and the like are stored. This is the error I am receiving. Traceback (most recent call last): File "chart_creator.py", line 1, in <module> from device_app import settings ModuleNotFoundError: No module named 'device_app' -
Creating a heatmap usinng HichChart and django
I'm trying to create a heatmap using django and highcharts as the title suggests. For now I think I have a grasp on the basics but right now I have a problem. Suppose that I have a dataset made like this (I use pandas for creating the dataframe in case) A B A 2 3 B 0 1 it's easy to upload the dataframe hardcoding it but is there a library or anything to help if I have everytime a different number of entries? I tried django highcharts and even pandas highcharts but I can't understand how to filter the values to the data field -
Is there a way to determinate the type of request received in a Class Based View with Django Rest Framework?
I have a Django Rest Framework API service that I want to re-use in my frontend app, but I have some doubts related of the best way to determinate the kind of request that the endpoint receive. I have a structure like below: core api web And I call my endpoints from my web app to my api app. At the moment, I'm not using any frontend framework, just only django, so i send data from my web app to api in this way: _customdictionary.custom_dictionary_kpi({"language": 1, "user": 1}), look that I'm not doing a POST request in this case, I just only send a dictionary with 2 values: language and user, that I defined in my serializers: serializers.py class CustomDictionaryKpiSerializer(serializers.ModelSerializer): class Meta: model = CustomDictionary fields = ('user','language') web/views.py class CustomDictionaryView(View): def get(self, request, *args, **kwargs): try: _customdictionary = CustomDictionaryViewSet() _customdictionary.custom_dictionary_kpi({"language": 1, "user": 1}) # Here i send my data '''some logic''' except Exception as e: '''handle exception''' return render(request,template_name='web/dictionary_get.html',status=self.code,context=self.response_data) Then I receive the data in api/api.py with request['field_name'] class CustomDictionaryViewSet(viewsets.ModelViewSet): queryset = CustomDictionary.objects.filter( is_active=True, is_deleted=False ).order_by('id') permission_classes = [ permissions.AllowAny ] pagination_class = StandardResultsSetPagination def __init__(self,*args, **kwargs): self.response_data = {'error': [], 'data': {}} self.code = 0 def get_serializer_class(self): if … -
error in django when crating an instance of inlineformset_factory
I created two models: primary and secondary with one-to-many relationship. Then I create a formset using inlineformset_factory. Then I create an instance of that variable with the argument instane. But when I do that, I get an error: Error: Traceback (most recent call last): File "...\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "...\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "...\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "...\main\views.py", line 14, in regCabinets cabinetsFormset = RegCabinetsFormset(instance=estab) File "...\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py", line 908, in init self.form._meta.fields.append(self.fk.name) AttributeError: 'set' object has no attribute 'append' models.py: from django.db import models import uuid # Create your models here. class Establishments(models.Model): quantity = models.SmallIntegerField(null=True, verbose_name="кол-во") name = models.TextField(verbose_name="имя") index = models.SmallIntegerField(verbose_name="индекс") email = models.EmailField(max_length=255, verbose_name="адрес эл. почты") showEmail = models.BooleanField(verbose_name="показывать эл. почту") address = models.TextField(verbose_name="адрес") showAddress = models.BooleanField(verbose_name="показывать адрес") key = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, verbose_name="ключ") class Meta: verbose_name = "заведение" verbose_name_plural = "заведения" ordering = ['index'] class Cabinets(models.Model): name = models.TextField(verbose_name="имя") ssid = models.CharField(max_length=255, verbose_name="имя wi-fi") password = models.CharField(max_length=255, null=True, blank=True, verbose_name="пароль wi-fi") value = models.SmallIntegerField(verbose_name="объём", default=0) establishment = models.ForeignKey('Establishments', on_delete=models.CASCADE, verbose_name="заведение") class Meta: verbose_name = "кабинет" verbose_name_plural = "кабинеты" ordering = ["value"] forms.py: from django import forms from .models … -
localhost in build_absolute_uri for Django with Nginx
On production I use the chain Django - UWSGI - Docker - Nxing. UWSGI works with the port 50012 and Ngxin is configured as: proxy_pass http://localhost:50012; Django process thinks that its host is localhost:50012 instead of the domain that Nginx listens to. So when the function build_absolute_uri is called there's localhost:50012 instead of my domain. Is there a way to make Django use the custom host name when build_absolute_uri is called? -
How to get current cursor using Django Rest Framework CursorPagination
I need to save the current cursor so users can continue from where they left off. CursorPagination only gives you previous and next cursors. I tried extending CursorPagination class and added current cursor by copying most of their implementation but it seems to be off by one item. class MyCursorPagination(CursorPagination): ordering = '-created_at' max_page_size = 100 def get_current_link(self): cursor = Cursor(offset=0, reverse=False, position=self._get_position_from_instance(self.page[0], self.ordering)) return self.encode_cursor(cursor) def get_paginated_response(self, data): return Response(OrderedDict([ ('next', self.get_next_link()), ('current', self.get_current_link()), ('previous', self.get_previous_link()), ('results', data) ])) def get_paginated_response_schema(self, schema): return { 'type': 'object', 'properties': { 'next': { 'type': 'string', 'nullable': True, }, 'current': { 'type': 'string', 'nullable': False, }, 'previous': { 'type': 'string', 'nullable': True, }, 'results': schema, }, } def get_html_context(self): return { 'previous_url': self.get_previous_link(), 'current_url': self.get_current_link(), 'next_url': self.get_next_link(), } Reference: https://github.com/encode/django-rest-framework/blob/master/rest_framework/pagination.py. -
How can I generate a youtube style unique alphanumeric id model id in django
I want dont want to use the django id directly for viewsets in django, since that potentially reveals the number of items. I already figured out how to generate UUIDs, which work, but are unwieldy and hexadecimal. Is there a way to generate a guaranteed unique sufficently long alphanummeric string in django similar to a uuid? -
Migrate Python QT (PyQT) GUI to HTML CCS Web GUI
We have a Python3 application with a QT GUI, running on a Raspberry PI with Linux. It's something like a panel to show sensor measurements We use Bluepy to acquire data from Bluetooth sensors. We store users, sensors info, and records on a SQL DB. We update the GUI each second to show the new measurements of multiple sensors We send emails with reports of the measurements. The user can start/stop each sensor reading individually using the GUI. We want to migrate the QT GUI to make it looks nicer, currently we have done improvements applying style sheets but we would like something much better like this: https://cmkt-image-prd.freetls.fastly.net/0.1.0/ps/479694/1160/772/m1/fpnw/wm0/detail1-.jpg?1431301354&s=1085f02d6c8bd415277cb269f5f3aca5 We know that Qt has a Web module, but we're going to use this app for future commercial purposes and we cannot afford the Qt prices. I have read about Django, and what I know is: Django is a Web Framework not a GUI, I'll have to create my HTML template using additional tools. Django is a Web Framework not a GUI, it's intended to answer to url requests and so something. Django implies to discard my current DB, with the advantage that Django will handle everything from now. What I don't … -
What Django event catching Clear checkbox?
If you create not null file, or, image field, and enter in admin panel, an additional choice will appear, like on screenshot below. I want to know, what event handling this Clear checkbox, and, how can i disable/override this? -
if condition is not working with string variables in d-jango template
I have a model Book which contains a CharField: 'category' which describes the genre of book and I want to display the information of books according to their genre. I tried this: {% for category in categories %} <div class="row"> <div class="title-section mb-5 col-12"> <h2>Popular in {{category}}</h2> </div> </div> <div class="row"> {% for book in books %} {% if book.category == '{{category}}' %} <div class="col-lg-4 col-md-6 item-entry mb-4"> <a href="#" class="product-item md-height bg-gray d-block"> <img src='/media/{{book.img}}' alt="Image" class="img-fluid"> </a> <h2 class="item-title"><a href="#">{{ book.title }}</a></h2> <strong class="item-price">Rs. {{ book.price }}</strong> </div> {% endif %} {% endfor %} </div> {% endfor %} models.py : def main(request): books = Book.objects.all() categories = [] for book in books: categories.append(book.category) categories = list(set(categories)) return render(request, "index.html", {'books': books, 'categories': categories,}) But this is not working, it displayed only: Popular in fiction Popular in motivational Popular in informative Popular in teen Popular in autobiography No information of any books is displayed. I think there is problem in if condition please help me out! -
How to deploy Python Django project on shared hosting cpanel?
I want to live my django website through shared hosting which I bought from Hostgator. Need help how to deploy Django project though cpanel -
Django: how to store information of multiple logins of the same user from different devices
In Django User model, we store the last_login to know when is the users last login. But assuming i am logging from firefox and chrome browsers and I want to store the information of the device and its login time, how can we do that. Later i can see from where all the devices the user is currently logged in and what times is logged in from those devices. -
Passing variable in Django form that user can't edit
I'd like to generate a random 1-time passcode for a user that appears as a disabled field in a Django form. The passcode will be shown in the form to the user on the page, and the user will not be able to edit it, but it will be submitted with the form. I do not want my users to set their own passcodes, but I want to tell them what their passcode is. What is the best way to ensure that the 1-time passcode that is generated for users is not edited by users? I have been using session variables to remember the value so that I can confirm it has not been tampered with upon submit. def my_page(request): # If submitted if request.method == "POST": # Check to make sure passcode wasn't altered if (request.POST.get('passcode') == request.session['pw']): ... rest of function here ... # Generate passcode and store it the session request.session['pw'] = genRandomPassword() # Init the form with a passcode form = MyForm(initial={'passcode': request.session['pw']}) return render(request, 'example.html', {'form': form}) Is there a better method for accomplishing what I am attempting to do? I think what I am doing works, as long as users can't edit their session … -
Django/DRF - prefetch_related() returning all objects without properly matching the foreign key relationship?
So hey guys I've been running into a problem with my endpoints. I've been trying to use return Player.objects.prefetch_related('playerstatistic_set') to return me the Player objects that match with the objects in the PlayerStatistic model. The PlayerStatistic table currently only has one row so player_id = 1 should be the only one returned but currently the prefetch_related() returns ALL of the Player objects. I've tried going into the PlayerStatistic model and adding a related_name like so - player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='player_stats') and changing the prefetch to prefetch_related('player_stats') but that still just returns all the Player objects as well. Models - class Player(models.Model): # class for Player model name = models.CharField(max_length=100) team = models.ForeignKey(Team, on_delete=models.CASCADE) class Game(models.Model): # class for Game model home_team = models.ForeignKey(Team, related_name='home_games', on_delete=models.CASCADE) away_team = models.ForeignKey(Team, related_name='away_games', on_delete=models.CASCADE) date = models.DateField() class PlayerStatistic(models.Model): # class for individual player statistics game = models.ForeignKey(Game, on_delete=models.CASCADE) player = models.ForeignKey(Player, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) points = models.IntegerField() assists = models.IntegerField() rebounds = models.IntegerField() My get_queryset function in my Player View - class PlayerViewSet(viewsets.ModelViewSet): # ViewSet to display Players queryset = Player.objects.all() serializer_class = PlayerSerializer def get_queryset(self): return queryset.prefetch_related('playerstatistic_set') Of course in my Player Serializer I've tried nesting the PlayerStatistic Serializer … -
Slice behaving differently in Django development than when running under IIS
I am confused. I have a list view which provides links to a detail view. I wanted the detail view to be able to go back to the (calling) list view. There were some reasons that an ordinary back button wouldn't do the trick; so I decided to provide the list view's url to the detail page by assigning request.path to a parameter named last_page. If I am running in the Django development environment on port 8000, last_page|slice:'1:' removes the leading '/' from my variable. When I run the same code under IIS, I have to use last_page|slice:'0:' to do the same thing or I get a NoReverseMatch error when I try to use last_page in my detail template. In my list view template, my URL looks like this: href="{% url 'a-detail' pk=s.s_id last_page=request.path %}" In my detail template, the code I use for the back button looks like this (This is where the slice removes the initial '/' from request.path): <script> document.write('<a href="{% url last_page|slice:'1:' %}">Go Back</a>') </script> In my urls.py file, I am using these url paths (don't really need the one for not passing the parameter any more): path('<int:pk>', views.ADetailView.as_view(), name='a-detail'), path('<int:pk>/<path:last_page>', views.ADetailView.as_view(), name='a-detail'), The views.py file …