Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pagination in function not working properly in Django Project
I am trying to add pagination to a list of notifications in a function, so I added Paginator in the function following the documentation in https://docs.djangoproject.com/en/3.1/topics/pagination/#using-paginator-in-a-view-function, but there is no pagination showing in the template. views.py: def ShowNotifications(request): user=request.user notifications= Notification.objects.filter(user=user).order_by('-date') template= loader.get_template('notifications/notifications.html') paginator = Paginator(notifications, 1) # Show 1 Notification per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'notifications': notifications, 'page_obj': page_obj } return HttpResponse(template.render(context, request)) here is the pagination html <!--Pagination--> {% if is_paginated %} <nav class="d-flex justify-content-center wow fadeIn"> <ul class="pagination pg-blue"> <!--Arrow left--> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% endif %} <li class="page-item active"> <a class="page-link" href="?page={{ page_obj.number}}">{{ page_obj.number}} <span class="sr-only">(current)</span> </a> </li> {% if page_obj.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.next_page_number }}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> <span class="sr-only">Next</span> </a> </li> {% endif %} </ul> </nav> {% endif %} <!--Pagination--> I have used the same pagination html in a List View and it worked, so this is the first time to add it in a function. My question: What am I doing wrong that prevents pagination from appearing? How do I fix it? I am in learning phase so a … -
Python Crash Course, Chapter 18 - AttributeError: 'Pizza' object has no attribute 'entry_set'
I've just made it to the end of chapter 18 (Getting Started with Django) of Eric Matthas' Python Crash Course. I have the below function, Pizza, in views.py which is raising the Attribute error noted below. AttributeError: 'Pizza' object has no attribute 'entry_set' This error occurs while I'm viewing my site and click the link for a specific pizza. Taking this action should open a new view (i.e. a page on the site) which displays the name of the pizza along with a list of toppings (i.e. it should execute the pizza function below). def pizza(request,pizza_id): """Show the toppings for a pizza""" pizza = Pizza.objects.get(id=pizza_id) toppings = pizza.entry_set.order_by('name') context = {'pizza': pizza, 'toppings': toppings} return render(request, 'pizzeria/pizza.html', context) Below are my classes from models.py. The Pizza class is what creates Pizza objects. class Pizza(models.Model): """The name of a specific type of pizza.""" name = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.name class Topping(models.Model): """toppings that belong to specific types of pizzas""" pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE) name = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.name I've followed the exercise in this chapter of the book … -
Django rest framework: How to serialize two or more serializers in one view?
First, I would like to say that I'm new on django rest framework. I've read some parts of the documentation but I'm not understanding how can I achieve what I want. I'll explain here and I really appreciate your help. In my views.py I'm using APICursoView(APIView) (Please enlighten me if this is not the desired solution for what I want), to serialize one model, but I need to serialize more than 3 or 4 models, depending on the Api specification. This view has two post requests but, how is the right way to send more than one post requests in one view? Because, the way I'm doing, my api is only showing one serializer to do post request. This is my model.py: class AcademicUnity(models.Model): id_unity = models.AutoField(primary_key=True, help_text='help text goes here') name_unity = models.CharField(max_length=100, null=True, help_text='help text goes here') sigla = models.CharField(max_length=100, null=True, help_text='help text goes here') co_localidade_mec = models.ForeignKey('comum.localidade', on_delete=models.CASCADE, db_column='co_localidade_mec', null=True, help_text='help text goes here') class Meta: managed = False db_table = 'schema1"."academic_unity' class Course(models.Model): id_course = models.AutoField(primary_key=True, help_text='help text goes here') name = models.CharField(max_length=100, null=True, help_text='help text goes here') id_unity = models.ForeignKey(AcademicUnity, on_delete=models.CASCADE, db_column='id_unity', null=True, help_text='help text goes here') class Meta: managed = False db_table = 'schema1"."course' … -
Django: Queryset returns `isinstance` instead of objects
i was just working on a project i have created a custom management command to insert data into the database for my api when i try to browse the data in the api i get this error: Got AttributeError when attempting to get a value for field `name` on serializer `CacheCategorySerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `builtin_function_or_method` instance. Original exception text was: 'builtin_function_or_method' object has no attribute 'name'. Here's my serializer: class CacheCategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = "__all__" depth = 1 Here's my view class CategoryViewset(viewsets.ReadOnlyModelViewSet): queryset = Category.objects.all() serializer_class = CacheCategorySerializer def get_queryset(self): qs = super().get_queryset() print(qs) return qs output from print(qs): <QuerySet [<built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, <built-in function isinstance>, '...(remaining elements truncated)...']> Here's my custom managment command class Command(BaseCommand): help = "insert categories into database" key = "categories" def handle(self, *args, … -
how can i override queryset and save method in django admin
I have a Transaction model class Transaction(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True) property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) and in admin .py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference','familymember__name'] inlines = [FamilyGroupInline,FamilyMemberInline] def save_model(self, request, obj, form, change): obj.user = request.user.groups.filter(name__isnull=False) print(obj.user) super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super().get_queryset(request) # print(qs.values('group__name')) print(request.user.groups.all()) if request.user.is_superuser: return qs return qs.filter(group__name=request.user.groups.all()) i have created two groups test1, test2 ... i want each group to view, add, delete and update their own transactions only, based on thier groups of course i override the save and queryset method but i dont know what is the problem, still groups cant see the transactions PS: i dont want to add a group field to transactions, i will add each user to his group, and this should be automated thanks! -
need to do the work of collecting the common applications and models use django
I have more than one application in one and I need to do the work of collecting the common applications in a separate application and all the applications are from this application to divide the applications possible What is the mechanism or means to do that use django -
Django wsgi unable to find module ModuleNotFoundError: No module named '' when trying to run individual tests
Trying: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. (django 2.0.1)(Python 3.6) leads to: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\projects\django\crypto-currency-board\crypto\manage_crypto_currency\__init__.py", line 4, in <module> application = get_wsgi_application() File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\msebi\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'manage_crypto_currency' Project layout (manage_crypto_currency is a separate app): wsgi.py (for the project 'crypto'): import os from django.core.wsgi import get_wsgi_application application = get_wsgi_application() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'crypto.settings') os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" application = get_wsgi_application() When trying to debug the file tests.py in the app 'manage_crypto_currency' I get the error above. tests.py (app 'manage_crypto_currency'): from django.test import TestCase from crypto.manage_crypto_currency.get_coins_scheduler import do_greeting if do_greeting(): print("Online") else: print("Offline/API changed") I want to do some vanilla python testing/debugging. I don't get why: ModuleNotFoundError: No module named 'manage_crypto_currency' is thrown. -
Is there a way to use Django authentication and authorization with node.js express server
I am building a project with Django/DjangoRestFramework and node.js for the backend together with a react frontend. I want to use Django for the core functionality and node.js for real-time stuff like chats and video streaming and also want to use a single authentication backend with Django. So how can i authenticate the node.js app with Django’s authentication. -
Django signal does perform action on last created record
I have two django signals that on creation kick off some actions. The order_fully_paid_signal kicks off save_to_db to the PrinterReceivedInfo model. When that model record is created it writes the file to Azure file storage (which is a celery task under tasks.py). The task is just basically taking all the output of a database table and writing it to a text file in Azure. It writes all the data except the last record that has been created by the signal. I suspect I have misunderstood the way that the .delay is working. Any help is really appreciated. Signals.py @receiver(post_save, sender=Order) def order_fully_paid_signal(sender, instance, created, **kwargs): if instance.get_payment_status() == "fully-charged": #some action save_to_db = PrinterReceivedInfo.objects.create(order_id=order_id, order_string=order) @receiver(post_save, sender=PrinterReceivedInfo) def azure_method(sender, instance, created, **kwargs): save_to_azure.delay() tasks.py @app.task def save_to_azure(): config_variables = ConfigurationSettings.objects.get(pk=1) azure_container_name = config_variables.config_azure_container_name azure_blob_name = config_variables.config_azure_blob_name azure_account_key = config_variables.config_azure_account_key block_blob_service = BlockBlobService(account_name=azure_container_name, account_key=azure_account_key) #Get a list of unprocessed orders (not sent to the receipt printer) unprocessed_orders = PrinterReceivedInfo.objects.filter(printer_description="Pending") #For each unprocessed order, recreate a new text file blob_content = "" for item in unprocessed_orders: blob_content += item.order_string + "\n" #Write the file back to Azure. If the file does not exist, it will be created block_blob_service.create_blob_from_text(azure_container_name, azure_blob_name, blob_content, content_settings=ContentSettings(content_type='text/plain')) -
How to create to images in the same Docker container?
I have the following two commands: RUN cd project/ && python3 -m celery -A tasks worker --loglevel=INFO CMD [ "python3", "project/main.py", "runserver", "0.0.0.0:8000" ] It does not work because the first command should be ran as background process and then it can't continue to the next command. The way I build: sudo docker build -t app . The way I run container: sudo docker run -d -p 8000:8000 app As I understand it's possible to have two images for one container. How can I create those two images in the same container? I'm not using docker-compose. -
Upload multiple images with Django admin
I'm trying to find a way to upload multiple images with only one "select file" (So you can select all the files and upload them at once). The number of images imported is not a fixed number. Can somebody show me what I have to do in the models.py and the admin.py. -
Multiplying two fields in django models to get total value but total value not getting updated in the database
My model looks like this. Other fields are getting updated in the database just as expected. The problem is getting the total value stored in the database by multiplying the price_per_unit with the quantity. Is there something I am missing ? from django.db import models from django.contrib.auth.models import User from django.db.models import Sum from django.db.models import F class CowData(models.Model): title = models.CharField(max_length=20, default="item") user = models.CharField( max_length=20, null=False) added_on = models.DateField(auto_now_add=True) feed = models.CharField(max_length=20, null=True) quantity = models.PositiveIntegerField() price_per_unit = models.PositiveIntegerField() total = models.PositiveIntegerField(blank=True, null=True) total = ( CowData.objects .filter() .aggregate( total=Sum('total', field="quantity*price_per_unit") )['total'] ) -
IndexError at /first_app/upload/8 list index out of range, while uploading non csv files in Django no validations are made?
enter image description here views.py enter image description here upload.html enter image description here error page hey guys can anyone help me with this I'm not able to validate this when uploading a non csv file or uploading without any file I'm able to upload csv file and process it , just not able to validate it, thats all. -
Using Natural Language Tool Kit with Django on Heroku - - Error: 'nltk.txt' not found
I’ve got a basic Django project. One feature I am working on counts the number of most commonly occurring words in a .txt file, such as a large public domain book. I’ve used the Python Natural Language Tool Kit to filter out “stopwords” (in SEO language, that means redundant words such as ‘the’, ‘you’, etc. ). Anyways, I’m getting this debug traceback when Django serves the template: Resource [93mstopwords[0m not found. Please use the NLTK Downloader to obtain the resource: [31m <<< import nltk nltk.download('stopwords') [0m For more information see: https://www.nltk.org/data.html So I need to download the library of stopwords. To resolve the issue, I simply open a Python REPL on my remote server and invoke these two straightforward lines: <<< import nltk <<< nltk.download('stopwords') That's covered at length elsewhere on SO. That resolves the issue, but only temporarily. As soon as the REPL session is terminated on my remote server, the error returns because the stopwords file just evaporates. I noticed something strange when I use git to push my changes up to my remote server on Heroku. Check this: remote: -----> Python app detected remote: -----> No change in requirements detected, installing from cache remote: -----> Installing pip … -
What is wrong with this js code, that its not working [closed]
I am making a website and I want that when in my dropdown 10 is selected and the button is clicked it should go to a specific page and if not then should display a message, I am doing it via js and Html, I am attaching the code Please tell me what is wrong with the code because the is statement is not working HTML Code: {% load static %} <!DOCTYPE html> <html> <head> <title>Hi there</title> <link rel="stylesheet" type="text/css" href="{% static 'homepage/style.css' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <form> <select id="final"> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12" selected="selected">12</option> <option value="13">13</option> <option value="14">14</option> </select> Length <br> <button id="button">click me!</button> </form> <script type="text/javascript" src="{% static 'homepage/custom.js' %}"></script> </body> </html> Java Script: document.getElementById("button").onclick = function() { var e = document.getElementById("final"); var selected = e.options[e.selectedIndex].value; if (selected == "10") { window.location.assign("https://www.youtube.com"); } else{ alert("it didn't work") } } -
How to add the deleted item's quantity back in my total quantities in django?
I am designing a model of the Health Center. If I am deleting the prescribed medicines to a patient, then I want those medicines' quantity back in the total stock of that medicine. e.g. Suppose I have total of 50 of medicine A in my stocks. If I prescribed 2 unit(quantity) of medicine A to a patient, then total remained in the stock will be 48, and suppose now I am deleting that entry, then I want total 50 stocks of medicine A back again. How do I solve this problem. I am a beginner in Django. -
What is the best way to calculate rank of posts in Django
What is the best way to calculate rank of a post. For example post with most comments get rank=1, second one get rank=2, and if posts have equal comments they get the same rank. My model: class Movie(models.Model): Text = models.CharField(max_length=200) Author = models.CharField(max_length=25, blank=True) class Comment(models.Model): comment_text = models.CharField(max_length=200) post_id = models.ForeignKey( Movie, on_delete=models.CASCADE, related_name='Comments') -
Can't log in after updating User model details in Django
I have a user model that extended from AbstractBaseUser I've shown that below class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField(verbose_name='email', max_length=80, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=100,null=True) last_name = models.CharField(max_length=100,null=True) phone_no = models.CharField(max_length=12, null=True) date_joined = models.DateField( verbose_name='date joined', auto_now_add=True) last_login = models.DateField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) address = models.CharField(max_length=500, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email # def has_perm(self, perm, obj=None): # return self.is_admin def has_module_perms(self, app_label): return True Also, I need to update the User's details by using the view mentioned below class UpdateUser(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) serializer_class = UserSerializerAPI queryset = User.objects.all() After Changing user model details I can not log in. I'm using rest-auth login URL to log user in. When I try to log in it gives me an error saying { "non_field_errors": [ "Unable to log in with provided credentials." ] } What is the reason for that -
How do I pass Foreign key value in views.py?
How do I access savedata.project_detail in views.py? Each user will have as many projects as he wants. Each project will have one unique primary key. I wan to access that primary key in def checklist(request) function. I only get model attribute "checked_value" from html template. The other attribute "project_detail" should automatically fetch primary key pf model "project". But I don't know how to fetch primary key of model project in def checklist function. If anyone can help here. Here is models.py class project(models.Model): project_name = models.CharField(max_length = 20) date = models.DateField(("Date"), default=datetime.date.today) user = models.ForeignKey(User, on_delete=models.CASCADE) class check_done(models.Model): checked_value = models.CharField(max_length = 200) project_detail = models.ForeignKey(project, to_field="id", db_column="project_detail", on_delete=models.CASCADE) Here is views.py def show(request): log_user = request.user projects = project.objects.filter(user=log_user) return render(request, 'project.html',{'p':projects}) @login_required(login_url='/login/') def add(request): if request.method == "POST": data = request.POST['data'] new = project(project_name = data, user=request.user) new.save() return render(request, 'addproject.html') else: return render(request, 'addproject.html') @login_required(login_url='/login/') def checklist(request): if request.method == "POST": savedata = check_done() savedata.project_detail = ?? print(savedata.project_detail) savedata.checked_value = request.POST.get('abc') savedata.save() return render(request, 'checklist.html') else: return render(request, 'checklist.html') -
accessing foreign keys in djnago views, id attribute of model class
Here are three of my models: class User(AbstractUser): pass class Category(models.Model): Name = models.CharField(max_length=20) class Listing(models.Model): Title = models.CharField(max_length=20) Description = models.TextField() StartingBid = models.IntegerField() Category = models.ManyToManyField(Category, verbose_name="Categories") Image = models.URLField() CurrentBid = models.IntegerField() Author = models.ForeignKey(User, on_delete=models.CASCADE) Close = models.BooleanField() Here's the url which takes me to the required view: path("<str:user>/<str:name>", views.name, name="name"), And finally the name view: def name(request, user, name): try: l = Listing.objects.get(Title=name) except Listing.DoesNotExist: l = None try: **bid = Bid.objects.get(Bidder=user, Item=name)** except Bid.DoesNotExist: bid = None if l.CurrentBid == bid.Value and l.Close: won = True else: won = False if l.Author == user: owner = True else: owner = False watchlist = Watchlist.objects.all() if name in watchlist: added = True else: added = False return render(request, "auctions/name.html", { "item": l, "added": added, "form_bid": BidForm(), "m": "", "owner": owner, "comments": Comments.objects.filter(Item=name), "won": won }) This is where the problem is occuring: bid = Bid.objects.get(Bidder=user, Item=name) The error message: Field 'id' expected a number but got 'admin'.(admin is the username) I figured what the problem is, but i don't know what to do. Bidder attribute of class bid is a Foreign key to the class User Can someone please tell me how to do it … -
how to update single field in database, django
Model.py file from django.db import models from django.contrib.auth.models import User class ClientDetails(models.Model): objects = models.Manager() username = models.CharField(max_length=20, unique=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) Mobile_no = models.IntegerField(blank=True) address = models.TextField(blank=True) online = models.BooleanField(default=True) def __str__(self): return self.username class Meta: verbose_name = 'ClientDetail' verbose_name_plural = 'ClientDetails' Views.py file here I want when user logs in his online status should be set to true [even though it is] def loginuser(request): ''' code for logging in the user also when logged in update staus to active ''' if request.method == "POST": user = authenticate(username=request.POST['username'], password=request.POST['password']) login(request, user) # get the id of the user pk = request.user.id ClientDetails.objects.filter(id=pk).update(online=True) return redirect('Client:dashboard') else: return render(request, 'Client/loginuser.html') when he sign's out his online status should be set to False I tried other ways and this as well but its not updating the status in backend [at admin side ] def sign_out(request): ''' before logging out the user update his online status to False ''' pk = request.user.id print(pk) ClientDetails.objects.filter(id=pk).update(online=False) logout(request) return render(request, 'Client/loginuser.html') loginuser.html file <div class="card-body"> <div class="d-flex align-items-center justify-content-between m-b-30"> <img class="img-fluid" alt="" src="{% static 'assets/images/logo/logo.png' %}"> <h2 class="m-b-0">Sign In</h2> </div> <form action="{% url 'Client:login' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label class="font-weight-semibold" for="userName">Username:</label> … -
Django Static Files sometimes load, sometimes not load
I am developing a django app in which i have made a static folder in app folder. I am encountering a problem related to static file. The problem is that while i run the app by runserver command, django does collect static files but when i change something in those static files sometime file gets updated and sometime does not get updated and instead it collects old version of those files even if i save the file and run the app again by runserver command. When I rename the static files (both css and js files) and change the index.html as per new names, the app works totally fine with updated file names for a while and i face this problem again and again. I am tired of renaming the files and not got any proper solution to this problem. I will be thankful for your opinion and help. The folders of my app look like this: ├───.vscode ├───Project └───manage.py └───Project └───__pycache__/ └───__init__.py └───asgi.py └───setting.py └───urls.py └───wsgi.py ├───templates │ └───base.html └───AppName └───templates └───index.html └───static └───AppName └───js └───indexjs.js //--> This file gets loaded with updated version and sometimes not └───css └───style.css //--> This file gets loaded with updated version and sometimes … -
Errno 13 Permission denied: '/app/celerybeat.pid' in Docker + Celery Beat
Celery Beat causes permission error when I try to run the docker containers. This is because the user permissions in Docker file so it seems I configured something wrong there. I tried all possible solutions but the error still showing up. Please help me to figure out what am I doing wrong. Thank you. Here is the Docker file: FROM python:3.7-alpine ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client jpeg-dev RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev musl-dev zlib zlib-dev RUN pip install -r /requirements.txt RUN apk del .tmp-build-deps RUN mkdir /app COPY ./app /app WORKDIR /app RUN adduser -D appuser RUN chown -R appuser:appuser /app RUN chmod -R 755 /app/staticfiles USER appuser and docker-compose file: version: '3' services: app: build: context: . env_file: - ./.env.dev volumes: - ./app:/app - static_volume_app:/app/staticfiles - media_volume_app:/app/media command: > sh -c "python3 manage.py migrate && python3 manage.py wait_for_db && gunicorn app.wsgi:application --bind 0.0.0.0:8000" expose: - "8000" depends_on: - db db: image: postgres:10-alpine env_file: - ./.env.dev ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data redis: image: redis:alpine celery: restart: always build: context: . command: celery -A app worker -l info volumes: - ./app:/app env_file: - ./.env.dev depends_on: - … -
Deleting Notifications by Using Signals in a Django Project depending on Value of Attribute
I have added a notification everytime a user has submitted Like button, but I am now receiving a notification everytime the button is click either by unliking or liking, so I have added value for the Like so that it can be Like and Unlike. So, now in the Notifications I have added the delete option but I am a bit confused on how to set delete the Noification if the value of the like is Unlike, to prevent receiving unwanted notifications. Here is the post models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) likes = models.ManyToManyField(User, related_name='liked', blank=True) Here is the likes models.py LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-{self.value}" def user_liked_post(sender, instance, *args, **kwargs): like = instance post = like.post sender = like.user notify = Notification(post=post, sender=sender, user=post.author, notification_type=1) notify.save() def user_unlike_post(sender, instance, *args, **kwargs): like = instance post = like.post sender = like.user notify = Notification.objects.filter(post=post, sender=sender, user=post.author, notification_type=1) notify.delete() # Likes post_save.connect(Like.user_liked_post, sender=Like) post_delete.connect(Like.user_unlike_post, sender=Like) Here is the notifications models.py class Notification(models.Model): NOTIFICATION_TYPES=((1,'Like'),(2,'Comment'),(3,'Follow')) post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name="noti_post", blank=True, null=True) sender = models.ForeignKey(User, on_delete=models.CASCADE, … -
"detail": "Not found." in Django rest-api
I got the error "detail": "Not found." even though some ids still works. model.py class Profile(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) swipe = models.ForeignKey(Swipe, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=10) age = models.FloatField(blank=True, null=True) gender = models.CharField(blank=True, max_length=10, null=True) native_lan = models.CharField(max_length=20) foreign_lan = models.CharField(max_length=20) image = models.ImageField(blank=True, null=True) location = models.CharField(blank=True, max_length=30, null=True) time_start = models.TimeField(blank=True, null=True) time_end = models.TimeField(blank=True, null=True) intro = models.TextField(blank=True, null=True) freeday = models.CharField(blank=True, max_length=10, null=True) def __str__(self): return self.name views.py class MyProfileView(GenericAPIView, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin, ListModelMixin): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'id' def post(self, request): return self.create(request) def get(self, request, id=None): if id: user = get_object_or_404(User, id=id) profile = get_object_or_404(Profile, user=user) print(profile.id) return self.retrieve(request, profile.id) else: return self.list(request) def put(self, request, id=None): print('REQUEST::',request.FILES) return self.update(request, id) def delete(self, request, id=None): return self.destroy(request, id) urls.py urlpatterns = [ path('list/', MyProfileView.as_view()), path('create/', MyProfileView.as_view()), path('update/<int:id>/', MyProfileView.as_view()), path('detail/<int:id>/', MyProfileView.as_view()), path('delete/<int:id>/', MyProfileView.as_view()), ] all the profiles My expectation is that you get user by the id of user account and it allows you to get id of profile, finally returning the profile. But, when I put id=2 which is the id of user account, I got "detail": "Not found." despite that I …