Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model not being updated after calling save() method
Im Using django signals to update a foreign key object of a model . @receiver(sender=PointItem, signal=post_save) def PointItemSaved(instance, sender, **kwargs): try: print(f"before save {user.points}") user = User.objects.get(id=instance.user.id) user.points += 100 user.save() print(f"after save {user.points}") except Exception as e: print(f"there is a problem {e}") according to logs , everything is correct . before & after values are correct . but when i check it on admin page it does not changed ! -
During handling of the above exception (badly formed hexadecimal UUID string), another exception occurred:
I have a checkbox list - user check which items to update - <th scope="row"><input type="checkbox" name="document_detail" value="{{ result.id }}" id="result_check"/>{{ result.id }} This is handled in view by: document_request = request.POST['document_detail'] logging.info(document_request) approval_items = [] for document in document_request: logging.info(document) logging.info gives the correct UUID field e.g. 91da274b-208f-4d65-9e5f-d5cbf2860961 after the loop is initiated the value change to simply "9" or the first character of the UUID. e.g. logging.info give "9" hence the correct error of badly formed UUID Is there a correct method of handling this type of item that I'm missing? -
How to write thread modeling in Django?
I am new to the security side, I know my question might be silly but totally new to Thread Modeling. I have a simple Django application and I need to write thread modeling for this application. If any can help me with a simple Thread Modeling Document it will be great help. Thanks & Regards, Mohamed Naveen -
Change URL when link is clicked in iFrame, when the links in question would be created by user input?
From what I can understand, the URLs of site do not change during navigation if the element with the href/src is within an iframe. And there is a way to override this by getting the ID of every single link element that would exist in the iframe and then set the src manually on each, such as in the response to this question Change URL in an iframe using javascript However the links I want to reflect in the URL are to pages created and added to the site by users, and I cannot know in advance what these URLs will be called, so cannot manually link to them in advance. Is there a workaround for this? And if so, is it really worth the effort and possible messiness? The iframe in question is part of a 3rd party library that I have no control over (django-fobi) -
How do you serialize a queryset that has been created by innerjoining different models?
So, I'm trying to serialize a queryset in my ModelsViewSet. This is my code in my viewset. `class StudentReportViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.AllowAny ] serializer_class = GeneralSerializer def get_queryset(self): if self.request.method == 'GET': queryset = StudentReport.objects.all() teststate_name = self.request.GET.get('testid',None) rawmodalstate_name = (self.request.GET.get('byRaw',None)) percmodaltstate_name = (self.request.GET.get('byPerc',None)) stanmodalstate_name = (self.request.GET.get('byStan',None)) convmodalstate_name = (self.request.GET.get('byConv',None)) print('@@@@@@@@@@@@@@@@') if teststate_name is not None: teststate_name= teststate_name.split(',') teststate_name = list(map(int,teststate_name)) print(teststate_name) print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') queryset= queryset.select_related('test').filter(test_id__in = teststate_name).values('test__subject','student__name','resultsmarked__totalrawscore') queryset= json.dumps(list(queryset), ensure_ascii=False) print('33333333333') print(queryset) return queryset` This is my serializers.py: class StudentReportSerializer(serializers.ModelSerializer): class Meta: model = StudentReport fields= '__all__' These are my models used in my query set: 1)StudentReport class StudentReport(models.Model): idstudent_report = models.AutoField(primary_key=True) student = models.ForeignKey('Students', models.DO_NOTHING, db_column='Student_ID', blank=True, null=True) # Field name made lowercase. test = models.ForeignKey('Test', models.DO_NOTHING, db_column='Test_ID', blank=True, null=True) # Field name made lowercase. resultsmarked = models.ForeignKey(ResultsMarked, models.DO_NOTHING, db_column='ResultsMarked_ID', blank=True, null=True) # Field name made lowercase. standardisedscoretable = models.ForeignKey(Standardizedscoretable, models.DO_NOTHING, db_column='StandardisedScoreTable_ID', blank=True, null=True) # Field name made lowercase. gradetableinternal = models.ForeignKey(Gradetableinternal, models.DO_NOTHING, db_column='GradeTableInternal_ID', blank=True, null=True) # Field name made lowercase. gradetableexternal = models.ForeignKey(Gradetableexternal, models.DO_NOTHING, db_column='GradeTableExternal_ID', blank=True, null=True) # Field name made lowercase. percentiletableid = models.ForeignKey(Percentiletable, models.DO_NOTHING, db_column='PercentileTableID', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'student_report' Test Model class Test(models.Model): idtest … -
Can't change interpreter path in VS Code (working on a Django project, python3)
On the first attempt I was able to change the interpreter, but when I come back to project the path is within suggestions but when I click nothing changes. -
unable to serve django media files with nginx (docker-compose)
I am using docker-compose to run my react-django-nginx application. The application is able to server static assets and the admin page. The problem is however, that I am unable to serve files in the media folder. The files in the media folder are created by me from the admin pannel. They are pdfs. I also have Icons that also do not show up. These are the relevant file: folder structure: backend |---Docker |---core |---settings.py |---etc frontend |---Docker |---conf.d |---etc. ngnix |---Docker |---default.conf docker-compose.yaml docker-compose: version: "3" services: backend: build: context: ./backend dockerfile: Dockerfile ports: - 8000:8000 volumes: - ./backend:/app - ./backend/media:/app/media - ./backend/static:/app/static frontend: build: context: ./frontend dockerfile: Dockerfile-prod ports: - 3000:80 volumes: - ./frontend/src:/app/src nginx: build: context: ./nginx dockerfile: Dockerfile volumes: - ./backend/media:/app/media ports: - 80:80 - 443:443 nginx server { listen 80; client_max_body_size 60M; location / { proxy_pass http://frontend:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /api { proxy_pass http://backend:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /admin { proxy_pass http://backend:8000/admin; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /media/ { alias /home/vicktree/Documents/EducationPortal/backend/media/; } location /nginx-health-check { access_log … -
Dango admin throws empty exception when calling __str__ method
I'm developping a web app with Django (2.2). I have the following Profile model extending the built-in User model trough an One-to-one relationship. class Profile(models.Model): class Meta: ordering = ['user__last_name'] txt = models.CharField("TXT", max_length=5, null=True, blank=True, unique=True) user = models.OneToOneField(User, on_delete=models.PROTECT) colleague = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True) def __str__(self): """ Display of User with its full name""" return "%s %s" % (self.user.last_name.upper(), self.user.first_name.capitalize()) The __str__ method works well in the Admin list display view or in a Django shell. However, an exception is thrown when I try to access to the admin form, pointing to the __str__ method but without any detail. When the __str__ method is removed the form is displayed correctly. Here is the ModelAdmin class ProfileAdmin(admin.ModelAdmin): readonly_fields = ('get_last_name','get_first_name',) fieldsets = [ ('User', {'fields': ['get_last_name', 'get_first_name','txt', 'colleague']}), ] #Sélection des champs à afficher dans la vue liste list_display = ('__str__','get_poste','txt', 'colleague ') #Champ de recherche search_fields = ['user__first_name', 'user__last_name', ] #calculate fields for list_display def get_last_name(self, obj): return obj.user.last_name def get_first_name(self, obj): return obj.user.first_name #Define description of fields for list_display get_last_name.short_description = 'Name' get_first_name.short_description = 'Firstname' #Enable sorting on calculated fields get_last_name.admin_order_field = 'user__last_name' get_first_name.admin_order_field = 'user__first_name' Any advice to solve this issue would be appreciated -
django-storages resize url
I'm using DigitalOcean spaces and try to resize the image that is already there. I have only filename. url = static(filename) # this contains full url to the image image = Image.open(what is here???) if image.size[1] > height: ratio = (height / float(image.size[1])) width = int((float(image.size[0]) * float(ratio))) image = image.resize((width, height), Image.ANTIALIAS) image.save(how to save???) -
Django deployment with Daphne
I want to deploy my Django app (Rest API + React on frontend) on AWS. I use nginx, gunicorn (for http handling) and daphne (for async websockets - Im using django channels for chat application). I was following THIS tutorial. It looks like I configured well nginx and gunicorn (page is normally loading, I can handle sync request to rest API) but I guess there are some problems with daphne and/or asgi. I use systemctl services for server. All 3 (nginx, gunicorn, daphne) statuses show 'active'. Everything works fine on my development server on local. On deployment server when I enter website, I see in console Firefox can’t establish a connection to the server at ws://PATH_TO_WEBSOCKET Is Daphne connected well with Nginx? I use Redis for CHANNEL_LAYERS. I have installed channels-redis and redis-server on Ubuntu server. I think it works fine as I get respond > redis-cli > ping **PONG** project tree . ├── frontend #react files ├── checkers #project dir │ ├── settings.py │ ├── urls.py │ └── asgi.py ├── chat #chat app │ ├── consumers.py │ └── routing.py └── checkers.sock asgi.py import os import django from channels.routing import get_default_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'checkers.settings') django.setup() application = get_default_application() settings.py ROOT_URLCONF = … -
How to create a User model in Django which contains a list of friens which are "User" models as well
I have a model named User and it must have a list of friends which are also "User"s.How shall i go about doing this. Should I make another model named Friends which will contain two "ForeignKey"s to the model User.Or is there any other way of doing this?? -
Add +7 before the entered number when saving to the database Django rest
I have a phone number field. I want the user to enter a phone number like 123 456 7889 and server add +7 when saving. I decided that it can be done with serialization and added this serializers.py class AbstractUserSerializer(serializers.ModelSerializer):полей""" class Meta: model = AbstractUser fields = ('id', 'phone_number', 'email', 'password') extra_kwargs = {"phone_number": {"error_messages": {"blank": "Phone number field can not be blank", "invalid": "Phone number field is not correct", "unique": "This phone number is already registered"}}, "email": {"error_messages": {"invalid": "Email field is not correct", "unique": "This email is already registered"}}, "password": {'write_only': True, "error_messages": {"blank": "Password field can not be blank", "invalid": "Password field is not correct"}}, } def create(self, validated_data): abstract = AbstractUser.objects.create_user( phone_number='+7' + validated_data.pop('phone_number'), **validated_data, ) return abstract This works, but this field must be unique and handled by my error, but after adding my functionality, my error message stopped working, instead an error is thrown django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_email_key" DETAIL: Key (email)=() already exists. Where and how best to add +7. I tried in the manager and view, but it didn't work. Can you please help me? My code: views.py class CreateUserView(generics.CreateAPIView): queryset = Participant.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class … -
annotate a datetime field from another date time and duration in minutes
I want to annotate a datetime field to a queryset using timedelta and F objects Example: Model.objects.annotate(end_time=F('start_time')+timedelta(minutes=F('meeting_duration'))) Here i have a field "start_time" and "meeting_duration" in my table and i want to calculate and annotate an end_time using datetime.timedelta And thereafter filter the queryset using the annotated field. quueryset.filter(end_time__gte=self.end_time) Now its throwing error: TypeError: unsupported type for timedelta minutes component: F -
Django enum compare in template (html)
I am creating an application with Django. (I am new to Django). The application has some statuses, so I tought: let's do it with an ENUM. It kind of works, except the ENUM compare in the template. That gives a false, but it should be true. My models.py: from django.db import models from enum import Enum # Create your models here. class ScannerStatus(Enum): OPERATIONAL = "Operational" ERROR = "Error" class SystemStatus: id: int scannerStatus: ScannerStatus feedStatus: str pentestStatus: str Views.py (partially): from .models import SystemStatus, ScannerStatus status = SystemStatus() status.scannerStatus = ScannerStatus.OPERATIONAL status.feedStatus = "Out dated" status.pentestStatus = "IDLE" return render(request, 'VulnManager/dashboard.html', {'status': status}) dashboard.html (partially): <div class="list-group-item"> <h6 class="list-group-item-heading"> Scanner <a href="#" data-toggle="tooltip" data-placement="bottom" title="Status of the scanner"> <i class="fa fa-question-circle"></i> </a> {% if status.scannerStatus == ScannerStatus.OPERATIONAL %} <!-- This compare doesn't work --> <span class="badge badge-pill badge-success"> {% else %} <span class="badge badge-pill badge-danger"> {% endif %} {{status.scannerStatus.value}}</span> </h6> </div> Anybody some suggestions or alternatives? I've also tried it with class ScannerStatus(models.Model) but that didn't work. Thanks -
images don't appear when i press on phone photos - django
images don't appear when i press on show imgs using collapse method , how to fix problem model.py : class Mobile_Images(models.Model): phone = models.ForeignKey(Mobile, default=None, on_delete=models.CASCADE) images = models.ImageField(upload_to = 'images/') admin.py: class Mobile_ImagesAdmin(admin.StackedInline): model = Mobile_Images class MobileAdmin(admin.ModelAdmin): search_fields = ('name', 'name') inlines = [Mobile_ImagesAdmin] class Meta: model = Mobile admin.site.register(Mobile,MobileAdmin) views.py : def mobile_posts(request,slug): mobile_posts = get_object_or_404(Mobile, slug=slug) best_posts = BestArticals.objects.all() phone_images = Mobile_Images.objects.all() context = {'mobile_posts':mobile_posts,'best_posts' : best_posts,'phone_images':phone_images} return render(request,'mobile/mobile_posts_page.html', { 'mobile_posts': mobile_posts,'best_posts' : best_posts,'phone_images':phone_images }) html page : <button type="button" class="btn btn-info" aria-controls="#phone_pic" data-toggle="collapse" data-target="#phone_pic" style="background-color:#7952b3;border-radius:10px"> phone photos </button> <div id="phone_pic" class="collapse"> <br> <img src="{{phone_images.images}}" alt="" height="300px" width="500px" class="rounded mx-auto d-block"> </div> so when i use the code in html src="{{phone_images.images}}" it don't show all photos that i uploaded before , how to fix this problem -
Career matching query does not exist
this is my views.py. its show a error, Career matching query does not exist. rg = request.GET.get rp = request.POST.get response_data = {} print(rp,'rppp') job = Career.objects.get(job_id=rp('career_id')) print("job_idddd", job) -
how to use choices argument inside a class as a value of radio input in Django template
I want to know how to define choices values to a radio button in the Django template. Here is my models.py RATING_CHOICES = ((1, "Weak"), (2, "Average"), (3, "Good"), (4, "Excellent")) ... class Answer(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) In the template I want to assign values of my RARING_CHOICES to radio in a loop condition. {% for question in questions %} <li>{{ question }}</li> <ul> <input type="radio" value=""> <input type="radio" value=""> <input type="radio" value=""> <input type="radio" value=""> </ul> {% endfor %} Views.py def index(request): context = { "questions": Question.objects.all(), "answers": Answer.objects.all(), "departments": Department.objects.all(), "semesters": Semester.objects.all(), "teachers": Teacher.objects.all(), "subjects": Subject.objects.all(),} return render(request, "evaluation/index.html", context) -
One place to monitor modifications of django model
I have model: class UserAvailableCredit(models.Model): user = models.ForeignKey( "auth_ex.User", related_name="credits", on_delete=models.CASCADE, ) payment = models.ForeignKey( Payment, related_name="credits", on_delete=models.CASCADE, ) project = models.ForeignKey( Project, related_name="credits", on_delete=models.CASCADE, null=True, blank=True, ) and on this model I make various actions like: Bulk creating Deleting Updating etc. is there any way to have one method that on any change of model triggers action? Overwriting save method doesn't solve problem when bulk_create action is triggered. In my solution I have done something like this: class UserAvailableCreditQuerySet(QuerySet): def update(self, **kwargs): notify = kwargs.pop("notify", False) if notify: #custom action def bulk_create(self, objs, batch_size=None): super().bulk_create(objs, batch_size) #custom action class UserAvailableCredit(models.Model): """Model to store available users credits to use with plan limitations.""" objects = UserAvailableCreditQuerySet.as_manager() user = models.ForeignKey( "auth_ex.User", related_name="credits", on_delete=models.CASCADE, ) payment = models.ForeignKey( Payment, related_name="credits", on_delete=models.CASCADE, ) project = models.ForeignKey( Project, related_name="credits", on_delete=models.CASCADE, null=True, blank=True, ) class Meta: ordering = ["id"] def save(self, *args, **kwargs): super().save(*args, **kwargs) #custom action def create(self, *args, **kwargs): super().create(*args, **kwargs) #custom action def delete(self, *args, **kwargs): super().delete(*args, **kwargs) #custom action But I am not sure if it is best way to solve this problem. -
'Order' object is not iterable [Django]
At the very beginning I would note that I'm a beginner as hel :P I have two models in my django models.py and I want them to display on a page. The issue is that I got error about no possible iteration and I don't know why. Also, I'm following the Crash Course from Youtube with changing some thing for my use :) Could You please advice as I haven't found any useful tips on google? Thanks! models.py from django.db import models # Create your models here. class Supplier(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('Pending Order', 'Pending Order'), ('Pending PR', 'Pending PR'), ('Declined by SME', 'Declined by SME'), ('Declined by Finance', 'Declined by Finance'), ('Ordered', 'Ordered'), ('Canceled', 'Canceled'), ('Delivered', 'Delivered'), ) product = models.CharField(max_length=200, null=True) link = models.CharField(max_length=400, null=True) supplier = models.ForeignKey(Supplier, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, default='Pending Order', choices=STATUS) amount = models.CharField(max_length=40, null=True) comment = models.CharField(max_length=400, null=True, blank=True) requester = models.CharField(max_length=40, null=True) def __str__(self): return self.product views.py from django.shortcuts import render from .models import * # Create your views here. def home(request): return render(request, 'accounts/dashboard.html') … -
How should I test this Custom Permissions
I'm confused about the procedure to test this permissions. Should I run this tests testing the login inheriting just the permissions? Couldn't just test this permissions by itsef? How must be done a test like this? def has_permission(self, request, view): user = request.user if not user: user = get_user(request) # -- Default user from allowed hosts bypasses authentication. if API_DEFAULT_USER == user.username: return True # -- Admin users have permission. if user.is_staff or user.is_superuser: return True # -- suscribed users have permission. if not user.is_anonymous: return True return False class SuscribedUserApiPerm(BasePermission): def has_permission(self, request, view): user = request.user # -- suscribed users only have permission. if not user.is_anonymous and user.username is None: return True return False class SubscriptionApiPerm(SuscribedUserApiPerm): def has_permission(self, request, view): user = request.user if super().has_permission(request, view): # Checking current user's subscription return user.owns_api() return False class SubscriptionSimulatorPerm(SuscribedUserApiPerm): def has_permission(self, request, view): user = request.user if super().has_permission(request, view): # Checking current user's subscription return user.owns_simulator() return False -
FATAL: password authentication failed for user "postgres" while running makemigrations
getting the below error while running makemigrations Traceback (most recent call last): File "/home/siva/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/siva/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/home/siva/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/home/siva/venv/lib/python3.8/site-packages/psycopg2/init.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "postgres" FATAL: password authentication failed for user "postgres" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/siva/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/siva/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/siva/venv/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/siva/venv/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/siva/venv/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/siva/venv/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/home/siva/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "/home/siva/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/home/siva/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/siva/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/home/siva/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/home/siva/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/siva/venv/lib/python3.8/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from … -
Deleting database objects in django - How do I correctly make a delete function?
I'm building my first solo django project and one of the stumbling blocks I've run into is creating a "delete function" so I can delete objects in the database. I've been looking at various tutorials for this but I'm getting slightly confused along the way. I'd really appreciate any advice on how to do this correctly in django. Here's what I've been working with so far. I have a model called "Myteam" which looks like this... class Myteam(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) QB = models.CharField(max_length=80, null=True) QBscore = models.IntegerField(null=True) RB1 = models.CharField(max_length=80, null=True) RB1score = models.IntegerField(null=True) RB2 = models.CharField(max_length=80, null=True) RB2score = models.IntegerField(null=True) WR = models.CharField(max_length=80, null=True) WR1score = models.IntegerField(null=True) WR2 = models.CharField(max_length=80, null=True) WR2score = models.IntegerField(null=True) TE = models.CharField(max_length=80, null=True) TEscore = models.IntegerField(null=True) D = models.CharField(max_length=80, null=True) Dscore = models.IntegerField(null=True) K = models.CharField(max_length=80, null=True) Kscore = models.IntegerField(null=True) In my views.py, yesterday, I tried this out... def delete_player(request, pk): player = Myteam.objects.get(pk=id) if request.method == 'POST': player.delete() return HttpResponseRedirect(reverse("index")) return render(request, 'game/index.html') Here's my urls.py path('delete_player/<str:pk>', views.delete_player, name="delete_player") For the html, I was initially trying to have a button link to the delete_player function, but so many of the tutorials I've been looking at use a form with a … -
Create one shared model entry for the whole scope or class in Pytest | Django
I have a simple and possible quite dumb question on Pytest. For example I have a following fixture: @pytest.fixture(scope='module') def my_fixture(db): data = dict( … some data here...) obj = Model.objects.create(**data) return obj Well, if I use it like that I would receive following error: ScopeMismatch: You tried to access the 'function' scoped fixture 'db' with a 'module' scoped request object, involved factories That’s clear So that in order to still use ‘module’ scope I did following: @pytest.fixture(scope='module') def my_fixture(django_db_setup, django_db_blocker): data = dict( … some data here…) with django_db_blocker.unblock(): obj = Model.objects.create(**data) yield obj with django_db_blocker.unblock(): Model.objects.all().delete() Question is: Is it looks like hack or it is just normal way to do it in Pytest? I asking this because in unitests it would be just simple one-liner: @classmethod def setUpTestData(cls): cls.obj = Model.objects.create(**data) Is it any native way how to create one test object in database and use(share) it for 20 tests in one module( or in one class, whatever) without recreating it for each and every test method? It makes no sense for me to do it because of overhead. Or should i come back to old kind setup/setuptestdata and teardown /teardownclass? If I have ‘module’ scoped fixture … -
Docker - served react app, asset-manifest.json with incorrect filenames
I'm new to web development, and I run into a strange error. I have a React/Django app which I'm trying to productionize with nginx and docker. Django runs on a postgres db, and nginx just reroutes port 80 to my react and django ports. When I locally deploy the application using npm run build serve -s build everything works as desired. However, doing the same through Docker doesn't. I have a Dockerfile building the react application: FROM node:12.18.3-alpine3.9 as builder WORKDIR /usr/src/app COPY ./react-app/package.json . RUN apk add --no-cache --virtual .gyp \ python \ make \ g++ \ && npm install \ && apk del .gyp COPY ./react-app . RUN npm run build FROM node:12.18.3-alpine3.9 WORKDIR /usr/src/app RUN npm install -g serve COPY --from=builder /usr/src/app/build ./build Now when I use docker-compose build docker-compose up I see that my Django, React, Postgres and nginx containers are all running, with nginx visible at port 80. When I open localhost in my browser, I see nginx is looking for some static react files in the right directory. However, the react files it is looking for have a different hash than the static files. The static files of both the nginx and react container … -
Using localStorage to force specific window tab or popup window to reload
I am working on a Django project where we protocol documents and the protocol number should appear in a modal message popup, after the form is submitted and closed. The requested function is that if a file is protocolled either from the main window or from a popup list of documents it should always present a modal window with the number of the protocol, the file has been assigned with. I have written a JQuery script that based on certain conditions (page URL contains-or-not specific strings), it sets the localStorage value of UPDATE to 1. When that happens, it forces the active window or popup window to reload in order to display a modal with the assigned protocol number. Unfortunately the reloading doesnt happen as I would like it to happen. It works most of the time but there are times where it either: forces a second reload of the page or doesnt force a reload at all and I have to do it manually or (when the script is activated in a popup) it reloads the main page instead of the popup or (when the script is activated in a popup) it reloads the popup but the modal message …