Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
which one is better use Django for full-stack? or Keep the front end separate and handle the ui with API calls
Based on performance and maintenance(includes library availability) which one is better. use Django as full-stack or keeping ui in separate (like using React or other library or framework) and handle with api calls?.Please kindly do needful. -
ValueError when trying to create a following relationship in Django
I have looked through the similar SOverflow questions and no answer helped. I am trying to create a follower/following relationship when a button is pressed, passing the info through Javascript... function follow(user) { fetch(`/profile/${user.id}`, { method: 'POST', body: JSON.stringify({ followed: user.id }) }) .then(response => response.json()) .then(() => load_profile(user.id)) } ...then I receive it and try to save it or update it... @csrf_exempt @login_required def view_profile(request, user_id): if request.method == "POST": data = json.loads(request.body) followed = data.get("followed", "") follower = request.user.id obj, created = UserFollowing.objects.get_or_create(user_id=followed, following_user_id=follower, following=True) if not created: obj(following=False) obj.save() return JsonResponse({"message": "(Un)Followed successfully."}, status=201) ... and this is the model: class User(AbstractUser): pass def serialize(self): return { "id": self.id, "user": self.username, "following": self.following.count(), "followers": self.followers.count(), } class UserFollowing(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="following") following_user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="followers") following = models.BooleanField(blank=False, default=True) ERROR: ValueError: Cannot assign "3": "UserFollowing.user_id" must be a "User" instance. I have tried to pass different values such as the username, the object itself, to no avail. -
How do I assign an ID to a div using Django?
I'm using mezzanine, based on the django framework of Python and I'm trying to add a method for my blog posts. In the models.py I have added an incremental counter to be used as an id reference. ` def get_new_id(): n = 100 i = 1 for i in range(n): if i ==100: break print (i) ##just checking if it actually did what I asked return i This way I want to be able to show the newest post on my homepage without having to change it manually. I'd probably still need to reverse the count so the last blogpost becomes number 1, but regardless, the issue is not that. I understand the code might already be too little for what I want it to do but even this simple loop does not print i in the console, let alone place itself into the meta tag. I have added the reference to the method in the correct html page (or so I believe) from blog_post_list.html {% for blog_post in blog_posts.object_list %} <div id="{{ blog_post.get_new_id }}" class="post-preview"> <a href="{{ blog_post.get_absolute_url }}"> <h2 class="post-title"> {{ blog_post.title }} </h2> </a> {% if settings.BLOG_USE_FEATURED_IMAGE and blog_post.featured_image %} {% block blog_post_list_post_featured_image %} <a href="{{ blog_post.get_absolute_url … -
How to make a browser send notification when you change the windows or tabs
So, I want to make a web app for tests. Usually students try to cheat so they change the tabs or open other apps and search for their info.So, I use fiverr, and you can take skill tests on fiverr and if you tried to change the browser, for example ALT + TAB the test would stop.How can I implement a function like that with django or js? -
I am getting a No such table error in Django
I have read lot's of questions/answers trying to solve this. I am currently working on a website. The problem I am getting is the following: All my website was working Then I added two new models and changed 2 models name's After that I did 'python manage.py makemigrations' And 'python manage.py migrate' Everything seemed okay, but when I went to admin page (after adding the models to admin) the two new models and the models that I have changed names are not working. When I click on them in the admin page I get 'No such table: <table_name>'. I am going to show you... models.py theme = models.CharField(max_length=100) def __str__(self): return f'{self.theme}' class Question(models.Model): title = models.CharField(max_length=30, default="Title") theme = models.ForeignKey(Theme, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) content = models.TextField() post_date = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.title}' class UpVote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post = models.ForeignKey(Question, on_delete=models.CASCADE) class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post = models.ForeignKey(Question, on_delete=models.CASCADE) comment = models.TextField() post_date = models.DateTimeField(default=timezone.now) # ARTICLES___________________________________________________________________________________________ class ArticleTheme(models.Model): theme = models.CharField(max_length=20) def __str__(self): return f'{self.theme}' class Article(models.Model): title = models.CharField(max_length=30) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) theme = models.ForeignKey(ArticleTheme, on_delete=models.CASCADE) pdf = models.FileField(upload_to='pdf', null=True) date_posted = models.DateTimeField(default=timezone.now) date_altered = models.DateTimeField(default=None, … -
How to filter and displayed 'many to many' elements in Django
I'm learning django and in my project can't figure out how properly get and displayed elements from many to many relation on deck detail page. model.py class Card(models.Model): def upload_path(self, filename): return os.path.join('cards/', filename) image = models.ImageField(upload_to=upload_path) card_num = models.CharField(max_length=20, default='') name = models.CharField(max_length=500, default='') desc = models.TextField(max_length=500, default='') card_class = models.OneToOneField(CardClass, on_delete=models.DO_NOTHING, default='') cost = models.OneToOneField(Cost, on_delete=models.DO_NOTHING, default='') card_type = models.OneToOneField(CardType, on_delete=models.DO_NOTHING, default='') rarity = models.OneToOneField(Rarity, on_delete=models.DO_NOTHING, default='') resource = models.IntegerField(default=None) attack = models.IntegerField(default=None) defence = models.IntegerField(default=None) def __str__(self): return self.name def get_absolute_url(self): return reverse('card:cardPageDetail', args=[self.name]) class Deck(models.Model): def upload_path(self, filename): return os.path.join('decks/', filename) image = models.ImageField(upload_to=upload_path) user = models.ForeignKey(User, on_delete=models.CASCADE) cards_list = models.ManyToManyField(Card, related_name='cards_list') deck_id = models.CharField(max_length=10, default='') name = models.CharField(max_length=500, default='') desc = models.CharField(max_length=500, default='') price = models.CharField(max_length=500, default='') def __str__(self): return self.name def get_absolute_url(self): return reverse('card:deckPageDetail', args=[self.name]) views.py def deckPageDetail(request, name): deck=get_object_or_404(Deck, name=name) cards_all = Card.objects.all() queryset = cards_all.objects.filter(cards_list__in=deck.deck_id) print(queryset) context = { 'deck': deck, 'cards_in_deck': queryset, } return render(request, 'landing/deck_detail.html', context) I tried few solutions based on stackoverflow and uncle google, but without results.I will be grateful for help.