Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Link transaction details with Product
I'm trying to link some models together to show what product a user is holding as well as the price they paid and the amount they hold. Which will be displayed within a table. I have Profile Product, Holding models, and want to add a Transaction model that is linked to the Profile, and Holding model to be able to add purchased amount and price. I'm not sure what the best way to link these models is to be able to easily present the data within a table. Models: class Product(models.Model): product_name = models.CharField(max_length=255, blank=False, unique=True) product_slug = models.CharField(max_length=50, blank=True,null=True) product_symbol = models.CharField(max_length=50, blank=True,null=True) product_price = models.FloatField(blank=True,null=True) product_capture_date = models.DateField(blank=True,null=True) product_logo_address = models.URLField(max_length=255, blank=True) def __str__(self): return str(self.product_name) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) products = models.ManyToManyField(Product, blank=True, through='Holding') website = models.URLField(max_length=50, blank=True) twitter = models.CharField(max_length=50, blank=True) meta = models.CharField(max_length=50, blank=True) github = models.CharField(max_length=50, blank=True) def __str__(self): return str(self.user) class Holding(models.Model): product_name = models.ForeignKey(Product, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) product_holding = models.FloatField(max_length=50, blank=True, null=True) def __str__(self): return str(self.product_name) class Transaction(models.Model): product = models.ForeignKey(Holding, on_delete=models.CASCADE) amount = models.FloatField(max_length=50, blank=True, null=True) price = models.FloatField(max_length=50, blank=True, null=True) transaction_date = models.DateField(null=True, blank=True) … -
No matching query Django Model
I want to add to number_of_points (from model Answer) a score (from model Vote) so whenever i save or add new vote i want it to either add +1 or +(-1). But i get this weird error saying that there is no matching query. Answer has to exist in order for vote to even create an instance. class Vote(models.Model): class AnswerScore(models.IntegerChoices): add = 1 subtract = -1 score = models.IntegerField(choices=AnswerScore.choices) answer = models.ForeignKey('Answer', on_delete=models.PROTECT) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) class Meta: unique_together = ('answer', 'user',) class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) @receiver(post_save, sender=Vote) def change_points(sender, created, instance, **kwargs): if created: answer = Answer.objects.get(answer=sender.answer) answer.number_of_points = F('number_of_points') + sender.score Traceback: Traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1653, in … -
call custom function on django model after using values over filter
i have custom function on my model named represent to call this function over queryset i extended queryset and added another custom function named data class DataQuerySet(models.QuerySet): def data(self, name=None): return [obj.represent(name) for obj in super()._chain()] the issue is when i use values for annotate, query set chain contain dict instead of model, so dict object don't have represent function, for example when i using something like this App.objects.values('app').annotate(total_time=Sum("duration")).data() when i call above code return dict object don't have represent function. how can i call my custom model function after using values ? -
Is there any way that you can make JWT in your own custom view?
So I've been trying to learn about JWT and I've used both rest_framework_simplejwt and djoser, and in both of them they provide a view for creating JWT(logging in), and that makes me wonder if there's a way to create JWT in your own custom view? -
Django: add new column by function ( datetimefield to datefield )
Change datetimefield to datefield and put in in new column python ways are useless because i want to be able to use order_by and distinct i don't want to use sorted() and etc my django model is something like this class Product(models.Model): price = models.PositiveIntegerField(null=False, default=0) discounted_price = models.PositiveIntegerField(null=False, default=0) date = models.DateTimeField(auto_now_add=True) And i want to be able to call date() function and put it in another column and order_by it Product.objects.annotate(day=date.date()).order_by('-day').distinct('day') -
Django - quiz app - issue with forms i guess
I'm trying to make an app by using django which allow me to study. for now I have already done it models.py class Question(models.Model): question_text = models.CharField(max_length=200, null=True) answer_text = models.CharField(max_length=200, null=True) date_posted = models.DateTimeField(auto_now_add = True) def __str__(self): return self.question_text class Test(models.Model): name = models.CharField(max_length=200) questions = models.ManyToManyField(Question) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True) date_posted = models.DateTimeField(auto_now_add = True) urls.py urlpatterns = [ path('', views.home, name='home'), path('test/<str:pk>/', views.test), ] views.py def test(request, pk): test = Test.objects.get(id=pk) questions = test.questions.all() form = Answer() context = {'questions':questions, 'form':form} if request.method == 'POST': instance = Question.objects.get(id=pk) form = Answer(request.POST, instance=instance) if form.is_valid(): if request.POST.get("answer").strip() == instance.answer: return redirect('home') return render(request, 'exam/test.html', context) forms.py class Answer(ModelForm): class Meta: model = Question fields = ['answer_text'] answer = forms.CharField(label='Your answer', max_length=100) and my html code: {% for question in questions %} <div class="question-container"> <p>{{question.question_text}}</p> <form method="POST"> <td>{{ form.answer }}</td> {% csrf_token %} <input type="hidden" name="question_id" value="{{ question.id }}" /> <td> <input type="submit" value="submit"> </td> </form> </div> {% endfor %} I haven't implemeted any point counter function. I wanted to be redirected to home page if answer is correct to see if the form works corectly but it is not. Where did i make mistake … -
How to connect a form?
I want to connect the form StockHistorySearchForm. At the same time, this must be done inside the ExpenseListView view. But no matter how I twisted it, for some reason the first form stops working for me. And search by date for some reason is not correctly implemented. Tell me how to connect it? enter image description here enter image description here -
I am facing '__init__(): incompatible constructor arguments.' error
I am trying object detection machine learning through Tensorflw; was following a video by Nicholas Renotte. A year old video and while running the trainning module to covert my xml and jpg file into record files I ran into this error. Tried alot of things and now stuck on what to do next. import os import glob import pandas as pd import io import xml.etree.ElementTree as ET import argparse os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow logging (1) import tensorflow.compat.v1 as tf from PIL import Image from object_detection.utils import dataset_util, label_map_util from collections import namedtuple # Initiate argument parser parser = argparse.ArgumentParser( description="Sample TensorFlow XML-to-TFRecord converter") parser.add_argument("-x", "--xml_dir", help="Path to the folder where the input .xml files are stored.", type=str) parser.add_argument("-l", "--labels_path", help="Path to the labels (.pbtxt) file.", type=str) parser.add_argument("-o", "--output_path", help="Path of output TFRecord (.record) file.", type=str) parser.add_argument("-i", "--image_dir", help="Path to the folder where the input image files are stored. " "Defaults to the same directory as XML_DIR.", type=str, default=None) parser.add_argument("-c", "--csv_path", help="Path of output .csv file. If none provided, then no file will be " "written.", type=str, default=None) args = parser.parse_args() if args.image_dir is None: args.image_dir = args.xml_dir label_map = label_map_util.load_labelmap(args.labels_path) label_map_dict = label_map_util.get_label_map_dict(label_map) def xml_to_csv(path): xml_list = [] … -
Testing Django model throws TypeError
I am trying to test my REST API and am currently testing my models. I am very new at Django and testing in particular. While testing my models I keep getting this error: TypeError: Field 'id' expected a number but got datetime.datetime(2022, ...) I get this error for every model and view so far. Why is this error occurring? How can I get my tests for this model to run? Am I even testing properly? This is one of my models: class Tag(models.Model): name = models.CharField(max_length=256) language = models.CharField(max_length=256) objects = models.Manager() def __str__(self): """Return a human readable representation of the model instance.""" return self.name or '' @property def tags(self): tags = self.tagging.values('tag') return tags.values('tag_id', 'tag__name', 'tag__language') And this is the corresponding test suite for this model: class TagTests(TestCase): def setUp(self): self.tag_name = "name of the tag" self.tag_language = "language of tag" self.tag = Tag.objects.create(name=self.tag_name, language=self.tag_language) def test_name_label(self): tag = Tag.objects.get(id=1) field_label = tag._meta.get_field('name').verbose_name() self.assertEqual(field_label, 'name') def test_tag_size(self): tag = Tag.objects.get(id=1) max_length = tag._meta.get_field('name').max_length self.assertEqual(max_length, 256) def test_str(self): """Test for string representation""" tag = Tag().objects.get(id=1) self.assertEqual(str(tag), tag.name) def test_model_can_create_tag(self): """Test the tagging model can create a tag instance""" old_count = Tag.objects.count() self.tag.save() new_count = Tag.objects.count() self.assertNotEqual(old_count, new_count) -
How and where to call a method in a Class based view Django
As part of a News Years resolution, I have promised to myself that I would learn to write Class Based Views, but as it turns out, I need some help.. What I am trying to do is call a method that generates a random number and then sends an email before the page loads, which I comfortable doing (I'll probably use celery to send the mail in the background). What I don't understand is how and where to call the methods random_code() and send_email() (see below)? Do I do this by overriding setup(), dispatch() or get() etc? Can someone please give me a basic example of what to do? The class is going to look something like this: class VerifyCode(FormView): template_name = "account/verify.html" form_class = VerifyForm def random_code(self): #random_code generator return random_code def send_email(self): #code to send email Many thanks in advance. -
Cross-Origin-Opener-Policy header has been ignored http://0x.0x.0x.0x
I've deployed my Django application on server I'm using Nginx everything is working fine but when I go to admin page I'm not able to log into my page in browserconsole I'm getting this error The Cross-Origin-Opener-Policy header has been ignored,http://0x.0x.0x.0x because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can also use the 'localhost' origin instead. See https://www.w3.org/TR/powerful-features/#potentially-trustworthy-origin and https://html.spec.whatwg.org/#the-cross-origin-opener-policy-header. -
How to access childern of a model in a query set django
I have a model for Products and a model for categories: Each product can have multiple categories and each category can have multiple sub categories for example: categories: -Digital devices: -laptop -smartphone -PC products: Mylaptop1 -category=laptop Myphone2 -category=smartphone i want to filter products using parent category for example when user reach this address : mysite.com/products/digital-devices i want to show both Mylaptop1 and Myphone2. I dont have problem with filtering sub categories but how can i filter using parent category in query set. models.py: class Category(models.Model): name=models.CharField(max_length=200, db_index=True), slug=models.SlugField(max_length=200, unique=True, allow_unicode=True) parent = models.ForeignKey('self', default=None, null=True, blank=True, on_delete=models.SET_NULL,related_name="children") class Product(models.Model): name=models.CharField(max_length=200, db_index=True), slug=models.SlugField(max_length=200, db_index=True, allow_unicode=True), description=models.TextField(blank=True), category = models.ManyToManyField(Category, related_name='products') views.py def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) photos = ProductImage.objects.all() if category_slug: category = get_object_or_404(Category,slug=category_slug) products = products.filter(category=category) # query for sub categories products = products.filter(category__in=[category.children.all]) # i tried to use this query set to get products using parent category but it does not work So how can i access to the products that have children categories using parent category -
How to remove 1 item in a list in Django?
This is the HTML code: <div class="col-sm-2 col-md-2 col-lg-2 col-xl-2 text-center"> {% if show_follow_button %} <button id="follow-btn" class="btn btn-primary" type="button" name="follow" {% if already_follow %}disabled{% endif %}> Follow </button> <button id="unfollow-btn" class="btn btn-primary" type="button" name="unFollow" {% if already_unFollow %}disabled{% endif %}> Unfollow </button> {% endif %} </div> So I have 1 button each for following and unfollowing a user. I'm trying to make the unfollow button remove that specific user in the list of users I've already followed. In my views.py I have this code in 1 of my methods: show_follow_button = False if user_id is not None and user_id != request.user.id: show_follow_button = True already_follow = False already_unFollow = False if show_follow_button: already_follow = user_id in [x.user.id for x in UserExtended.objects.get(user__id=request.user.id).following.all()] already_unFollow = user_id in [x.user.id for x in UserExtended.objects.get(user__id=request.user.id).following.all().delete()] I'm having a hard time making the last line of code work HAHA. Am confused. I don't know how to remove 1 loool. Help -
How to make a function that adds score from another model Django
I want to make an Api for adding points to an answer, so i created this model to secure user not adding 2 points to an answer: class Vote(models.Model): class AnswerScore(models.IntegerChoices): add = 1 subtract = -1 score = models.IntegerField(choices=AnswerScore.choices) answer = models.ForeignKey('Answer', on_delete=models.PROTECT) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) class Meta: unique_together = ('answer', 'user',) The answer model looks like this: class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) i've got a simple viewset and serializer class Vote(ParentKeyAPIView, generics.CreateAPIView): model = Vote parent_model_field = 'answer_id' serializer_class = VoteSerializer def perform_create_kwargs(self, **kwargs): return super().perform_create_kwargs(user=self.request.user, answer_id=self.kwargs['pk'], **kwargs) class VoteSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) answer = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Vote fields = '__all__' And it works, but i want to make sure, that everytime i post this api, the score gets added to Answer.number_of_points. Do you have any idea how to do that? -
Django update form with multiple images
I'm trying to implement product update form with multiple images. I have already done the main form but have stucked with following thing: When user want to update image using formset he can use only square images, so i've implemented custom validation for it. But here is the problem: after the validation the form "current" image and "clear" checkbox disappear. Here is what it is: incorrect form after validation Here is how it should be + validation error message (it's not on the screenshot): correct form after validation The only place where the isse could be is following piece of code form.instance = form.cleaned_data.get('id') fixes the problem when after form submission it shows me an uploaded image (which is not valid by the way), because i receive it from form.instance.image.url: class ProductImageUpdateInlineFormSet(BaseInlineFormSet): def clean(self): super().clean() for form in self.forms: if form.cleaned_data and form.cleaned_data.get('image'): try: square_image_validator(form.cleaned_data.get('image')) except ValidationError as ex: form.instance = form.cleaned_data.get('id') form.add_error('image', ex.message) # FormSet for updating product images ProductImageUpdateFormSet = inlineformset_factory(Product, ProductImage, formset=ProductImageUpdateInlineFormSet, fields=['image'], max_num=3, min_num=1, can_delete=False) class ProductUpdateForm(ProductAddForm): def __init__(self, data=None, files=None, instance=None, **kwargs): super().__init__(data=data, files=files, instance=instance, **kwargs) self.image_formset = ProductImageUpdateFormSet(data=data, files=files, instance=instance, **kwargs) self.fields['price'].initial = instance.price -
TemplateDoesNotExist in get_template in loader.py - Django
Hello, this is the error I'm getting on VS code. I'm using Windows 10. I'm following this course and did exactly as they said. It's still showing me this exception. These are my folders and files. This is from the settings.py file. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This is my loader.py file from the template folder. from . import engines from .exceptions import TemplateDoesNotExist def get_template(template_name, using=None): chain = [] engines = _engine_list(using) for engine in engines: try: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) raise TemplateDoesNotExist(template_name, chain=chain) def select_template(template_name_list, using=None): if isinstance(template_name_list, str): raise TypeError( 'select_template() takes an iterable of template names but got a ' 'string: %r. Use get_template() if you want to load a single ' 'template by name.' % template_name_list ) chain = [] engines = _engine_list(using) for template_name in template_name_list: for engine in engines: try: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) if template_name_list: raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) else: raise TemplateDoesNotExist("No template names provided") def render_to_string(template_name, context=None, request=None, using=None): if isinstance(template_name, (list, tuple)): template = select_template(template_name, using=using) else: template = get_template(template_name, using=using) return template.render(context, request) def _engine_list(using=None): return … -
Build a PoC of OCPP server which can communicate with an EV charger using OCPP protocol
I am new to OCPP protocol and I have the following task involving OCPP protocol which I can not find any documentation about it: build a PoC of OCPP server which can communicate with an EV charger using OCPP protocol.Server should be implemented using Python django. Features needed on server side: Connect an EV charger to server List all connected chargers Authenticate user via RFID Start/stop charging process. I basically do not understand the OCPP server. I think it's like a server that receives the requests from clients and respond them. I also found the python package available in the link here. But I could not find the documentations for this, for example, is there any method to list all connected chargers. Can anyone give me simple demo implementation for this task on Python django? Any help would be aprreciated. -
django receiver only works with superuser status
in my users/models.py I have user creation which works fine. I added this. @receiver(post_save, sender=User) def create_userprofile(sender, instance, *args, **kwargs): up, created = UserProfile.objects.get_or_create(user=instance) if created: logger.debug(f"Created UserProfile for {instance.username} using create_userprofile(*)") up.save() the UserProfile instance it creates only creates with superuser. It doesn't matter I add the user through the normal sign up process or the admin. When I change the status of the user to superuser the receiver is kicked off. I want the receiver code to kick off every time. -
How to add the logged in user email in a field in the model directly without using a view in django
I have a field in my model as shown below uploaded_by = models.CharField(max_length=255, blank=True, null=True, editable=False) This field will store the username (email in this case) of the user who has uploaded the data. As you can see that this is non editable so there is no way the user can edit it. The data has to be entered from the admin pannel. I wanted to know if there is any way to fill this field with the username of the loged in user who is uploading the data. I know if I use the view I can do some thing like uploaded_by = request.user So is there a way to do the same directly in the model so that I can use the admin pannel directly to store the username without using a view. -
How to update model fields from views with values from a href/url?
I'm making a events website, I need to show the event history of a user logged in. Currently I'm only passing Event instance to below template not User instance So when he clicks on Register for Event button on a certain event with id event.id. {%for event in events%} <div class='card-event'> <div style="font-weight: 600; margin-top:5px;font-size: 20px;">{{event.name}}</div> <div style="margin:10px 0 5px 0;">{{event.event_desc}}</div> <div style="margin:5px 0 10px 0;">Entry Fee: {{event.entry_fee}}</div> <a href="{%url 'update-event' value1=user.id value2=event.id%}"><button class='register-button'>Register for Event</button></a> </div> {%endfor%} He is redirected to url path('update-event/<value1>/<value2>/',web_views.update_event,name='update-event') Then the update_event view where database is updated,and is redirected to a simple stable template my_events.html def update_event(request,value1,value2): user= User.objects.get(id=value1) ev=Event.objects.get(id=value2) data=Participated(user_id=user,event_id=ev) data.save() return redirect(request,'webpage/my_events.html') This is the Participated model class Participated(models.Model): user_id=models.ForeignKey(User,on_delete=models.CASCADE) event_id=models.ForeignKey(Event,on_delete=models.PROTECT) I'm getting an error Reverse for '<WSGIRequest: GET '/update-event/1/4/'>' not found. '<WSGIRequest: GET '/update-event/1/4/'>' is not a valid view function or pattern name. So how to insert values to Partcipated model? -
How to set token expiration time when using django-rest-authtoken?
I'm using the django-rest-authtoken library (https://github.com/wichmannpas/django-rest-authtoken) to manage my API users. The biggest inconvenience is that the user authentication tokens expire in 24 hours, effectively requiring to perform login every day. Unfortunately I couldn't find a way to change the token expiration time. Any help appreciated. -
Can we create multiple users in Django which edit a single product information?
I am new to Django. I have to work on a project which allows 5 or more users to edit a single value. For example, User1 logs in and modifies the status of a product. The modification should be publicly visible. All groups should now see that okay, User1 has added this information at this time. Now, User2 should also be able to modify it and rest should see it. How can we make this happen? Thank you for your valuable time! -
Django rest setting the one to one relation creating an post method
I am new to django,I have created the models with OnetoOne relationship , I have user table and i have onetoone relation with storyboard library table, the issue is when i am creating an storyboardlibraby object , i need to save the user objectin the onetoonefield , even after adding user object not able to save the storyboardlibrary to the database, if anybody can help on this please help me , i will add the code which I have written. class StoryboardLibrary(models.Model): name = models.CharField(max_length=50) data = JSONField(db_index=True) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return "%s The Library" % self.name Serializer class class StoryboardSerializer(serializers.ModelSerializer): class Meta: model = StoryboardLibrary fields = ('data','name','user') views post method def add_storyboard(request): # validating for already existing data if StoryboardLibrary.objects.filter(**request.data).exists(): raise serializers.ValidationError('This data already exists') user = get_object_or_404(User, id=request.user.id) request.data['user'] = user storyboard = StoryboardSerializer(data=request.data) print(storyboard) if storyboard.is_valid(): storyboard.save() return Response(storyboard.data, status=status.HTTP_201_CREATED) else: return Response(status=status.HTTP_404_NOT_FOUND) After hitting the post api i am not able to save the data storyboardserializer is not valid hence it is executing the else block and returning the status 404 not found -
How to test a Django REST APIView class with get and post methods combining multiple models?
I am currently testing my API for a game (models and view) and since I have never written tests before, I am only getting errors for my tests. This is my GameView: class GameView(APIView): """ API View that retrieves the game, retrieves an game round as well as a random resource per round allows users to post tags that are verified and saved accordingly to either the Tag or Tagging table """ def get(self, request, *args, **kwargs): current_score = 0 if not isinstance(request.user, CustomUser): current_user_id = 1 else: current_user_id = request.user.pk random_resource = Resource.objects.all().order_by('?').first() first_resource_serializer = ResourceSerializer(random_resource) gameround = Gameround.objects.create(user_id=current_user_id, gamesession=gamesession, created=datetime.now(), score=current_score) gameround_serializer = GameroundSerializer(gameround) return Response({ # 'gametype': gametype_serializer.data, 'resource': resource_serializer.data, 'gameround': gameround_serializer.data, }) def post(self, request, *args, **kwargs): tag_serializer = TagSerializer(data=request.data) tagging_serializer = TaggingSerializer(data=request.data) if tagging_serializer.is_valid(raise_exception=True): tagging_serializer.save(tagging=request.data) return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_201_CREATED) else: return Response({"status": "error", "data": tag_serializer.errors}, status=status.HTTP_400_BAD_REQUEST) This is what I have tried so far in my test suite: class ARTigoGameViewTests(TestCase): def setUp(self): self.client = APIClient() self.artigo_game_data = {'resource': '', 'gamesession': '', 'gameround': ''} self.response = self.client.get('http://localhost:8000/artigo_api/artigo_game/', self.artigo_game_data, format="json") def test_api_can_create_game_data(self): """Test the api has resource retrieve capability.""" self.client = APIClient() self.assertEqual(self.response.status_code, status.HTTP_200_OK) def test_get(self): response = self.client.get('http://localhost:8000/artigo_api/artigo_game/') self.assertEqual(response.status_code, 200) def test_post(self): self.client = … -
Serviceworker.js code being shown on page (only in Google) each time i open root site directory and being replaced with index.html after ctrl+f5
I guess, it is something about django-pwa. This problem appears only in google chrome (in local mode it even works fine on 127.0.0.1:8000 but doesnt work on localhost:8000). My project structure: D:. ├───api │ └───migrations ├───core │ └───__pycache__ ├───games │ └───migrations ├───main │ ├───migrations │ └───__pycache__ ├───static │ ├───images │ └───js ├───staticfiles └───templates it appears, that chrome browser requests the empty path for pwa.urls firstly, but other browsers requesting main urls. i dont really how to make chrome request my urls from main app on first place. this is my urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.views.generic import TemplateView from rest_framework.schemas import get_schema_view import debug_toolbar schema_url_patterns = [ path('api/v1/', include('api.urls')), ] urlpatterns = [ path(r'', include('main.urls')), path('openapi', get_schema_view( title="Gamers Gazette", description="API!", version="1.0.0", patterns=schema_url_patterns, ), name='openapi-schema'), path('swagger-ui/', TemplateView.as_view( template_name='swagger-ui.html', extra_context={'schema_url':'openapi-schema'} ), name='swagger-ui'), path('redoc/', TemplateView.as_view( template_name='redoc.html', extra_context={'schema_url':'openapi-schema'} ), name='redoc'), path('admin/', admin.site.urls), path('games/', include('games.urls')), path('api/v1/', include('api.urls')), path("", include("pwa.urls")), ] if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include('debug_toolbar.urls')), ] + urlpatterns this is my serviceworker.js: var staticCacheName = 'djangopwa-v1'; self.addEventListener("install", event => { this.skipWaiting(); event.waitUntil( caches.open(staticCacheName) .then(cache => { return cache.addAll(filesToCache); }) ) }); // Clear cache on activate self.addEventListener('activate', …