Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to filter ascending, descending, old price promotional-price to be shown in the public page
if request.GET.get("sort", False): category_products = category_products.filter(old_price=request.GET.get("sort")) -
Django REST how to get output of multiple nested object serializer
Im trying to create an api for a quiz app. I`m working with the Django rest framework to create this API. However, Im stuck with creating a good view for the API. Im not really getting the response I want I tried multiple things but I can't figure it out. The app has videos with questions. The questions have multiple answers, and videos have multiple questions. VideoQuestions model is created for adding the id of the video for the questions. Questions model is created for making questions Question_answers is created for making answers to the questions. The admin side looks like this: The problem: I want to achieve a JSON response that looks like the admin (see image above && what json response I want below). Im not that good with creating an API and working with django rest framework. The response I get now is also shown below. Models.py class VideoQuestions(models.Model): """ Categorize questions per video """ video = models.ForeignKey(Video, on_delete=models.CASCADE) created = models.DateTimeField() class Meta: verbose_name_plural = "E-learner questions" class Questions(models.Model): """ Questions class for the e-learner overlay """ video = models.ForeignKey(VideoQuestions, on_delete=models.CASCADE) question_text= models.CharField(max_length=65) class Meta: verbose_name_plural = "Questions" class Question_answers(models.Model): """ Answers for respected questions """ … -
502 Bad Gateway with nginx
We are using nginx for django application. by this application we can select set of devices to execute some actions like service restart. when we start using this application in more than 4 tabs(execute in 4 list of devices in same time), we are getting "502 Bad Gateway with nginx" randomly. Looking to find a way to increase the capacity of requests in order to allow multiple access in same time. -
how to extract this stores data and store into the js file
i'm getting this error while working with django channels tutorial project F:\djangoprojects\chatproject\mychat>docker run -p 6379:6379 -d redis:5 docker: Error response from daemon: failed to start service utility VM (createreadwrite): hcsshim::CreateComputeSystem 9eb1deb8fc69ee2656d9e049530b329c0fa8ca44a1f6523e9d5a27768fbedb62_svm: The virtual machine could not be started because a required feature is not installed. (extra info: {"SystemType":"container","Name":"9eb1deb8fc69ee2656d9e049530b329c0fa8ca44a1f6523e9d5a27768fbedb62_svm","Layers":null,"HvPartition":true,"HvRuntime":{"ImagePath":"C:\Program Files\Linux Containers","LinuxInitrdFile":"initrd.img","LinuxKernelFile":"kernel"},"ContainerType":"linux","TerminateOnLastHandleClosed":true}). -
Message Persistency with Django-channels and Rabbitmq?
I want to build chat server using django-channels with rabbitmq as channel-layer. And I want persist all messages for each group for archive purposes. Direct solution would be to save the message inside the Consumer of django-channels, but this might be slowing the overall performance because you are calling django ORM synchronously. A better solution I think is to create separate service that is responsible for the persistency. This service should subscribe and store all events pushed into rabbitmq. But to do so I have to know how django-channels integrate with rabbitmq? In other words: does django-channels create fanout exchange for each group? or it use topic exchange? or something else? -
How to add mobile collapsing navarro to django using materialize css?
I have some problems adding a navbar that collapses into a ‘hamburger bar’ at mobile devices and when a device is in split view. This is what I have done so far, the hamburger bar shows but when I click on it nothing happens, my code: <head> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> {% load static %} <link rel="shortcut icon" type="image/JPG" href="{% static 'images/favicon.ico' %}"/> <link href="{% static "tinymce/css/prism.css" %}" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> </head> <body> <div class="navbar-fixed"> <nav> <div class="nav-wrapper teal lighten-1"> <a href="#!" class="brand-logo"><i class="material-icons">assignment </i>Logo</a> <a href="#" data-target="mobile" class="sidenav-trigger"><i class="material-icons">menu</i></a> <ul class="right hide-on-med-and-down"> <li><a href="/">Home</a></li> <li><a href="/newsroom">Newsroom</a></li> </ul> </div> </nav> </div> <ul class="sidenav" id="mobile"> <li><a href="/">Home</a></li> <li><a href="/newsroom">Newsroom</a></li> </ul> <script language="javascript"> document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('.sidenav'); var instances = M.Sidenav.init(elems, options); }); </script> <div> {% block content %} {% endblock %} </div> </body> <script src="{% static "tinymce/js/prism.js" %}"></script> I think the problem is about the javascript part, but I can’t solve it. Thanks from now! -
Django: Filter on a pk with ManyToManyField gives as many element as in m2m relation
I'm really confused with my Django Model. Models.py class Category(models.Model): id = models.CharField(max_length=100, primary_key=True) name = models.CharField(verbose_name="Category name", max_length=400, unique=False) slug = models.SlugField(max_length=151, unique=True, editable=False, null=True) def __str__(self): return self.id def save(self, *args, **kwargs): self.slug = slugify(self.name)[:50] + '-' + str(self.id) super(Category, self).save(*args, **kwargs) class Product(models.Model): objects = ProductManager() code = models.BigIntegerField( primary_key=True, unique=True) # TROUBLE SEEMS TO BE HERE... name = models.CharField(max_length=100, null=True, verbose_name="Nom") slug = models.SlugField(max_length=100, unique=True, blank=True, null=True) nutritionGrade = models.CharField( max_length=1, null=True, verbose_name="Nutriscore") image = models.URLField(null=True) category = models.ManyToManyField( # ...AND HERE Category, related_name="category", verbose_name="Catégorie") compared_to_category = models.ForeignKey( Category, on_delete=models.PROTECT, null=True ) Test_commands class TestDuplicates(TestCase): @patch('products.management.commands.init_db.requests.get') def test_init_nutella(self, mock_request): # replace json by a small mock openff request with only 3 product mock_request.return_value.json.return_value = NUTELLA call_command('init_db') self.assertEquals(len(list(Product.objects.filter(code=3017620422003))), 1) This test call the custom command init_db to populate my DB. In the mock NUTELLA product with code 3017620422003 has 7 categories in the ManyToManyField category. I get a AssertionError: 7 != 1 and I can't understand why since a filter on a primary_key should return a unique element. What am I doing wrong ? Other example in my real database here with 4 categories (event using distinct) : >>> Product.objects.get(code=8000500310427) <Product: Nutella biscuits> >>> Product.objects.filter(name__contains="Nutella biscuits") <QuerySet … -
Django: Retrieve pk for every object in ListView
I have a Dictionary view that shows the list of words created by a specific (special) user: class Dictionary(FilterView): model = Word template_name = 'vocab/dictionary.html' context_object_name = 'dict_list' paginate_by = 15 filterset_class = WordFilter strict = False def get_queryset(self): qs = self.model.objects.filter(user__username__iexact='special_user') return qs def get_object(self): queryset = qs pk = self.kwargs.get('pk') if pk is None: raise AttributeError('pk expected in url') return get_object_or_404(queryset, pk=pk) Now I want any user to be able to come to this page and add any word that they want to, like this: def custom_create_word(request, object): if request.method == 'POST': pass if request.method =="GET": from .forms import WordForm from .models import Word word = Word.objects.get(pk=object) user = request.user target_word = word.target_word source_word = word.source_word deck_name = "My Words" fluency = 0 new_word, created = Word.objects.get_or_create(user=user, target_word=target_word, source_word=source_word, deck_name=deck_name, fluency=fluency) return HttpResponseRedirect(reverse('vocab:dict')) Everything works as expected. But in the template I want the button to look different depending on whether the logged in user already has this word in their own list (which should be judged by if target_word is the same). My template looks like this: <tr> {% for word in dict_list %} <td>{{word.target_word}}</td> <td>{{word.source_word}}</td> <td> {% if user_word %} <a href="" class="btn btn-success btn-sm" >Added</a> … -
How to pass field value from one model object to another?
Oh my... It is kind of a basic question, but I tried many solutions, but nothing works for me and I cannot find the similar question to mine... I have two models: class ForQuery(models.Model): id=models.BigAutoField(primary_key=True) dep_sch = models.ForeignKey('DepDict', models.DO_NOTHING, db_column='dep_sch', blank=True, null=True) code_dep_sch = models.CharField(max_length=5, blank=True, null=True) class DepDict(models.Model): department = models.CharField(primary_key=True, max_length=35) code = models.CharField(max_length=5) I have all minimal meta for these Models incuding get_absolute_url and str . I have defined url for the function in view which I am using in the template. I am matching both models by department in DepDict and dep_sch in ForQuery and in the template, based on this match I can print easily the code for the dartment, like so: {% for d in c%} {% if forquery.dep_station == d %} {{ d.code }} {% endif %} {% endfor %} Now, based on this match, I cannot save referenced field code from DepDict to field code_dep_sch from ForQuery. How would I approach this task? My view function looks like this so far: class MetalDetailView(generic.DetailView): model=ForQuery def get_context_data(self, **qwargs): content = super(MetalDetailView, self).get_context_data(**qwargs) content['c'] = DepDict.objects.all() self.code_dep_sch = c.code #this didn't work self.save() return conObject Trying to using object.field_name doesn't work... Thank you for … -
ModuleNotFoundError: No module named 'django_assets'
Whenever i am trying to use my manage.py I get this error. Please, can someone help me with this? Traceback (most recent call last): File "src/youla/manage.py", line 26, in <module> execute_from_command_line(sys.argv) File "C:\Users\bagzh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\bagzh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\bagzh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\bagzh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\bagzh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\bagzh\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_assets' Fatal error: local() encountered an error (return code 1) while executing 'python src/youla/manage.py makemigrations is_free_user' Aborting. [localhost] local: python src/youla/manage.py makemigrations is_free_user``` -
Conftest.py is not loaded from a subfolder
The thing is that I need to have a conftest with a special setting for a set of tests. To use a live database in readonly mode only for these tests. Other tests from unit folder working with an empty db created by pytest. If I run pytest tests or pytest tests/unit conftest from tests_readonly_db are not recognized. It is recognized when I put conftest file in unit folder. And run any of these two commands. But it works perfectly when I run pytest tests/unit/tests_readonly_db with conftest in tests_readonly_db folder. Also tried to creat another subfolder in tests_readonly_db, put tests in there, with conftest.py staying level up. Doesn't work. I wonder if there is way to implement desired behaviour. Found some related answers, but couldn't fully understand how it helps in my case. For example: https://stackoverflow.com/a/13686206/7744657 But if conftest.py files from sub directories are by default not loaded at tool startup. Why it was loaded from a unit folder? conftest.py import pytest @pytest.fixture(scope='session') def django_db_setup(): """Avoid creating/setting up the test database""" pass @pytest.fixture def db_access_without_rollback_and_truncate(request, django_db_setup, django_db_blocker): django_db_blocker.unblock() request.addfinalizer(django_db_blocker.restore) App structure: -
How to update other table's fields using Post request in Django Rest
I'm new to Django and I am having issues updating the other table's fields when Posting or creating new entry. I am not sure how to. And I have been figuring this out for 2 days on how to do this through serializer or better implement it if it's not through serializer. Basically, I want to update the Fruits' status every time I create a delivery. So I can say if it's available or not. Below are the code snippet. This is my model: class Delivery(models.Model): delivery_type = models.CharField(max_length=60) driver_name = models.CharField(max_length=60) def __str__(self): return self.delivery_type class Fruits(models.Model): name = models.CharField(max_length=250) status = models.CharField(max_length=250) delivery = models.ManyToManyField(Delivery, related_name='fruits') def __str__(self): return self.name This is my serializer: class FruitSerializer(serializers.ModelSerializer): class Meta: model = Fruits fields = "__all__" class DeliverySerializer(serializers.ModelSerializer): fruits = FruitSerializer(many=True) class Meta: model = Delivery fields = "__all__" def create(self, validated_data): delivery = Delivery.objects.create( delivery_type = validated_data['delivery_type'], driver_name = validated_data['driver_name'] ) #update the status field in Fruits Table fruits = validated_data.get('fruits') for fruit in fruits: fruit_data = Fruits( id = fruit['id'], status = "Not Available", delivery=delivery ) fruit_data.save() return delivery This is my view: class DeliverySerializerView(APIView): def post(self, request): serializer = DeliverySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return … -
How to make the characters dispalyed in django input text box as not human readable
How to make the characters dispalyed in django input text box as not human readable. For example, if I have a sensitive field like bank account number, I wanted to show the value as '*********'. Instead of showing the actual value. Just to secure the value I tried with changing my text input widget to password input, but the problem with that is , it doesnt display '*********' . and form assumes it as an empty value and when I submit it gives error to enter value for it. Your ideas will be much appreciated. Thanks Benny Varughese -
Django: How to add products to order model as whatever I try its showing ManyRelatedManager' object has no attribute 'add' or filter or similar error
Hello I am trying to learn developing a ecommerce website, and in the order model, I have this product with manytomany relation with order item. so whenever an order is processed, I would like to add the products from order item model to this product object of order model. How to implement this? Please have a look at the code. class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) product = models.ManyToManyField('OrderItem', related_name='ordered_products') date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=200, null=True, unique=True) payment = models.ForeignKey('Payment', on_delete=models.SET_NULL, blank=True, null=True) received = models.BooleanField(default=False) orderitem class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, blank=True,) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1, blank=True, null=True) views.py def processorder(request): transaction_id = create_transaction_id() data = json.loads(request.body) user = request.user order, created = Order.objects.get_or_create(user=user, complete=False) items = order.orderitem_set.all() total = float(data['form']['total']) order.transaction_id = transaction_id order.items = items if total == order.get_cart_total: order.complete = True order.save() if order.shipping == True: ShippingAddress.objects.create( user=user, order=order, address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], zipcode=data['shipping']['zipcode'], ) return JsonResponse('Payment Complete', safe=False) How can I add the products ordered to the order model? Help would be much appreciated. -
How do i save/show manytomany field in select option field
I am working on a project where users can upload a post, edit a post and tag other users. I was able to implement upload post, edit and tag users (I implemented tag users with jquery ui). When i want to edit a post i have already tagged users on, i do not get the names of the users on select option field, instead it shows empty. How do i save/show users already tagged users from manytomany field in select option field in template. I will attach images to my question for clarity. These are the users i tagged on my post, showing in manytomany field: This image below is what i want, when i want to edit my post, let all tagged users of that post be shown in select option field: Views.py: def update_post_view(request, id): #update post post = get_object_or_404(Post, id=id) edit_form = PostForm(request.POST, instance=post) if request.method == "POST": if edit_form.is_valid(): edit_form.save() return redirect('site:comments', id=id) else: edit_form = PostForm(instance=post) #Tag username dropdown in form tag_list_users = User.objects.all() context = { 'edit_form': edit_form, 'post':post, 'tag_list_users': tag_list_users, } return render(request, 'update_post.html', context) Template: <label for="id_tag_someone">Tag someone:</label><br> <select name="tag_someone" id="id_tag_someone" multiple="" class="chosen w-100"> {% for user in tag_list_users %} <option value="{{user.pk}}">{{user}}</option> … -
Long running connection as part of my Django app
I would like to have a websocket client connection as part of my Django app. I want to listen to events and do stuff with those inside my Django world. Is there a clean way to pack something like that into the app startup? Do I put it in asgi.py or somewhere else? -
Compile python django files to run on server without storing raw codes?
I want to know is there any way to compile python Django files for running them on a server without storing main .py files? I mean like ASP.Net files, which can be compiled and make binary files in order to limit access to codes. -
Blank posts being added, as well as the user created post (Django)
Whenever you click on the Add a post button on my forum page, it will instantly add a blank post to the forum, while still adding the user-created post. Before Add a post is clicked: After Add a post is clicked (but no post details are added): I've had a go at changing the view I made for creating posts, but I ended removing the ability to add a post at all! So, wanted to see if anyone had any idea why blank posts were being added, as well as the post the user creates? View used for adding posts: @login_required def create_forum_post(request, pk=None): """ Create a view that allows us to create a post """ post = get_object_or_404(Post, pk=pk) if pk else None if not post: post = Post.objects.create(creator_id=request.user) if request.method == "POST": form = ForumPostForm(request.POST, request.FILES, instance=post) if form.is_valid(): post = form.save() return redirect('forum_post_details', post.pk) else: form = ForumPostForm(instance=post) return render(request, 'forum_post_form.html', {'form': form}) Post model: class Post(models.Model): creator_id = models.ForeignKey(User, null=False, default=1) title = models.CharField(max_length=200) content = models.TextField() created_date = models.DateTimeField(auto_now_add=True) published_date = models.DateTimeField(blank=True, null=True, default=timezone.now) views = models.IntegerField(default=0) category = models.CharField(choices=CATEGORY_CHOICES, max_length=30, blank=True, null=True) image = models.ImageField(upload_to="img", blank=True, null=True) def __str__(self): return self.title -
Query all objects by date | Django REST framework
I would like to add an URL like 'reports//month/' and list all the reports that I have for that month of that year Currently, my view.py is like that : class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer class ReportGroupData(ListAPIView): queryset=Report.objects.annotate(month=TruncMonth('date')).values('month').annotate(count=Count('id')).values('month', 'count').order_by('-month') serializer_class = ReportGroupMonthSerializer In Django I did it like this : urls.py : path('reports/<int:year>/month/<int:month>', ReportMonthArchiveView.as_view(month_format='%m'), name='report_archive_month'), Views.py : class ReportMonthArchiveView(MonthArchiveView): template_name = 'dashboard/reports_month.html' queryset = Report.objects.all() date_field = "date" allow_future = True paginate_by = 7 What are the steps to have something similar in DRF? Thanks! -
deleting data from the model django after a certain time
my model : class Registration(models.Model): fio = models.CharField(verbose_name = 'fio', max_length = 100, null=True) phone = models.CharField(verbose_name ='phone', max_length = 16, null=True) date_register = models.DateTimeField(verbose_name = 'date registers', max_length = 100, null=True) date_visit = models.DateField(verbose_name = 'date visit', blank=True, null=True) time_visit = models.CharField(verbose_name = 'time visit', null=True,max_length = 100) verification = models.BooleanField(default=False) upon registration, it must be confirmed by mail. How can automatic deletion of records be implemented if the registration is not confirmed after a certain period of time? decided to use the management command to delete (so far just all unconfirmed). It is launched by the manage.py del command. The code itself: import datetime from django.core.management.base import BaseCommand from django.utils import timezone from registers.models import Registration class Command(BaseCommand): help = 'delete unverified users' def handle(self, *args, **kwargs): regs = Registration.objects.filter(verification__in=["False"]) for a in regs: if a.date_register <= (datetime.datetime.now() - datetime.timedelta(minutes=10)): rg = Registration.objects.get(date_register = a.date_register.strftime("%Y-%m-%d %H:%M:%S")) rg.delete() How to make this command work even when the site starts every hour (p.s. after running the manage.py runserver command) -
Error uploading resized image to Google cloud storage
I'm trying to upload a resized image to google storage, but it throws the following error. Size 9422 was specified but the file-like object only had 9308 bytes remaining. Here is the code below. This works fine in my local machine without google storage. thus, i guess there should be some google setting models.py class Product(models.Model): image=models.ImageField(default='default.jpg',upload_to='productimages') def compressImage(self,uploadedImage): imageTemproary = Image.open(uploadedImage) outputIoStream = BytesIO() imageTemproary = imageTemproary.resize( (400,300) ) imageTemproary.save(outputIoStream , format='JPEG', quality=60) outputIoStream.seek(0) uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % uploadedImage.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None) return uploadedImage def save(self, *args, **kwargs): self.image = self.compressImage(self.image) super(Product,self).save(*args, **kwargs) I Even tried the another method to resize image using thumbnail, but i ran into another error this backend doesn't support absolute paths code below models.py class Product(models.Model): image=models.ImageField(default='default.jpg',upload_to='productimages') def save(self): super().save() img=Image.open(self.image.path) outputsize=(400,300) img.thumbnail(outputsize) img.save(self.image.path) Please help me get the resized image uploaded. -
Unable to commit changes after running pre-commit hooks for django project
here is my pre-commit-config.yaml default_language_version: # force all unspecified python hooks to run python3 python: python3 fail_fast: true repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.3.0 hooks: - id: check-ast - id: check-byte-order-marker - id: check-builtin-literals - id: check-case-conflict - id: check-docstring-first - id: check-json - id: pretty-format-json args: [--autofix] - id: check-merge-conflict - id: check-symlinks - id: check-toml - id: check-vcs-permalinks - id: check-xml - id: check-yaml - id: debug-statements - id: detect-aws-credentials - id: detect-private-key - id: end-of-file-fixer - id: file-contents-sorter - id: fix-encoding-pragma - id: forbid-new-submodules - id: mixed-line-ending - id: name-tests-test - id: no-commit-to-branch args: [--branch, develop, --branch, master] - id: requirements-txt-fixer - id: sort-simple-yaml - id: trailing-whitespace - repo: https://github.com/pre-commit/mirrors-autopep8 rev: v1.4.4 hooks: - id: autopep8 - repo: https://github.com/pre-commit/pre-commit rev: v1.18.3 hooks: - id: validate_manifest - repo: https://github.com/asottile/pyupgrade rev: v1.25.1 hooks: - id: pyupgrade - repo: meta hooks: - id: check-useless-excludes - repo: https://github.com/ambv/black rev: 19.3b0 hooks: - id: black language_version: python3.7 args: [-S, -l 99, --exclude="migrations|.venv|node_modules"] - repo: https://github.com/egichuri/mirrors-future rev: 1fed4cb06bab1cc93e42b080b6645dd47e029b04 hooks: - id: future - repo: https://github.com/asottile/seed-isort-config rev: v1.9.3 hooks: - id: seed-isort-config - repo: https://github.com/pre-commit/mirrors-isort rev: v4.3.21 hooks: - id: isort After running git add . then git commit, most test pass but then … -
Can Django create a default row in a new table for each row in an existing table?
I have a company table populated with data. The need to introduce branches table has arisen. What mechanic would be used in Django to use the existing data in the company table to create a basic branch entry for each of the existing company entries. "Company A will get a default HQ branch as part of the migration." Is there a way to tie a function to the migration or would I need to create a custom migration that performs the operation after the table creation procedure is handled? -
Javascript qurryselectors not reading classes and ID when used in Django project
when I am working outside Django file, everything works fine with javascript reading classes and Ids like document.querySelector('.class_name').addEventListener. But when loaded in Django projects it gives an error that eventlistner can't read NULL. <script type="text/javascript" src="{% static 'info/js/for_recrs.js' %}"></script> <link href="{% static 'info/css/for_recrs.css' %}" rel="stylesheet" type="text/css" /> {% endblock %} ``` -
can't send post data to api in django
i can't send post data to api using django rest framework. i used postman to send data only user part is adding to the database , the activity of user is rejecting . i can't figure out problem can anyone help me to solve this problem sending post data to api { "name": "karen", "username": "karen", "timezone": "US/Samoa", "activity_periods": [ { "log_in": "2020-06-09T21:53:25.120897Z", "log_out": null }, { "log_in": "2020-06-09T22:02:35.289891Z", "log_out": null }, { "log_in": "2020-06-09T22:03:36.425212Z", "log_out": null } ] } but only the user data is stored the activity is ignored like this { "name": "karen", "username": "karen", "timezone": "US/Samoa", "activity_periods": [] } how can i add activity data to user...? models.py class User(models.Model): name = models.CharField(max_length=20) username = models.CharField(max_length=20) password = models.CharField(max_length=20) timezone = models.CharField(max_length=32, choices=TIMEZONES, default='UTC') def __str__(self): return self.name class Activity(models.Model): user = models.ForeignKey(User, related_name="activity_periods",on_delete=models.CASCADE,null=True, blank=True) log_in = models.DateTimeField(null=True, blank=True) log_out = models.DateTimeField(null=True, blank=True) def __str__(self): return self.user.name serializers.py class ActivitySerializer(serializers.ModelSerializer): class Meta: model = Activity fields = ['log_in', 'log_out'] class UserSerializer(serializers.ModelSerializer): # Passing login Logout to User activity_periods = ActivitySerializer(many=True, read_only=True) class Meta: model = User fields = ['name', 'username','timezone', 'activity_periods'] views.py class ActivityListView(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer name = "activity-list" urls.py path('rest/',views.ActivityListView.as_view()) how …