Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Django model name of uploaded file
I have a django model and I want to access its name. I am using objects.get with id set to 1 because I know that there is only one file that has currently been uploaded to excel_upload class. below is how i go that path for the file. However I a looking to try and access the name of the file. by name i mean the the string associated with the file. I know i can go into the admin panel and just click on excel_upload -> my_excel_file and then see the name. but I am looking for a way to access it in code. the_uploaded_excel_file = excel_upload.objects.get(id=1) excel_file_path_from_db = the_uploaded_excel_file.my_excel_file.path print(excel_file_path_from_db) -
Django cookiecutter with postgresql setup on Ubuntu 20.4 can't migrate
I installed django cookiecutter in Ubuntu 20.4 with postgresql when I try to make migrate to the database I get this error: python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/mais/PycharmProjects/django_cookiecutter_task/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/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/management/base.py", line 387, in check all_issues = self._run_checks( File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/db/utils.py", line 216, in all return [self[alias] for alias in self] File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/db/utils.py", line 213, in iter return iter(self.databases) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/utils/functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/conf/init.py", line 79, in getattr self._setup(name) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/conf/init.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/conf/init.py", line 176, in init raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I did the whole instructions in cookiecutter docs and createdb what is the wrong? -
django queryset values not merging
based on this answer i have this model class PortfolioExchangeTransaction(models.Model): creator = models.ForeignKey('accounts.Account', on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Creator')) create_time = models.DateTimeField(default=timezone.now, verbose_name=_('Create Time')) portfolio = models.ForeignKey(Portfolio, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Portfolio'), related_name='exchange_transaction') type = models.CharField(max_length=40, choices=Transaction_TYPE, blank=True, null=True, verbose_name=_('Type')) exchange = models.ForeignKey(BorseExchange, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Exchange')) count = models.IntegerField(default=0, verbose_name=_('Count')) i want to sum count of all PortfolioExchangeTransaction per exchange so i want sum similar records queryset per exchange as below code: PortfolioExchangeTransaction.objects.all().values('exchange') and i was hopping get something like this: <QuerySet [{'exchageid': 591}, {'exchageid': 512}, {'exchageid': 248}, {'exchageid': 940}]> but with values i got like this: <QuerySet [{'exchageid': 591}, {'exchageid': 591}, {'exchageid': 512}, {'exchageid': 248}, {'exchageid': 591}, {'exchageid': 591}, {'exchageid': 591}, {'exchageid': 591}, {'exchageid': 940}, {'exchageid': 591}, {'exchageid': 248}, {'exchageid': 248}]> how fix this? -
Azure MySQL transaction.atomic() in Django gives a server error
I use an Azure VM, mysqlclient==1.4.6, Django==2.1.5 My code in admin.py: from django.db import transaction ... try: with transaction.atomic(): ... settings.py: 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': DB_HOST, 'PORT': '3306', 'NAME': 'db', 'USER': ..., 'PASSWORD': ..., 'AUTOCOMMIT': True, 'OPTIONS': { 'ssl': {'ssl-ca': '...'} # i modified it } I get: The page cannot be displayed because an internal server error has occurred. any help is appreciated -
Django ORM queryset equivalent to group by year-month?
I have an Django app and need some datavisualization and I am blocked with ORM. I have a models Orders with a field created_at and I want to present data with a diagram bar (number / year-month) in a dashboard template. So I need to aggregate/annotate data from my model but did find a complete solution. I find partial answer with TruncMonth and read about serializers but wonder if there is a simpliest solution with Django ORM possibilities... In Postgresql it would be: SELECT date_trunc('month',created_at), count(order_id) FROM "Orders" GROUP BY date_trunc('month',created_at) ORDER BY date_trunc('month',created_at); "2021-01-01 00:00:00+01" "2" "2021-02-01 00:00:00+01" "3" "2021-03-01 00:00:00+01" "3" ... example 1 "2021-01-04 07:42:03+01" 2 "2021-01-24 13:59:44+01" 3 "2021-02-06 03:29:11+01" 4 "2021-02-06 08:21:15+01" 5 "2021-02-13 10:38:36+01" 6 "2021-03-01 12:52:22+01" 7 "2021-03-06 08:04:28+01" 8 "2021-03-11 16:58:56+01" 9 "2022-03-25 21:40:10+01" 10 "2022-04-04 02:12:29+02" 11 "2022-04-13 08:24:23+02" 12 "2022-05-08 06:48:25+02" 13 "2022-05-19 15:40:12+02" 14 "2022-06-01 11:29:36+02" 15 "2022-06-05 02:15:05+02" 16 "2022-06-05 03:08:22+02" expected result [ { "year-month": "2021-01", "number" : 2 }, { "year-month": "2021-03", "number" : 3 }, { "year-month": "2021-03", "number" : 3 }, { "year-month": "2021-03", "number" : 1 }, { "year-month": "2021-04", "number" : 2 }, { "year-month": "2021-05", "number" : 3 }, { "year-month": … -
500 internal server error when editing files on ubuntu server(No Module named Django)
I had my website running normally not until I made a few changes in the views.py and one of the templates file. Then I had this Werid error, "500 Internal Server Error", and when I changed the error logs. I saw the error. Error Logs (venv) root@vps-e47d7ac6:/home/ubuntu/app# sudo tail /var/log/apache2/error.log [Tue Jan 26 07:40:03.581363 2021] [wsgi:error] [pid 18182:tid 140673103349504] [remote 197.210.227.43:50689] Traceback (most recent call last): [Tue Jan 26 07:40:03.581405 2021] [wsgi:error] [pid 18182:tid 140673103349504] [remote 197.210.227.43:50689] File "/var/www/app/station/asgi.py", line 12, in <module> [Tue Jan 26 07:40:03.581414 2021] [wsgi:error] [pid 18182:tid 140673103349504] [remote 197.210.227.43:50689] from django.core.asgi import get_asgi_application [Tue Jan 26 07:40:03.581446 2021] [wsgi:error] [pid 18182:tid 140673103349504] [remote 197.210.227.43:50689] ImportError: No module named 'django' [Tue Jan 26 07:40:04.348655 2021] [wsgi:error] [pid 18182:tid 140673220962048] [remote 197.210.54.234:55809] mod_wsgi (pid=18182): Target WSGI script '/var/www/app/station/asgi.py' cannot be loaded as Python module. [Tue Jan 26 07:40:04.348789 2021] [wsgi:error] [pid 18182:tid 140673220962048] [remote 197.210.54.234:55809] mod_wsgi (pid=18182): Exception occurred processing WSGI script '/var/www/app/station/asgi.py'. [Tue Jan 26 07:40:04.348939 2021] [wsgi:error] [pid 18182:tid 140673220962048] [remote 197.210.54.234:55809] Traceback (most recent call last): [Tue Jan 26 07:40:04.348978 2021] [wsgi:error] [pid 18182:tid 140673220962048] [remote 197.210.54.234:55809] File "/var/www/app/station/asgi.py", line 12, in <module> [Tue Jan 26 07:40:04.348987 2021] [wsgi:error] [pid 18182:tid 140673220962048] [remote 197.210.54.234:55809] … -
xhtml2pdf on heroku deployment gets (404)
deployed my little django app to heroku. locally everything with xhtml2pdf is working fine. on heroku i get: Page not found (404) Request Method: GET Request URL: https://ers-heatscreen-app.herokuapp.com/1/pdf/ Raised by: angebot.views.generate_pdf_view do i have to install/configure something extra on heroku? requirements.txt arabic-reshaper==2.1.1 asgiref==3.3.1 dj-database-url==0.5.0 Django==3.1.5 django-crispy-forms==1.10.0 django-heroku==0.3.1 future==0.18.2 gunicorn==20.0.4 html5lib==1.1 Pillow==8.1.0 psycopg2==2.8.6 PyPDF2==1.26.0 python-bidi==0.4.2 python-form==0.2.3 pytz==2020.5 reportlab==3.5.59 six==1.15.0 sqlparse==0.4.1 webencodings==0.5.1 whitenoise==5.2.0 xhtml2pdf==0.2.5 -
Django can you give the same user 2 usernames(with "profiles")?
I'm working on a system where the same user might have 2 profiles (ex one as an employee and one as his personal profile) and I want him to access diff parts of the app based on his profile, can he get 2 usernames and get diff permissions based on the username he signed in with? Thought of making a profile model which has a user type and a foreign key to user and then make user type and user unique together so that the user could have multiple profiles but not of the same time. and then make the username on the profile and then keep the profile in the request instead of the user, but that is making a lot of issues, one is that Django doesn't allow having no username field on the user model, so does anyone know any workaround? Or the only way is giving him multiple users??? Please I need a fast answer.... -
How should I implement delayed topic architecture in python Kafka
I am. building a project which uses Kafka . I have to implement retry strategies, if a msg process failed in the main topic it will be published to retry_topic. Here I want to try /retry to send/consume a message after every 15 minutes. Can anyone suggest a solution for this? Kafka consumer should process the message after 15 minutes corresponding to the timestamp in the msg data. I am using python Kafka client. -
Django post single form to 1 model and another model twice
I have a customer form containing name, email, email2 and email3 inputs. I would like to save the form using a class based view and post name and email to Customer model and iterate thru email2 and email3 and post to AdditionalEmail model, which has a foreign key to the customer model. I got it to work using a function based view, but the code seems a bit...hacky to me and I wanted to see if someone had a better way to do this, preferably using a CBV instead of FBV. Here is what I have: models.py class Customer(models.Model): name = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=64, null=True, blank=True) def __str__(self): return f"{self.name}" def get_absolute_url(self): return reverse('customer_list') class Meta(object): ordering = ['name'] class AdditionalEmail(models.Model): name = models.ForeignKey(Customer, on_delete=models.CASCADE) email = models.EmailField(max_length=64, null=True, blank=True) def __str__(self): return f"{self.email}" class Meta(object): ordering = ['name'] forms.py class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = '__all__' widgets = { 'name': forms.TextInput(attrs={'autofocus': 'true', 'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), } class AdditionalEmailForm(forms.ModelForm): class Meta: model = AdditionalEmail fields = ['email'] widgets = { 'email': forms.EmailInput(attrs={'class': 'form-control'}), } views.py def CustomerCreateView(request): if request.method == 'POST': customer_form = CustomerForm(request.POST) email_form2 = AdditionalEmailForm(request.POST, prefix='email2') email_form3 = AdditionalEmailForm(request.POST, prefix='email3') if … -
How to create a line chart with Json in Django?
I created a system with Django. I want to display a line chart. I decided to use chart.js library. I have an API address and I take values from there. I can get values correctly, but I can not figure out how to display this values in a line chart. I try create some for loop but I had so many charts with only one value. It is wrong. Please, can you help me? views.py def Trend(request): response = requests.get('https://api.f-...gelir') data = response.json() return render(request, 'trend.html', {'data': data}) trend.html <div class="col-md-6"> <div class="card"> <div class="card-header"> <div class="card-title">Line Chart</div> </div> <div class="card-body"> <div class="chart-container"> <canvas id="lineChart"></canvas> </div> </div> </div> </div> <script> var lineChart = document.getElementById('lineChart').getContext('2d') var myLineChart = new Chart(lineChart, { type: 'line', data: { labels: [{{ data.text }}], datasets: [{ label: "Trend", borderColor: "#1d7af3", pointBorderColor: "#FFF", pointBackgroundColor: "#1d7af3", pointBorderWidth: 2, pointHoverRadius: 4, pointHoverBorderWidth: 1, pointRadius: 4, backgroundColor: 'transparent', fill: true, borderWidth: 2, data: [{{ data.value }}] }] }, options : { responsive: true, maintainAspectRatio: false, legend: { position: 'bottom', labels : { padding: 10, fontColor: '#1d7af3', } }, tooltips: { bodySpacing: 4, mode:"nearest", intersect: 0, position:"nearest", xPadding:10, yPadding:10, caretPadding:10 }, layout:{ padding:{left:15,right:15,top:15,bottom:15} } } }); </script> API [{"text":"Satış Gelirleri","value":0.04148631496798572},{"text":"TİCARİ FAALİYETLERDEN … -
Django filter does not filter
I'm trying to filter my API results through url parameters, but it's not working as expected. what am I missing in my code? even on DateRangeFilter, it's not filtering. Thanks! class RainfallFilter(filters.FilterSet): start_date = DateFilter(field_name='date', lookup_expr=('gt')) end_date = DateFilter(field_name='date', lookup_expr=('lt')) date_range = DateRangeFilter(field_name='timestamp') class Meta: model = Rainfall fields = ('level', 'amount', 'timestamp') class RainfallView(generics.ListCreateAPIView): serializer_class = RainfallSerializer queryset = Rainfall.objects.all() filterset_class = RainfallFilter def get(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = RainfallSerializer(queryset, many=True) return Response(serializer.data) -
'NotificationQuerySet' object has no attribute 'mark_as_read'
I am implementing the django-notifications package in my code. Everything is simple and easily adoptable except I don't know how to use a method of AbtractionNotification class. The model in package is as bellow: # -*- coding: utf-8 -*- # pylint: disable=too-many-lines from distutils.version import \ StrictVersion # pylint: disable=no-name-in-module,import-error from django import get_version from django.conf import settings from django.contrib.auth.models import Group from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ImproperlyConfigured from django.db import models from django.db.models.query import QuerySet from django.utils import timezone from jsonfield.fields import JSONField from model_utils import Choices from notifications import settings as notifications_settings from notifications.signals import notify from notifications.utils import id2slug from swapper import load_model if StrictVersion(get_version()) >= StrictVersion('1.8.0'): from django.contrib.contenttypes.fields import GenericForeignKey # noqa else: from django.contrib.contenttypes.generic import GenericForeignKey # noqa EXTRA_DATA = notifications_settings.get_config()['USE_JSONFIELD'] def is_soft_delete(): return notifications_settings.get_config()['SOFT_DELETE'] def assert_soft_delete(): if not is_soft_delete(): # msg = """To use 'deleted' field, please set 'SOFT_DELETE'=True in settings. # Otherwise NotificationQuerySet.unread and NotificationQuerySet.read do NOT filter by 'deleted' field. # """ msg = 'REVERTME' raise ImproperlyConfigured(msg) class NotificationQuerySet(models.query.QuerySet): ''' Notification QuerySet ''' def unsent(self): return self.filter(emailed=False) def sent(self): return self.filter(emailed=True) def unread(self, include_deleted=False): """Return only unread items in the current queryset""" if is_soft_delete() and not include_deleted: return self.filter(unread=True, deleted=False) … -
Django app crashes when I try to submit a photo to a form
So I have a django app in which I have created a form. When I get to submitting an image on the form I click the image icon and the app automatically crashes and i get this in the terminal: django.utils.datastructures.MultiValueDictKeyError: 'photo' ''' {% extends "auctions/layout.html" %} {% block body %} <h2>Create New Listing</h2> <form action="{% url 'newListing' %}" method="post"> {% csrf_token %} <div class="form-group"> <input autofocus class="form-control" type="text" name="title" placeholder="Title"> </div> <div class="form-group"> <input class="form-control" type="text" name="description" placeholder="Description"> </div> <div class="form-group"> <input class="form-control" type="number" name="bid" placeholder="Price"> </div> <div class="form-group"> <input class="form-control" type="image" name="photo" placeholder="Image"> </div> <input class="btn btn-primary" type="submit" value="Post"> </form> {% endblock %} ''' views.py ''' from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import User def index(request): return render(request, "auctions/index.html") def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/login.html", { "message": "Invalid username and/or password." }) else: #if user didnt just fill form they … -
How to GET API data USING AJAX BY ID in FULLCALENDAR
events: { // your event source url: 'http://127.0.0.1:8000/api/blocks-view/', // use the url property textColor: 'white', // an option! extraParams: { procedure: 'procedure', scheduler: 'scheduler' }, failure: function() { alert('there was an error while fetching events!'); } }, eventClick: function(info) { var event = info.event; $.ajax({ url:'http://127.0.0.1:8000/api/blocks-view/', type: 'GET', dataType: 'json', data: 'id=' + event.id, success: function(data) { var id = event.id; console.log(event.id); $('#spanBlockname').html(data.title); $('#spanStart').html(data.start); $('#spanEnd').html(data.end); $('#spanProcedure').html(data.procedure); $('#spanSchedulername').html(data.scheduler) $('#fullCalModal').modal('toggle'); }, -
No Reverse Match error for python crash course learning logs project
I am following the book Python Crash Course and am trying to do the Learning Logs app for Django. Everything was going well except when I tried to add entry forms for users on chapter 19. I am encountering the error "Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$']" My models.py look like this: from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about""" text = 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.text class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..." My urls.py: """Defines url patterns for learning_logs""" from django.urls import path from . import views urlpatterns = [ # Homepage path('', views.index, name='index'), path('topics/', views.topics, name='topics'), #Detail page for single topic path('topics/<int:topic_id>/', views.topic, name='topic'), #page for adding a new topic path('new_topic', views.new_topic, name='new_topic'), #page for adding a new entry path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'), ] my views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from .models import Topic … -
axios shows CORS error, with django rest framework
Thanks for reading. I am working with vuejs SPA with flask and django backends. Yes there are 2 backends. The application is in transition. I am switching the back end from Flask to Django Rest Framework. Some parts are still with Flask. Problem axios POST request does not hit django server. The error in console shows as a CORS error. Same calls worked with flask-restful and flask-CORS. GET request works fine with Django Relevant code BACKEND settings.py ... INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders' ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS=True ... views.py ... class SnippetView(ListCreateView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer urls.py ... path('snippets/', SnippetListView.as_view(), name='snippet-list') ... FRONTEND Vuejs component <template> <v-form ref="form" v-model="valid" > <v-text-field v-model="code" label="Code" ></v-text-field> <v-text-field v-model="text" label="text" ></v-text-field> </v-form> </template> axios ... let snippet = { code: 'abc', text: ''} // comes from vuetifyjs form axios.post('http://localhost:8000/data/snippets', snippet) .then(res => console.log(res.data) // not working ... Adding json data works normally in django-admin dashboard, django_rest_framework API interface and in httpie command line client So it appears the issue is with axios. I have tried headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin' : '*', 'Content-Type': 'application/x-www-form-urlencoded' } Above have been tried separately I have also … -
I need to open a modal if a condition is satisfied and get the post value. Is this possible in django?
In my app there are several if conditions. In one of the if condition a modal with two buttons will be shown. if the user clicks one button it should go execute a statement. If user clicks another one it should execute another statement. Is it possible in django. In my views.py def something(request): if statement: (modal should pop up in window) and from the post value from the modal another process should be done. -
Django. Pytest and Postman are getting different results on a single default value when testing
I'm starting to get into Django and pytest. I created a project with few basic components, and it all works well as designed. Except for a Pytest result The model is: class Opportunity(models.Model): class OpportunityQualityLevel(models.TextChoices): H = "High" M = "Medium" L = "Low" class StageProbability(models.TextChoices): A = "Signed Contract" B = "Verbal Confirmation" C = "Resumes First" D = "Nothing Firm" name = models.CharField(max_length=60) value = models.IntegerField() quality = models.CharField(max_length=8, choices=OpportunityQualityLevel.choices, default=OpportunityQualityLevel.M, blank=True) Stage = models.CharField(max_length=24, choices=StageProbability.choices, default=StageProbability.D, blank=True) client = models.ForeignKey(Client, on_delete=models.CASCADE) is_active = models.BooleanField(default=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) last_updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Opportunities" def __str__(self): return self.name The Serializer is: class OpportunitySerializer(serializers.ModelSerializer): class Meta: model = Opportunity fields = ["id", "name", "value", "quality", "Stage", "client", "is_active", "date_created", "last_updated"] The view is: class OpportunityViewSet(ModelViewSet): queryset = Opportunity.objects.all().order_by("name", "client", "-is_active") serializer_class = OpportunitySerializer pagination_class = PageNumberPagination The URL is: router = routers.DefaultRouter() router.register("", views.OpportunityViewSet) urlpatterns = [ path("", include(router.urls)) ] The test itself is very simple: Creating a client and assigning an opportunity from that client. The problematic field on value is the "is_active" I configured it in the model to be "True" as can be seen in the model. When testing with Postman … -
How to allow a user to add objects in Django admin based on the user that has logged in
I want to have an admin where any user who logs in to the admin dashboard can add the objects from their operator email only. Now, the user can add a package object from another operator email as well. I don't want a user to add objects under the email of another operator's email. My Models: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) user_type = models.CharField(max_length=1, choices=USER_TYPES, default='g') first_name = models.CharField(max_length=255, default="") def __str__(self): return self.user.email class Package(models.Model): operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE) destination = models.ForeignKey(Destination, on_delete=models.CASCADE) package_name = models.CharField(max_length=255) city = models.CharField(max_length=255) My package/admin.py: class PackageAdmin(ModelAdmin): icon_name = 'explore' autocomplete_fields = ['destination'] list_display = ('package_name', 'featured', 'price', 'discounted_price', 'savings', 'fix_departure', 'rating', 'date_created',) def get_queryset(self, request): abc = super(PackageAdmin, self).get_queryset(request) if request.user.is_superuser: return abc else: operator = request.user.profile return abc.filter(operator=operator) Here in the above image we can see that a user can add an object under another operator's email as well. I dont want that. The two solutions will be: Only the current user/profile visible in operator field. Although the emails are visible, cant add the package under another operator's ema -
Multi-image is my motive in this project. I wants to show images but not able to show them on front-end but able to upload multi-image on admin panel
My project is based on the multi-image there is problem with html file. There is some mistakes with the html file please help to find the problem in it. I am able to upload the images but they are not able to show on the frontend. help me in my project. my html files are thus: base.html <!DOCTYPE html> <html lang='en'> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css" integrity="sha384-DhY6onE6f3zzKbjUPRc2hOzGAdEf4/Dz+WJwBvEYL/lkkIsI3ihufq9hk9K4lVoK" crossorigin="anonymous"> <title>Multi Image Tutorial</title> </head> <body> <div class="container py-4"> {% block content %} {% endblock %} </div> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> blog.html {% extends 'base.html' %} {% block content %} <div class="row row-cols-1 row-cols-md-2"> {% for post in posts %} <div class="col mb-4"> <div class="card"> <div class="view overlay"> <img class="card-img-top" src="{{post.image.url}}" alt="Card image cap" > <a href="#"> <div class="mask rgba-white-slight"></div> </a> </div> <div class="card-body"> <h4 class="card-title">{{post.title}}</h4> <p class="card-text">{{post.description}}</p> <a href="{% url 'detail' post.id %}" class="btn btn-primary btn-md">Read More</a> </div> </div> </div> {% endfor %} </div> {% endblock %} detail.html {% extends 'base.html' %} {% block content %} <div id="carouselExampleIndicators" class="carousel slide" data-mdb-ride="carousel"> <ol class="carousel-indicators"> {% for p in photos %} <li data-mdb-target="#carouselExampleIndicators" data-mdb-slide-to="{{forloop.counter0}}" class="{% if forloop.counter0 == 0 … -
Django GraphQL Testing Images
I'm currently performing pytest to test my GraphQL mutations. In this case, I input a test image file to determine if it's working. The following is a sample test in which the SimpleUploadedFile object throws a not JSON serializable error. What could be the cause and how should I fix this? @pytest.mark.django_db class TestUploadImage: query = """ mutation uploadImage($input: Upload!) { uploadImage(file: $input) { __typename ... on ResponseErrors { errors { __typename code message } } ... on Output { url } } } """ file = SimpleUploadedFile( name='test_image.jpg', content=b'', content_type='image/jpeg' ) input_data = {"file": file} def test_non_authenticated_request(self, user, client, client_query): response = client_query( self.query, op_name="uploadMessageImage", input_data=self.input_data, ) # Verify that there were no unhandled exceptions content = json.loads(response.content) assert "errors" not in content # Verify that AuthenticationError is in the response data assert AuthenticationError.__name__ in str(response.content) -
cart_id = self.request.session.get("cart_id", None)
I'm creating a ecommerce website with watching YouTube tutorial. Meanwhile typed this code cart_id = self.request.session.get("cart_id", None) Now I do not understand why this code. So plz explain usage of this code. if you have any issue to explain please mention link how that says this code. views.py class AddToCartView(TemplateView): template_name = "add_to_cart.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) product_id = self.kwargs['pk'] produc_obj = Product.objects.get(id=product_id) cart_id = self.request.session.get("cart_id", None) # Old Cart if cart_id: cart_obj = Cart.objects.get(id=cart_id) prd_in_this_cart = cart_obj.cartitem_set.filter(product=produc_obj) # Item already exist in cart if prd_in_this_cart.exists(): cartproduct = prd_in_this_cart.last() # first() prd_in_this_cart.quantity += 1 cartproduct.total += produc_obj.amazon_rate cartproduct.save() cart_obj.total += produc_obj.amazon_rate cart_obj.save() # Item already exist in cart else: cartproduct = CartItem.objects.create(cart=cart_obj, product=produc_obj, quantity=1, total=produc_obj.amazon_rate, subtotal=produc_obj.amazon_rate) cart_obj.total += produc_obj.amazon_rate cart_obj.save() # New Cart else: cart_obj = Cart.objects.create(total=0) self.request.session["cart_id"] = cart_obj.id cartproduct = CartItem.objects.create(cart=cart_obj, product=produc_obj, quantity=1, total=produc_obj.amazon_rate, subtotal=produc_obj.amazon_rate) cart_obj.total += produc_obj.amazon_rate cart_obj.save() return context -
My Custom mixin is not being called in my DetailView in Django?
My custom mixin is not being called in my DetailView. I have 2 DetailView which inherited same custom mixin but only one DetailView can inherited the mixin. Can you take a look and tell me what are my problems? # my custom mixins class GetLastestPostsMixin(object): model = None def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['some_data'] = # some queryset return context # First Detail view class FirstDetailView(GetLastestPostsMixin, DetailView): model = Model1 template_name = my template def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['some_data'] = # some queryset return context # Second DetailView class SecondDetailView(GetLastestPostsMixin, DetailView): model = Model2 template_name = my template def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['some_data'] = # some queryset return context When I do .__mro__ in shell it shows me like this >>> FirstDetailView.__mro__ (<class 'my_app.views.FirstDetailView'>, <class 'my_app.views.GetLastestPostsMixin'>, ....) >>> SecondDetailView.__mro__ (<class 'my_app.views.SecondDetailView'>, ....) # custom mixin is not being called -
How to make docker-compose django server run on local wifi network, so our iOS developer can test the API from the iPhone device?
I'm trying to serve django on our local wifi IP, so our client developer can use his iOS device to test the API. The problem is that when I run the containers, it's only accessible from my chrome browser as localhost(=chrome browser run on the same macbook that is used to run the containers) My docker-compose file: version: '3' volumes: dev_postgres_data: {} dev_postgres_data_backups: {} services: django: build: context: . dockerfile: ./compose/dev/django/Dockerfile image: apps_dev_django container_name: django depends_on: - postgres volumes: - .:/app:z env_file: - ./.envs/.dev/.django - ./.envs/.dev/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: apps_production_postgres container_name: postgres volumes: - dev_postgres_data:/var/lib/postgresql/data:Z - dev_postgres_data_backups:/backups:z env_file: - ./.envs/.dev/.postgres # ports must be set to use postgres container alone ports: - "5432:5432" If I run the django server locally(=not using docker-compose)with the command python manage.py runserver 192.168.0.255:8000, the client who is using the same wifi as me can access the API. I got the 192.168.0.255 with the command ifconfig | grep "inet " | grep -v 127.0.0.1 | cut -d\ -f6(something I got after some googling). If I run ifconfig, I get, ... en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 options=400<CHANNEL_IO> ether a4:5e:60:f1:cb:5b inet6 fe80::85:51dd:e37a:5435%en0 prefixlen 64 secured scopeid 0x4 inet 192.168.0.17 netmask …