Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Check if pk list is present within given Django Model table in a SINGLE query
So let's say I want to implement this generic function: def do_exist(pks:list[int], model: django.db.models.Model) -> bool Which checks if all the given primary keys exist within a given model. I've implemented something like this from django.db.models import Exists def do_exist(pks, model): chained_exists = (Exists(model.objects.filter(pk=pk_i)) for pk_i in pks) qs = model.objects.filter(*chained_exists).values("pk")[:1] # Limit and values used for the sake of less payload return len(qs) > 0 It generates a pretty valid SQL query, but the thing that scares me is that if I try to append evaluating METHOD call to qs like .first() instead of [:1] or .exists() or .all() MYSQL connection drops. Does anyone have a more elegant way of solving this? -
django Concat queryset can not show in template html
Thank you for help. I want to show the queryset in table, I tried to merge two tables, however, After merger with Concat function. I can not get the search. before merge I can get the table with my search. such as: return object_list will get table but object_list2 only have bland page def get_queryset(self): query=self.request.GET.get('q') object_list = object_list1.prefetch_related("Sequence_ID") object_list2=object_list.annotate(mutation_mer=Concat('mutation_site',V(''),'mutation', output_field=CharField())) return object_list2 here is my template html cod <body> <h1>Search Results</h1> <table> <tr> <th>mutation_site</th> <th>mutation</th> </tr> {% for mutation in object_list %} <tr> <td>{{ mutation.mutation_site }}</td> <td>{{ mutation.mutation }}</td> </tr> {% endfor %} </table> </body> -
reverse('rest_framework:login', current_app=request.resolver_match.namespace) returns a weird path
I am working on a Django Rest Framework API. I was encountering an issue with my project where I keep getting the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'login' with no arguments not found. 2 pattern(s) tried: ['(?P<version>[v1]+)/auth/login(?P<format>\\.[a-z0-9]+/?)\\Z', '(?P<version>[v1 ]+)/auth/login/\\Z'] This error is very weird because in my urls.py class, I used the following pattern: re_path(r'(?P<version>[v1]+)/auth/', include('rest_framework.urls')) I looked at the file rest_framework/urls.py, this is the code inside it: from django.contrib.auth import views from django.urls import path app_name = 'rest_framework' urlpatterns = [ path('login/', views.LoginView.as_view(template_name='rest_framework/login.html'), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), So, I had no idea why the two patterns tried by the resolver were '(?P[v1]+)/auth/login(?P\.[a-z0-9]+/?)\Z' '(?P[v1]+)/auth/login/\Z' since the path in rest_framework/urls.py is just 'login/', not 'login(?\.[a-z0-9]+/?\z' or the latter. In order to replicate the error, I created a new simple DRF API: views.py: from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse @api_view(['GET']) def root(request, format=None): return Response({ '/': reverse('root', request=request, format=None), 'login': reverse('rest_framework:login', current_app=request.resolver_match.namespace), }) urls.py: from django.urls import re_path, include from demo.views import root urlpatterns = [ re_path(r'', root, name='root'), re_path(r'/auth/', include('rest_framework.urls')), ] When I sent a GET request to /, I got the following response: HTTP 200 OK Allow: GET, OPTIONS Content-Type: application/json Vary: Accept { … -
ManytoManyField or Foreign Key, what to use and how to do it -Django User review system
Alright, so I am in the middle of developing a user access review program where managers can authenticate into the system and have their direct reports listed on a webpage and can then approve/deny the access their employees have. We want to run these review campaigns periodically throughout the year to stay in compliance with our standards. I'm just having some issues when trying to create the model for the campaign. I've included the employee model here for reference, essentially I load all employees into the database and then use a management command to create the employee/manager relationship. class employee(models.Model): pid = models.CharField(max_length=20) firstName = models.CharField(max_length=200) middleInit = models.CharField(max_length=20, null=True) lastName = models.CharField(max_length=200) title = models.CharField(max_length=200) email = models.CharField(max_length=200) managerId = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='employees') managerEmail = models.CharField(max_length=200, null=True) enabledAD = models.CharField(max_length=20, null=True) acsPerms = models.CharField(max_length=200, null=True) enabledACS = models.CharField(max_length=20, null=True) accessCorrect = models.BooleanField(default=False) def __str__(self): return (self.firstName + " " + self.lastName + " (" + self.pid +")") @classmethod def createEmp(cls, **kwargs): employee = cls.objects.get_or_create( managerEmail = kwargs['ManagerEmailAddress'], pid = kwargs['SamAccountName'], firstName = kwargs['GivenName'], middleInit = kwargs['Name'], lastName = kwargs['Surname'], title = kwargs['title'], email = kwargs['UserPrincipalName'], enabledAD = kwargs['Enabled'], ) The main problem I'm having is getting the … -
DRF: How to use urls with UUID
So, I would like top stop ursing urlpatterns and just use router. But instead of using ID of an object I'm using UUID instead and I'm using it with urlpatterns and dont't find some way to use it with routers. this is my current model: class Board(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200, blank=False, null=False) this is my core app urls.py: ... router = DefaultRouter() router.register(r'boards', BoardViewSet) router.register(r'y', yViewSet) router.register(r'z', zViewSet, basename='z') urlpatterns = [ path('', include(router.urls)), path('board-list/<uuid:pk>/', BoardViewSet.as_view({'get': 'list'}), name='boards'), ] and this is the project urls.py: from django.contrib import admin from django.urls import path, include from core.urls import router as api_router routes = [] routes.extend(api_router.urls) urlpatterns = [ path('api/', include((routes, 'board_microservice'), namespace='v1')), path('admin/', admin.site.urls), ] the application usage is ok, but I have some troubles with test. i.e: this works well: url = reverse('v1:board-list') response = api_client().get( url ) and it isn't working: board = baker.make(Board) url = reverse('v1:board-list', kwargs={"pk": board.id}) response = api_client().get(url) I receive django.urls.exceptions.NoReverseMatch: Reverse for 'board-list' with keyword arguments and I think I can replace urlpatterns by router to solve it and turns it more simple There is any way to do it with router? -
Which Django ORM or raw SQL I should write to get exactly what I need
I'm using Postgresql as I have model class EventsList(CreatedUpdatedMixin): start = models.DateTimeField() end = models.DateTimeField() is_inner = models.BooleanField() Assume that I have those DB entries: | start | end | is_inner | | --- | --- | --- | | 2021-12-09 14:30:12 | 2021-12-09 15:00:21 | true | | 2021-12-09 14:00:05 | 2021-12-10 21:00:15 | false | | 2021-12-10 09:00:39 | 2021-12-10 09:30:50 | true | | 2021-12-10 14:00:00 | 2021-12-11 15:00:00 | true | | 2021-12-14 10:00:00 | 2021-12-14 11:00:00 | true | | 2021-12-13 13:30:00 | 2021-12-16 14:30:00 | false | | 2021-12-14 13:10:00 | 2021-12-15 00:30:00 | true | | 2021-12-14 10:30:00 | 2021-12-16 13:34:00 | false | | 2021-12-15 13:30:00 | 2021-12-15 18:30:00 | true | And there is the result I need: [ {"2021-12-09": {"external_events": 1, "internal_events": 1}}, {"2021-12-10": {"external_events": 0, "internal_events": 2}}, {"2021-12-11": {"external_events": 0, "internal_events": 1}}, {"2021-12-13": {"external_events": 1, "internal_events": 0}}, {"2021-12-14": {"external_events": 2, "internal_events": 2}}, {"2021-12-15": {"external_events": 2, "internal_events": 2}}, {"2021-12-16": {"external_events": 2, "internal_events": 0}}, ] So I want to get all existing dates and for each date get the count of external events (where is_inner == False) and the count of internal events (where is_inner == True). How can I do … -
TypeError: $(...).textcomplete is not a function inside Django
I'm trying to implement $('textarea-selector').textcomplete method from https://github.com/ranvis/jquery-textcomplete/blob/master/jquery.textcomplete.js in Djnago Textarea widget. django/forms/templates/django/forms/widgets/textarea.html {% load static %} <textarea name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> {% if widget.value %}{{ widget.value }}{% endif %}</textarea> <script src="js/tasks/jquery-1.10.2.min.js"></script> <script src="js/tasks/jquery.textcomplete.min.js"></script> <script type='text/javascript'> $('#id_{{ widget.name }}').textcomplete([ { words: ['select', 'from', 'fct_table1', 'fct_table2', 'where', 'column1', 'column2'], match: /\b(\w{2,})$/, search: function (term, callback) { callback($.map(this.words, function (word) { return word.indexOf(term) === 0 ? word : null; })); }, index: 1, replace: function (word) { return word + ' '; } } ]) </script> But get errors: At the same time if I do the same in simple html file everything works well: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-1.10.2.js"></script> <script src="jquery.textcomplete.js"></script> </head> <body> <textarea class="textarea" id="textarea" rows="4" cols="50">...</textarea> <script> $('.textarea').textcomplete([ { // tech companies words: ['select', 'from', 'fct_table1', 'fct_table2', 'where', 'column1', 'column2'], match: /\b(\w{2,})$/, search: function (term, callback) { callback($.map(this.words, function (word) { return word.indexOf(term) === 0 ? word : null; })); }, index: 1, replace: function (word) { return word + ' '; } } ]); </script> </body> </html> How to make the script work inside Django?strong text -
Django rest framework multiple endpoints for one page at frontend
First time im building api's for SPA. And now i wonder how to do some of them right. For example, we all have delivery club app and main page of a restaurant has banners, some info about, categories, products. Product detail pop up has info about product, measure units, modifiers, additivies and some more options. So i understand how to build api's for admins dashboard but how to do it for clients app? They should be all seperated and front-end will get them all together or my serializers should be nested? Can someone tell? -
Serializing Related Data in Django using Natural Foregin Keys (Three Models, Two Layers)
I've got three models, Product, ProductRelease, and ReleaseNote that all inherit from an abstract model factory (with common fields) with the following relationships: class Product(abstract_base_model_factory()): <additional fields> class ProductRelease(abstract_base_model_factory()): <additional fields> product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_releases') class ReleaseNote(abstract_base_model_factory()): <additional fields> product_release = models.ForeignKey(ProductRelease, on_delete=models.CASCADE, related_name='release_notes') I've followed the documentation to serialize these for returning JSON. I used the docs here to set up serialization of natural keys. I can add the additional code, if needed, but it's mostly boilerplate and works with two models in play (ProductRelease and Product or ReleaseNote and ProductRelease). But it's not working with three models in play. For example, if I serialize ProductRelease objects, I can see the Product and fields I specify: { "product_releases": [ { "model": "products.productrelease", "pk": 7, "fields": { "name": "Product Release A", "product": "prod1" } }, { . . . }, ] } However, I want to be able to serialize ReleaseNote objects, but then show the ProductRelease (first foreign key relation) and the Product (second foreign key relation) objects. Can this be done in a single JSON response? -
Django-Storages change s3 bucket on existing object
I have a django app that allows files to be uploaded to an S3 bucket using django-storages. The file is for a part that needs to be approved. Once it is approved, I'd like to move the file to a different S3 bucket. class DesignData(models.Model): file = models.FileField(storage=PublicMediaStorage()) ... class PublicMediaStorage(S3Boto3Storage): location = "media" default_acl = "public-read" file_overwrite = False After approval, I copy the file over to the new bucket using: client.copy_object( Bucket=settings.AWS_APPROVED_STORAGE_BUCKET_NAME, CopySource=copy_source, Key=design_data["s3key"], ) The file gets moved correctly however I need to update my object. How can I update the object? Trying something like myObject.file = "newbucket/myfile.txt" won't work as it is expecting an actual file. I've read I should be able to update the url with myObject.file.url = "newbucketaddress/myfile.txt" but I get an error AttributeError: can't set attribute. Is there a way in django-storages with s3 to update an existing file s3 bucket? -
django.db.utils.OperationalError: no such table when creating new database from scratch
I deleted my database and all my migrations and would like to re-build them from scratch. When I run makemigrations I get the error: django.db.utils.OperationalError: no such table: registration_setting I was able to trace this to my urls.py which reference several views. If I comment this out it builds the migrations fine. urlpatterns = [ url(r'results', views.results, name='results'), url(r'all', views.results_all, name='results_all'), url(r'results_batch', views.results_batch, name='results_batch'), url(r'form', views.RegistrationFormView.as_view(), name='reg_form'), url(r'^$', views.login, name='login'), url(r'tokensignin', views.token_sign_in, name='token_sign_in'), url(r'logout', views.logout, name='logout'), url(r'^ajax/get_course_description$', views.get_course_description, name='get_course_description'), url(r'^not_registered_report', views.not_registered_report, name='not_registered_report'), ] As best as I can tell it is this line from views.py settings_CGPS_REG_TERM = Setting.objects.filter(key="CGPS_REG_TERM").first().value Which in-fact references the Settings table which has not been built yet by migrate. But isn't this a very normal situation? Of course I have code that references values to fetch from tables in my database. Why is makemigrations trying to execute any code whatsoever before creating the underling database tables? Is there some best practice I am not following that is causing this? -
combine data of foreign key table and primary key table using django rest api
I want to display all buyers with book names. output needed: { "city" "buyer_name" "book_name" } I have the code as follows, but the output is different, i am getting book_id instead of book_name. How to get it? models.py class Book(models.Model): book_id=models.BigAutoField(primary_key=True) book_name=models.CharField(max_length=50) def __str__(self): return str(self.book_id) class Buyer(models.Model): buyer_id=models.BigAutoField(primar_key=True) buyer_name=models.CharField(max_length=50) book_id=models.ForeignKey(Book,on_delete=models.CASCADE) city=models.CharField(max_length=50) def __str__(self): return str(self.buyer_id) serializers.py class BookSerializer(serializers.ModelSerializer): class Meta: model=Buyer fields=['city','buyer_name','book_id'] views.py @api_view(['POST'] class BuyerList(request) buyerlist=Buyer.objects.all() ser=BookSerializer(buyerlist,many=True) return Response(ser.data) -
Reportlab SimpleDocTemplate change default font
Working on reportlab with django. In generated pdf Default Font is used Helvetica. But want to change default font from google fonts. Saw previous question on SO but adding to textstyles like below text_styles.add(ParagraphStyle( name='Normal_MyFont', parent=text_styles['Normal'], fontName='MyFont', )) is time consume as in every paragraph it also need to define text_styles like below Paragraph('Hello World', text_styles['Normal_MyFont']) Is there any alternative? -
register=template.library() TypeError: 'module' object is not callable
I have writen a custom filter to show the number of products that has been added to cart page. here's custom filter cart_tags.py from django import template from order.models import Order register=template.library() @register.filter(name="cart_total") def cart_total(user): order=Order.objects.filter(user=user,ordered=False) if order.exists(): return order[0].orderitems.count() else: return 0 navbar.html to show the use the filter {% load cart_tags %} <li class="nav-item"> <a href="{% url 'cart' %}" class="nav-link"> <i class="fa fa-shopping-cart"></i> Cart <span class="badge badge-light">{{ request.user | cart_total}}</span> </a> </li> I have also created init.py in templatetags folder. But it shows me this error in terminal File "C:\Users\ITS\Desktop\my-e-com-project\E_commerce\order\templatetags\cart_tags.py", line 4, in <module> register=template.library() TypeError: 'module' object is not callable Help me with this please -
how to keep a PR's code separate from other branch's PR code?
I am looking for git and GitHub related help. I am working on a project in which I am resolving different issues and creating PRs. last time when I resolved two issues of the same repo having different branches for each PR, what I faced was that I ended up mixing both PRs codes into each other. so I don't know how to keep different PRs codes from each other. -
How to keep values from a queryset?
I have a problem with an update function. I make a queryset to get some objects that I store in a variable. I make some modifications in the base. I do the same queryset again and store it in another variable. The result of my 2 querysets are not equal, but the 2 variables are. def update(self, instance, validated_data): old_priorities = DiscountPriority.objects.filter(machine__in=instance.machines.all()) print(old_priorities) # <QuerySet [<DiscountPriority: Priority 1 of a13 on dzafezfdezaaaa>, <DiscountPriority: Priority 1 of a13 on test19>]> response = super(DiscountSerializer, self).update(instance, validated_data) current_priorities = DiscountPriority.objects.filter(machine__in=instance.machines.all()) print(current_priorities) # <QuerySet [<DiscountPriority: Priority 1 of a13 on dzafezfdezaaaa>]> print(old_priorities) # <QuerySet [<DiscountPriority: Priority 1 of a13 on dzafezfdezaaaa>]> -
My website shows only 'Authentication/index.html' not the content . I am very new to programming language, how to fix this problem
System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. January 13, 2022 - 22:57:16 Django version 2.1, using settings 'gfg.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. -
Ajax request with a response from a different Django View
I am trying to get my head around executing the following idea using Django and Ajax. I already understand how to implement the validation email side of things and the JQuery required to change button colors etc. My question solely relates to how I should set up the Ajax interaction between two different views. What I would like to be able to do is; A 'validate email' button is clicked on a webpage and a request is sent via Ajax to a Django view (validate_view()) - the button changes colour to Orange. Then, validate_view() sends an email with an activation link back to the Django server and activate_view() captures the uidb64 and token and updates the database, job done. My question is, how do I then send a response back to the page? (primarily to change the original button colour to Green) -
DRF: How to add annotates when create an object manually?
Currently I'm trying to create an expected json to use in my test: @pytest.mark.django_db(databases=['default']) def test_retrieve_boards(api_client): board = baker.make(Board) objs = BoardSerializerRetrieve(board) print(objs.data) url = f'{boards_endpoint}{board.id}/' response = api_client().get(url) assert response.status_code == 200 But i'm receiving the following error: AttributeError: Got AttributeError when attempting to get a value for field `cards_ids` on serializer `BoardSerializerRetrieve`. E The serializer field might be named incorrectly and not match any attribute or key on the `Board` instance. E Original exception text was: 'Board' object has no attribute 'cards_ids' Currently cards_idsare added on my viewSet on get_queryset method: def get_queryset(self): #TODO: last update by. #TODO: public collections. """Get the proper queryset for an action. Returns: A queryset object according to the request type. """ if "pk" in self.kwargs: board_uuid = self.kwargs["pk"] qs = ( self.queryset .filter(id=board_uuid) .annotate(cards_ids=ArrayAgg("card__card_key")) ) return qs return self.queryset and this is my serializer: class BoardSerializerRetrieve(serializers.ModelSerializer): """Serializer used when retrieve a board When retrieve a board we need to show some informations like last version of this board and the cards ids that are related to this boards, this serializer will show these informations. """ last_version = serializers.SerializerMethodField() cards_ids = serializers.ListField(child=serializers.IntegerField()) def get_last_version(self, instance): last_version = instance.history.first().prev_record return HistoricalRecordSerializer(last_version).data class Meta: model … -
ValueError: Cannot assign must be a model instance
I'm doing a query to get the chocies from a charfield and assign them. But at the moment I want to save the form in my view I am getting this error. What I can do? ValueError: Cannot assign "'17'": "Con_Transaccioncab.doc_id" must be a "Adm_Documento" instance. In the form I retrieve and assign the options to the field form.py class Con_MovimientosForm(ModelForm): class Meta: model = Con_Transaccioncab fields = '__all__' exclude = ['cab_estado'] widgets = { 'emp_id': HiddenInput(), 'per_id': HiddenInput(), 'suc_id': HiddenInput(), 'cab_numero': HiddenInput(), 'cab_estadocon': RadioSelect, 'cab_escambpat': CheckboxInput, 'cab_fecha': DatePickerInput(format=Form_CSS.fields_date_format, options=Form_CSS.fields_date_opts, attrs={'value': Form_CSS.fields_current_date}), } def __init__(self, *args, **kwargs): self.AIGN_EMP_ID = kwargs.pop("AIGN_EMP_ID") self.AIGN_PER_ID = kwargs.pop("AIGN_PER_ID") # -------------------------------------------------------------------------------------- self.AIGN_OPCIONES = kwargs.pop("AIGN_OPCIONES") self.PERMISOS = [] # para recuperar los permisos de la tabla __json_values = json.loads(json.dumps(self.AIGN_OPCIONES)) self.PERMISOS = recuperarPermisos(__json_values, self._meta.model.get_table_name(self._meta.model)) # -------------------------------------------------------------------------------------- super(Con_MovimientosForm, self).__init__(*args, **kwargs) self.fields['cab_estadocon'].required = False self.fields['cab_numero'].required = False # here I am assigned the choices to the field self.fields['doc_id'] = ChoiceField(label='Acción: ', choices=self.get_choices(), required=False) for form in self.visible_fields(): form.field.widget.attrs['placeholder'] = Form_CSS.fields_placeholder + form.field.label.lower() form.field.widget.attrs['autocomplete'] = Form_CSS.fields_autocomplete form.field.widget.attrs['class'] = Form_CSS.fields_attr_class self.helper = FormHelper(self) self.helper.form_method = 'post' self.helper.form_id = Form_CSS.getFormID(self) self.helper.attrs = Form_CSS.form_attrs self.helper.form_tag = True self.helper.form_error_title = Form_CSS.form_err_title self.helper.form_class = Form_CSS.form_class self.helper.label_class = Form_CSS.fields_label_class self.helper.field_class = 'col-sm-5' self.helper.layout = Layout( Div( DivHeaderWithButtons(instance_pk=self.instance.pk, … -
Spanning relationship to obtain field value with .annotate() and .values() clauses
I'm making some computations using values & annotate on queryset. Let's consider this model: class Foo(models.Model): fk_bar = models.ForeignKey(to=Bar, ....) foo_val = models.IntegerField(...) class Bar(models.Model): attr = models.Charfield(...) val = models.IntegerField(...) So I can do: Foo.object.all().values("fk_bar") in order to group by the foreign relationship (some Foo might point to the same Bar). Then I can do Foo.object.all().values("fk_bar").annotate(qte=Sum("foo_val")) To the the sum of foo_val for all the object with the same fk_bar, which yields something like: {"fk_bar":<int>, "qte": <int>} However I want the resulting dictionnary to calso contain Bar.attr, e.g. something like: Foo.object.all().values("fk_bar").annotate(qte=Sum("foo_val")).annotate(bar_attr="fk_bar__attr") To get something like: {"fk_bar":<int>, "qte": <int>, "bar_attr":<str>} However that fails (TypeError: Queryset.annotate() received a non-expression). Any ways to go around this? -
Python datetime.today() Showing different time in different python programms
I am having 2 different python file, views.py in django and a test.py .I use test.py to write a specific function and check if iam getting desired output,and if yes, i will copy that code to views.py in my django project. Today i was writting a function to calculate time intervals of 15 mins and populate a list. When i was trying to do print('Today: ',datetime.today()) in test.py it was giving the correct output and a different output in views.py Here's the output in both test.py: Today: 2022-01-13 20:28:45.613094 views.py: Today: 2022-01-13 14:58:25.850835 Note:In my views.py there are other function which uses datetime libraries but iam sure that they are not interfering with each other Here's the Code i use to generate a list of time with interval of 15 mins: def datetime_range(start, end, delta): current = start while current <= end: yield current current += delta def create(): print('Today: ',datetime.today()) #This is where the problem occurs! a=datetime.strftime(datetime.now(),'%I:%M') h=a[0:2] dts = [dt.strftime('%I:%M') for dt in datetime_range(datetime(2022, 1, 1,int(h)), datetime(2022, 1, 1,9), timedelta(minutes=15))] new=[] for d in dts: if datetime.strptime(d,'%I:%M') > datetime.strptime(a,'%I:%M'): new.append(d) return new -
adding a foreignkey set to serializer in django rest framework
I am making a movie-related website and well, every movie or tv show has some trailer videos. I have two models which look like the code provided below. I need to make an API which retrieves an instance of a movie with all it's details. I have done everything that's needed for that and the only thing remaining is returning the details of the trailer videos. The trailer model has a foreignkey field which points to the movie its related to. but I dont know how I can add each movie's video details to the retrieve instance api. Any idea on how I could do that? Models.py class Film(models.Model): filmID = models.AutoField(primary_key=True) title = models.CharField(max_length=150) price = models.PositiveIntegerField() seasons = models.IntegerField(default=1) duration = models.PositiveIntegerField() statusOf = models.IntegerField(default=1, validators=[MaxValueValidator(4), MinValueValidator(1),]) typeOf = models.IntegerField(validators=[MaxValueValidator(4), MinValueValidator(1),]) numberOfFilminoRatings = models.PositiveIntegerField(default=0) filminoRating = models.IntegerField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),]) rating = models.IntegerField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),]) releaseDate = models.DateTimeField(null=True) details = models.TextField() salePercentage = models.PositiveIntegerField(default=0) saleExpiration = models.DateTimeField(auto_now_add=True) filmGenre = models.ManyToManyField(Genre) filmActor = models.ManyToManyField(Celebrity, related_name='actor') filmDirector = models.ManyToManyField(Celebrity, related_name='director') filmProducer = models.ManyToManyField(Celebrity, related_name='producer') def __str__(self): return f"{self.title} {self.releaseDate.strftime('%Y')}" class Video(models.Model): videoID = models.AutoField(primary_key=True) duration = models.PositiveIntegerField() qualityHeight = models.PositiveIntegerField() qualityWidth = models.PositiveIntegerField() sizeOf = models.PositiveIntegerField() directoryLocation = models.TextField() film = … -
'DataFrame' object has no attribute 'value_counts' in pandas 0.25
I am using pandas==0.25.0 django-pandas==0.6.1 And I am using value_counts() to group for unique valor in two columns: charges_mean_provinces = whatever.objects.filter(whatever = whatever).values('origin_province','destination_province') df_charges_mean = pd.DataFrame(charges_mean_provinces) df_charges_mean = df_charges_mean.value_counts().to_frame('cantidad').reset_index() In local (development) it work correctly. But in production (I use Heroku), it return this error. 'DataFrame' object has no attribute 'value_counts' Is there other way to group unique valor from two columns without use value_counts? Considering that I can not change my Pandas version in Heroku. Anyway, value_counts is in pandas 0.25 documentation, so, I do not understand the error. -
AttributeError: module 'purchase.views' has no attribute 'viewPDF'
I get this error after followed an tutorial, and I'm pretty new to this, but cant figure out what is wrong, since i have checked, double checked, triple checked and so on. it's probably a simple error but for me as a beginner it's not simple ;) Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\jenny\appdata\local\programs\python\python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\jenny\appdata\local\programs\python\python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self.kwargs) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\management\base.py", line 438, in check all_issues = checks.run_checks( File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\urls\resolvers.py", line 446, in check for pattern in self.url_patterns: File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\urls\resolvers.py", line 632, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\jenny\Documents\OneDrive Jens privat\OneDrive\Programmering\Django\Nymoen ERP project\env\lib\site-packages\django\utils\functional.py", line 48, in get res …