Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my else statement not working in django rest framework?
I have the following code: views.py @api_view(['DELETE']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def selected_job_delete(request,pk=None): if pk != None: job=Job.objects.get(pk=pk) jobdetail = Job_detail.objects.get(job=pk) jobtrack = Job_track.objects.get(job = pk) jr = Job_removed() jdr = Job_detail_removed() jtr = Job_track_removed() jr.jobname = job.jobname jr.owner = job.owner jr.enabled = job.enabled jr.start_date = job.start_date jr.start_time = job.start_time jr.date_added = job.date_added jr.version = job.version jr.save() jdr.job = jr jdr.json = jobdetail.json jdr.save() jtr.job=jr jtr.jobdetail= jdr jtr.save() operation = job.delete() data = {} if operation: data["Success"] = "Successfully deleted" else: data["Failure"] = "Unsuccessful" return Response(data) urls.py path('api/jobs/<int:pk>/delete', views.selected_job_delete), Lets say my database in Job have the only following id of 40. I want to delete it so i key the url of api/jobs/40/delete and the deletion will happen, followed by the task in the function. The output result in my postman will show it is successfully deleted . But if I key the url of api/jobs/41/delete, the id of 41 does not exist in my database, it does not run my else statement to show unsuccessful . Instead it shows me How can I make it to show unsuccessful instead of the whole chunk of the error that it does not exist? -
TransactionManagementError in Django when make migrate
I am new to programming , I have an issue when make migrate in Django 3.2.9. Here is my code, models.py from django.db import models from django.db.models.deletion import CASCADE, PROTECT # Create your models here. class Promotion(models.Model): description = models.CharField(max_length=255) discount = models.FloatField() class Collection(models.Model): title = models.CharField(max_length=255) class Product(models.Model): slug = models.SlugField() title = models.CharField(max_length=255) description = models.TextField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotions = models.ManyToManyField(Promotion) class Customer(models.Model): MEMBERSHIP_BRONZE = 'B' MEMBERSHIP_SILVER = 'S' MEMBERSHIP_GOLD = 'G' MEMBERSHIP_CHOICES = [ (MEMBERSHIP_BRONZE, 'Bronze'), (MEMBERSHIP_SILVER, 'Silver'), (MEMBERSHIP_GOLD, 'Gold') ] first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=255) birth_date = models.DateField(null=True) membership = models.CharField( max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE) class Order(models.Model): STATUS_Pending = 'P' STATUS_Complete = 'C' STATUS_Failed = 'F' STATUS_CHOICES = [ (STATUS_Pending, 'Pending'), (STATUS_Complete, 'Complete'), (STATUS_Failed, 'Failed') ] placed_at = models.DateTimeField(auto_now_date=True) payment_status = models.CharField( max_length=1, choices=STATUS_CHOICES, default=STATUS_Pending) customer = models.ForeignKey(Customer, on_delete=PROTECT) class Address(models.Model): street = models.CharField(max_length=255) city = models.CharField(max_length=255) customer = models.OneToOneField( Customer, on_delete=models.CASCADE, primary_key=True) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=PROTECT) product = models.ForeignKey(Product, on_delete=PROTECT) quantiy = models.PositiveSmallIntegerField() unit_price = models.DecimalField(max_digits=5, decimal_places=2) class Cart(models.Model): created_at = models.DateTimeField(auto_now_add=True) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=CASCADE) product = models.ForeignKey(Product, on_delete=CASCADE) quantity = … -
How do I write a Django query to get distinct objects linked to another object?
I'm using Python 3.9 and Django 3.2. I have this class, which has a field for another ... class Transaction(models.Model): ... id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) account = models.ForeignKey('Account', on_delete=models.CASCADE) I woudl like to get the distinct set of Account objects, linked to certain transactions., so I treied this class TransactionManager(models.Manager): def get_accounts_with_pending_transactions(self): """ Returns acounts with pending transactions """ return Transaction.objects.filter(status=Transaction.Status.PENDING).values("account").annotate(n=models.Count("pk")) ... However, the above seems to return a list of dicts as opposed to objects. Thus, I don't have access to all the fields from my Account objects. Is there any way to write a query to get the Account objects such that they are already hydrated as actual objects? -
Django - What happens when you delete an entity in a table that has a foreign key ManyToMany relationship to another?
I've noticed that Django doesn't let you set the on_delete parameter for ManyToManyField. This made me curious what happens if you delete an entity in a ManyToMany relationship? So for example, let's say we have Book, which has a ManyToMany relationship to Author. Let's say that a book A has 3 authors: "Tom Lam", "Lam Tom" and "Britney Britney". Then let's say "Britney Britney" gets deleted from the Author table. Does "Britney Britney" get removed from the ManyToMany relationship with Book? Does an exception get thrown when trying to delete "Britney Britney?" What does Django do in the case that an entity is deleted when it exists in a ManyToMany relationship? -
Django-allauth: Redirect users post sign-up/sing-in to a specific page depending on the page they are coming from
Problem I have an invite system in my django app that allow users to invite other people (using their email) to join their team. When an invited user clicks on an invitation, they are redirected to an url that carries informations about the specific team the user was invited to. Such url calls a view called accept_invitation that handles the following use-cases: a) If a user is logged-in already AND they are also the invited user (i check the email of the invite), I add the user to the team and redirect them to the team's page. b) If a user is logged-in already BUT they are not the invited user, I redirect them to a page where I invite them to log-in with a different account. c) If a user is logged-out, I redirect them to a page where I invite them to log-in and/or sign-up to continue. Use-case a) works just fine but use-case b) and c) I had to figure out how to propagate the informations of the invite to the following screens and past the login. My initial idea was to add the parameters of the invitation to the request.session so that after the login-in I … -
Fix Django "Unresolved attribute reference" for prefetched field
Let's say I have the following Django models: class Toolbox(models.Model): name = models.CharField(max_length=255) tools = models.ManyToManyField("Tool") class Tool(models.Model): class Size(models.TextChoices): SMALL = "S" MEDIUM = "M" LARGE = "L" name = models.CharField(max_length=255) size = models.CharField(max_length=10, choices=Size.choices) I have a function to get all small tools for each toolbox. The @queries_disabled() comes from django-zen-queries to ensure the small tools have been prefetched and avoid N+1 performance problems. @queries_disabled() def get_toolbox_to_small_tools_mappings(toolboxes: list[Toolbox]) -> dict: return {toolbox: toolbox.small_tools for toolbox in toolboxes} The problem is my editor (PyCharm) is highlighting a warning: Unresolved attribute reference 'small_tools' for class 'Toolbox' I can fix this my changing the argument's type hint: def get_toolbox_to_small_tools_mappings(toolboxes: list[Toolbox] | QuerySet): ... This feels a little hacky to me. Is there a better way to fix this? -
In Django how I can create automatically a many to many entry based on a field found in two models
I have the following models example: class TestSet(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Class(models.Model): name = models.CharField(max_length=50) test_set_id = models.ForeignKey(TestSet) def __str__(self): return self.name class Test(models.Model): title = models.CharField(max_length=50) test_set_id = models.ForeignKey(TestSet) def __str__(self): return self.title class ClassTest(models.Model): class_id = models.ForeignKey(Class) test_id = models.ForeignKey(TestSet) memo = models.CharField(max_length=250) def __str__(self): return self.memo What I want to do is when a new Class or Test is created, it should also create automatically a ClassTest entry if their test_set_id matches with the currenct entries on the database. Example: Lets say I already have three Test objects with test_set_id = 1 I create a new Class object with test_set_id = 1 After creating the new Class object, the program should also create 3 new entries in the ClassTest model connecting classes to tests based on the match of the test_set_id field. It should work the same if a new Test object is added. -
how to compare two querysets in django
I'm writing an if statement in Django that compares two querysets and extracts the same assignment. Although the results of cycle_per_day and next_visit_per_day are different, the field values are the same because the same Class Model is used. The assignment_id field is also included in both querysets. In other words, I would like to add a condition called if next_visit_per_day query reset exists in the cycle_per_day query set. But it doesn't apply. What went wrong? cycle_per_day = cycle_visit.filter(dosing_date__day=day, dosing_date__year=self.year, dosing_date__month=self.month, assignment__teacher=self.user.first_name) next_visit_per_day = next_visit.filter(next_visit__day=day, next_visit__year=self.year, next_visit__month=self.month, assignment__teacher=self.user.first_name) d = '' for cycle_visit in cycle_per_day: d += f'{cycle_visit.get_html_url_cycle}' for next_visit in next_visit_per_day: if next_visit.assignment_id in cycle_per_day: d += f'{next_visit.get_html_url_drop}' else: d += f'{next_visit.get_html_url_next_visit}' -
Form not submitting to the DataBase when using HTMX
I have the following models, and as you can see they are related to each other class Leads(models.Model): project_id = models.BigAutoField(primary_key=True, serialize=False) created_at = models.DateTimeField(auto_now_add=True) expected_revenue = MoneyField(decimal_places=2,max_digits=14, default_currency='USD') expected_licenses = models.IntegerField() country = CountryField(blank_label='(select_country)') status = models.CharField(choices=[('Open', 'Open'), ('Closed', 'Closed'), ('Canceled', 'Canceled'), ('Idle', 'Idle') ], max_length=10) estimated_closing_date = models.DateField() services = models.CharField(choices=[('Illumination Studies', 'Illumination Studies'), ('Training', 'Training'),('Survey Design Consultancy', 'Survey Design Consultancy'), ('Software License', 'Software License'), ('Software Development','Software Development')], max_length=40) agent = models.ForeignKey(Profile, default='agent',on_delete=models.CASCADE) company = models.ForeignKey(Company,on_delete=models.CASCADE) point_of_contact = models.ForeignKey(Client, default='agent',on_delete=models.CASCADE) updated_at = models.DateTimeField(auto_now=True) application = models.CharField(choices=[('O&G','O&G'),('Renewables','Renewables'),('Mining','Mining'), ('Other','Other'),('CSS','CSS')], default='O&G',max_length=20) sub_category = models.CharField(choices=[('Wind','Wind'),('Geo-Thermal','Geo-Thermal'),('Solar','Solar'), ('Tidal','Tidal')], max_length=20, blank=True) @property def age_in_days(self): today = date.today() result = self.estimated_closing_date - today return result.days def __str__(self): return f'{self.project_id}' class LeadEntry(models.Model): revenue = MoneyField(decimal_places=2,max_digits=14, default_currency='USD',blank=True) date = models.DateField() lead_id = models.ForeignKey(Leads,on_delete=models.CASCADE) id = models.BigAutoField(primary_key=True, serialize=False) probability = models.DecimalField(max_digits=2, decimal_places=2, default=0, blank=True) @property def est_revenue(self): result = self.revenue * probabiity return result Essentially a lead entry is related to the lead, and I'm using HTMX to essentially add data to LeadEntry database using a form. Form class LeadEntryForm(forms.ModelForm): class Meta: model = LeadEntry fields = ('lead_id','date','revenue','probability') widgets = {'date': DateInput()} I have 2 views, one that will simply pass an HTML with a button for the user … -
bad performance for loop with instance and bulk create
I need to use bulk_create to create a lot of "detalle"(details), the problem is i have to iterate trough a json to get the arguments, and i got 4 fk so django ask to me for the instance, not the id. but to have id i have to do a .get(), so i got a bad performance, because its 4 gets by each iteration. its there a way to get all objects instances and put in a list or something to perform load then the instance without using get every time? class DetalleFichaAllViewSet(viewsets.ModelViewSet): serializer_class = DetalleFichaUpdateAllSerializer def create(self, request, *args, **kwargs): user = self.request.user data = request.data try: ficha = Ficha.objects.get(autor=user.id) DetalleFicha.objects.filter(ficha=ficha.id).delete() except Http404: pass # Create Ficha now = datetime.now() date_time = now.strftime("%Y-%m-%d %H:%M") print("AAAAAA DATA:", data) Ficha.objects.filter(autor=user.id).update(fecha_creacion=date_time, autor=user, nombre=data["nombreFicha"], descripcion=data["descripcionFicha"]) ficha = Ficha.objects.filter(autor=user.id).last() recintos = Recinto.objects.all() productos = Producto.objects.all() estandar_productos = EstandarProducto.objects.all() cotizaciones = Cotizacion.objects.all() detalles_ficha = [] for detalle in data["detalles"]: recinto = recintos.get(id=detalle[1]) producto = productos.get(id=detalle[10]) estandar_producto = estandar_productos.get(id=detalle[9]) try: cotizacion = cotizaciones.get(id=detalle[4]) except ObjectDoesNotExist: cotizacion = None print("Fecha: ", detalle[8]) detalle = DetalleFicha(carreras=detalle[0], recinto=recinto, nombre=detalle[2], cantidad_a_comprar=detalle[3], cotizacion=cotizacion, valor_unitario=detalle[5], valor_total=detalle[6], documento=detalle[7], fecha_cotizacion=detalle[8], estandar_producto=estandar_producto, producto=producto, ficha=ficha) detalles_ficha.append(detalle) DetalleFicha.objects.bulk_create(detalles_ficha) print("Array convertida", detalles_ficha) print(detalles_ficha[0]) return Response(status=status.HTTP_200_OK) -
django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17) for Python venv
I'm having trouble setting up my database on Django. I am running my server on CentOS7 and although I downloaded the version of SQLite I wanted to use, Python keeps pointing to the preinstalled version that is not compatible with my version of Django. I've looked through the other questions that had the same problem as me: django can't find new sqlite version? (SQLite 3.8.3 or later is required (found 3.7.17)) How to use the latest sqlite3 version in python https://number1.co.za/upgrading-sqlite-on-centos-to-3-8-3-or-later/ But the thing that differs between all of these problems and mine is that I used the Python Manager that comes with aaPanel to install my version of Python (3.8.3) which creates a virtual environment for the version of Python that I'm using whereas the others download and compile it from the source. I have tried finding where the correct configure file (as I have found multiple that were not helpful) that is outlined in each of the answers to these questions could be, but to no avail. How could I go about pointing my version of Python to the up-to-date version of SQLite that I have installed? -
Getting "Authentication credentials were not provided" error when I don't want to require authentication
I have a project with JWT authentication in Django Rest Framework. Usually I require user to be authenticated but in the case of GET action (both list and retrieve) I would like everyone to be able to access it with no authentication required. The code for this functionality is very simple: class GetUserViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin): # allowed for everyone serializer_class = UserSerializer permission_classes = [permissions.AllowAny] queryset = User.objects.all() The permissions are set to allow any but there is probably some inconsistency with default auth class in Settings.py # --------------------------REST-framework-------------------------- REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticatedOrReadOnly' ], "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } The last thing that could matter are my endpoints: urlpatterns = [ path("", UserViewSet.as_view({"post": "create"}), kwargs={'quantity': 1}), path("<int:quantity>/", UserViewSet.as_view({"post": "create"})), path("", GetUserViewSet.as_view({"get": "list"})), path("<int:pk>/", GetUserViewSet.as_view({"get": "retrieve"})), path("<int:pk>/", UserViewSet.as_view({"put": "update", "delete": "destroy"})), ] What I don't understand is that in other app where I have register functionality there is no such an error. I will show you this viewset: class ApiUserViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin): serializer_class = ApiUserSerializer permission_classes = [permissions.AllowAny] queryset = ApiUser.objects.all() @extend_schema(request=ApiUserSerializer, responses=TokenSerializer) def create(self, request, *args, **kwargs): api_user_serializer = self.get_serializer(data=request.data) api_user_serializer.is_valid(raise_exception=True) api_user = api_user_serializer.save() refresh = RefreshToken.for_user(api_user) token_serializer = TokenSerializer( data={ "access": str(refresh.access_token), "refresh": str(refresh) } ) … -
Django-allauth: My post-sign-up redirect flow with Google Auth is broken and I can't figure out why
I integrated django-allauth with my Django app but something is not fully working: Problem If a user that does not have an account in my DB tries to sign-up using the the google allauth process, after the authentication process it is sent to the home page (behind login filter) successfully. However, if a user that already has an account in my DB (manually created) tries to login using the google auth by visiting /accounts/google/login/, after the authentication process it is sent to /accounts/social/signup/ (a weird page that django-allauth has). Funny enough thought, the user is logged in and if they try to access the home page they can and everything works. So it's just the redirect that is broken. I narrowed it down to the fact that the user's email already exist BUT there is no social account associated. Setup I have a custom user model where email is the main unique id of a user. from django.contrib.auth.base_user import BaseUserManager from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create … -
Django Heroku Porting
Trying to set up Django configurations for a public url. So I ran this first. $ echo "web: python manage.py runserver 0.0.0.0:\$PORT" > Procfile $ git add Procfile $ git commit -m "Specify the command to run your project" In Procfile: web: python manage.py runserver 0.0.0.0:\$PORT release: python manage.py migrate In settings.py: PORT = os.getenv("PORT", default="5000") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["url"] In env.: PORT=5000 SECRET_KEY=value Was using the above commands and got (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> heroku config:get PORT 5000 (portfolio) PS C:\Users\arund\Desktop\Code\Django\portfolio-project> heroku local [OKAY] Loaded ENV .env File as KEY=VALUE Format 3:08:10 PM web.1 | CommandError: "0.0.0.0:\$PORT" is not a valid port number or address:port pair. [DONE] Killing all processes with signal SIGINT 3:08:10 PM web.1 Exited with exit code null I also used $PORT without the backslash and $. How would I proceed from here to make the public url working. -
Django FileField auto urlencoding problem
image_file = models.FileField(storage=s3, max_length=512, blank=True) I have a model with theis image_file field backed by s3 storage. The only problem I have with this field is if the filename contains any url-encode-able characters, it will auto encode the filename. For example, if the filename contains %40, when retrieve the value from the model, it becomes %2540. I wonder if there is a switch I can turn this feature/bug off. -
Django cannot display model fields to template
I have a model from a package I would like to retreive fields from for the user to my template but am struggling to get this to work as I have done with user model previously: models class DeviceManager(models.Manager): def devices_for_user(self, user, confirmed=None): devices = self.model.objects.filter(user=user) if confirmed is not None: devices = devices.filter(confirmed=bool(confirmed)) return devices class Device(models.Model): user = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), help_text="The user that this device belongs to.", on_delete=models.CASCADE) name = models.CharField(max_length=64, help_text="The human-readable name of this device.") confirmed = models.BooleanField(default=True, help_text="Is this device ready for use?") objects = DeviceManager() class Meta: abstract = True def __str__(self): try: user = self.user except ObjectDoesNotExist: user = None return "{0} ({1})".format(self.name, user) view from django_otp.models import Device def account(request): user = request.user device = Device.objects.all() context = {"user": user, "device": device} return render(request, 'account.html',context) template {{ device.name }} {{ device.confirmed}} I am getting the folowing error: AttributeError: Manager isn't available; Device is abstract I have also tried to change device = Device.objects.all() # To device = DeviceManager.objects.all() But the produces the following error: AttributeError: type object 'DeviceManager' has no attribute 'objects' Help is much apprecaietd in displaying the content from model to my template. Thanks -
Python Requests with Django Rest Framework - 'detail': 'Authentication credentials were not provided'
I've got a tiny function that just looks to get a response from my DRF API Endpoint. My DRF settings look like this: "DEFAULT_AUTHENTICATION_CLASSES": [ # Enabling this it will require Django Session (Including CSRF) "rest_framework.authentication.SessionAuthentication" ], "DEFAULT_PERMISSION_CLASSES": [ # Globally only allow IsAuthenticated users access to API Endpoints "rest_framework.permissions.IsAuthenticated" ], I'm using this to try and hit the endpoint: def get_car_details(car_id): headers = {"X-Requested-With": "XMLHttpRequest"} api_app = "http://localhost:8000/" api_model = "cars/" response = requests.get(api_app + api_model + str(car_id), headers=headers) json_response = response.json() return json_response I keep getting 'detail': 'Authentication credentials were not provided' Do I need to generate a CSRF token and include it in a GET request? The only time this gets hit is when a user goes to a view that requires they are logged in. Is there a way to pass that logged-in user to the endpoint?? -
Django Rest Framework API is being called twice
I am using Django Rest Framework to make a custom backend that does the web3 login flow. However, it is calling my authenticate function twice. And I can't figure out why. my token view: #expects public_address, nonce and token if user is currently signed in @api_view(["POST"]) def get_token(request): logger.debug(request.data) public_address = request.data["public_address"] web3 = Web3Backend() logger.debug(web3) logger.debug('running authenticate from token endpoint') user, token = web3.authenticate(request) logger.debug(user) logger.debug(token) if token: return JsonResponse({'token': token}) else: return Response({'message': 'Missing token'}, status=400) Authenticate Function: def authenticate(self, request, **kwargs): logger.debug(request); public_address = request.data.get('public_address', None) nonce = request.data.get('nonce', None) curr_token = request.data.get('token', None) Web3User = get_user_model() if public_address: if curr_token: #TODO: decode token and check if public_address is the same as the user calling it and if not expired #TODO: if yes then just return true and token token =jwt.decode(curr_token, SECRET_KEY, algorithms="HS256") #TODO: convert into datetime and make sure the current datetime is not pass this expiry = datetime. strptime(token['expiry'],'%y-%m-%d') now = datetime.date.today() logger.debug(expiry) logger.debug(now) if(token['user'] == public_address and expiry < now): logger.debug('JWT still valid') return True, curr_token else: return AuthenticationFailed() #TODO: decode the JWT and check if the user is the proper user try: #TODO: database check; will want to switch to JWT tokens in … -
How can I integrate jquery timepicker in my django project
Here is the jquery timepicker code: $('.timepicker').timepicker({ timeFormat: 'h:mm p', interval: 60, minTime: '10', maxTime: '6:00pm', defaultTime: '11', startTime: '10:00', dynamic: false, dropdown: true, scrollbar: true }); Here is my forms.py from django import forms from bootstrap_datepicker_plus import TimePickerInput from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content','chamber','address','fees','days','hours','review'] widgets = { 'hours': forms.DateField(widget=forms.DateInput(attrs={'class':'timepicker'})) } Here is my models.py class Post(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField('Doctor\'s Name',max_length=100) content = models.CharField('Specialty',max_length=100) chamber = models.CharField('Chamber\'s Name',max_length=200) address = models.CharField('Address',max_length=100) fees = models.IntegerField(default=0) days = MultiSelectField(choices= DAYS_OF_WEEK) hours = models.TimeField() review = models.TextField() liked = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='liked') date_posted = models.DateTimeField(default=timezone.now) objects = PostManager() class Meta: ordering = ('-date_posted', ) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'pk': self.pk}) I am new to django and jquery how can I add a timepicker in my hours field? Where I put my mouse on right side of hours field it changes shape. But no event is triggered when pressed. Here no timepicker comes When I inspect this comes -
'int' object is not iterable when count the number of rows in database in Django
I have database created in Django. File models.py class Guest(models.Model): first_name = models.CharField(max_length=30, verbose_name='First name') last_name = models.CharField(max_length=30, verbose_name='Last name') middle_name = models.CharField(max_length=30, verbose_name='Middle name', blank=True, null=True) date_of_birth = models.DateField(verbose_name='Birthday') address = models.CharField(max_length=50, verbose_name='Address', default='VP 5/7') city = models.CharField(max_length=30, verbose_name='City') email = models.CharField(max_length=50, verbose_name='Email',blank=True, null=True) phone = models.CharField(max_length=20, verbose_name='Phone number', default='897777777') passport = models.CharField(max_length=15, default='C5555555') def __str__(self): return "First name: {}, Last name: {}".format(self.first_name, self.last_name) File views.py class GuestListView(generics.ListAPIView): serializer_class = GuestSerializer def get_queryset(self): queryset = Guest.objects.all() params = self.request.query_params city = params.get('city', None) if city: queryset = queryset.filter(city__startswith=city).count() return queryset File serializers.py class GuestSerializer(serializers.ModelSerializer): class Meta: model = Guest fields = "__all__" I run url like: http://127.0.0.1:8000/guests/all/?city=Kazan I got a error: 'int' object is not iterable How to fix that? -
How to query image path with right if condition from Django template?
In Django I have a box model. Each box has some images related to that box. from django.db import models from products.models import Product # Create your models here. class Box(models.Model): boxName = models.CharField(max_length=255, blank = False) boxDescription = models.TextField() boxPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0) boxSlug = models.SlugField(max_length = 255, unique = True, help_text = "Unique text for url created from box name") boxCreatedAt = models.DateTimeField(auto_now_add=True) boxUpdatedAt = models.DateTimeField(auto_now=True) product = models.ManyToManyField(Product) def __str__(self): return self.boxName class Meta: db_table = 'boxes' ordering = ['-boxName'] class BoxImage(models.Model): image = models.ImageField() imageMetaKeyWords = models.CharField("Meta keywords for SEO", max_length = 255, help_text = "Comma delimited words for SEO") imageMetaDescription = models.CharField("Meta description", max_length = 255, help_text = "Content for image meta tag description") defaultImage = models.BooleanField(default= False) box = models.ForeignKey(Box, on_delete=models.CASCADE, related_name="images") In the views.py I need put all the boxes in the context so that they can be passed to the template from django.shortcuts import render from django.views import View from index.views import createNavContent from box.models import Box # Create your views here. class MainShop(View): def __init__(self): context = createNavContent() self.context = context.context def get(self, request, *args, **kwargs): self.context['title'] = 'Dimsum Box Shop' self.context['boxes'] = Box.objects.filter().all() return render(request, template_name='mainShop.html', context = self.context) … -
React axios patch overwrites manytomany field instead of adding to element
My react code is patching the model field group and completely erasing the original content within the group. I realize it might be my serializer or my view set but i can not find any examples of this being done through google search any help would be greatly appreciated. Request Handler handleJoin = (e, group) => { e.preventDefault(); axios.get('http://127.0.0.1:8000/core/current_user/', { headers: { Authorization: `JWT ${localStorage.getItem('token')}` } }) .then((user) => { let group_data = new FormData(); group_data.append('user', user.data.id); group_data.append('group', group.id); for (var value of group_data.values()) { console.log(value); } axios.patch(`http://127.0.0.1:8000/core/usergroup/${user.data.id}/`, group_data,{ headers: { Authorization: `JWT ${localStorage.getItem('token')}`, 'Content-Type': 'application/json', }, }) .then((res) => { console.log(res.data); }) .catch((err) => { console.log(err); }); }) .catch((err) => { console.log(err); }); } Model Serializer class UserGroupSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True, read_only=True,) class Meta: model = UserGroup fields = '__all__' Model Viewset class UserGroupDetail(APIView): def patch(self, request, pk): usergroup = UserGroup.objects.get(pk=pk) serializer = UserGroupSerializer(instance=usergroup, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
AttributeError: 'WindowsPath' object has no attribute 'endswith' when using runmodwsgi Django command
Windows 10, Python 3.8.10, Apache 2.4.51, Django 3.2.8, mod_wsgi 4.9.0 When I try to run the Apache server using python manage.py runmodwsgi, I get this output: Successfully ran command. Server URL : http://localhost:8000/ Server Root : C:/Users/Me/AppData/Local/Temp/mod_wsgi-localhost-8000-Me Server Conf : C:/Users/Me/AppData/Local/Temp/mod_wsgi-localhost-8000-Me/httpd.conf Error Log File : C:/Users/Me/AppData/Local/Temp/mod_wsgi-localhost-8000-Me/error_log (warn) Operating Mode : daemon Request Capacity : 5 (1 process * 5 threads) Request Timeout : 60 (seconds) Startup Timeout : 15 (seconds) Queue Backlog : 100 (connections) Queue Timeout : 45 (seconds) Server Capacity : 20 (event/worker), 20 (prefork) Server Backlog : 500 (connections) Locale Setting : en_US.cp1252 Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\mod_wsgi\server\management\commands\runmodwsgi.py", line 134, in handle options = mod_wsgi.server._cmd_setup_server( File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\mod_wsgi\server\__init__.py", line 3613, in _cmd_setup_server generate_apache_config(options) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\mod_wsgi\server\__init__.py", line 1086, in generate_apache_config if target.endswith('/') and path != '/': AttributeError: 'WindowsPath' object has … -
Django Rest Framework - Cannot POST because username already exists
I am working on a basic rest api with django rest framework. And my database is on MySQL. For one of the functions, when I try to POST, it gives me an error because there is a row with the same username already. I have set the model to have all three of its fields to be unique_together. Please help me understand where i am going wrong, heres snippets of what i have currently: models.py: class VolunteerHours(models.Model): username = models.OneToOneField(Volunteer, models.DO_NOTHING, db_column='Username', primary_key=True) date = models.DateField(db_column='Date') hours = models.IntegerField(db_column='Hours') class Meta: managed = False db_table = 'volunteer_hours' unique_together = (('username', 'date', 'hours'),) urls.py: urlpatterns = [ path('timesheet/', views.TimesheetAPIView.as_view()),] views.py: from . import models from . import serializers from rest_framework import generics from rest_framework import mixins class TimesheetAPIView(generics.GenericAPIView, mixins.CreateModelMixin): serializer_class = serializers.VolunteerTimesheetSerializer def post(self, request): return self.create(request) serializers.py: class VolunteerTimesheetSerializer(serializers.ModelSerializer): class Meta: model = models.VolunteerHours fields = '__all__' The error im getting is: "username": [ "volunteer hours with this username already exists." ] What I want to happen is i can add as many rows with the same username as long as the date and hours are unique. Which are what is submit in my POST requests, but it says username … -
Django - Pymongo list index out of range error
I want to print the _id part of the results by running a query on the mongo db, but I am getting the "list index out of range" error. view; def deleted(request): q1=('XX') q2=('XX') client = MongoClient("XX") database = client["XX"] collection = database["XX"] query = {} query["Marketplace"] = q1 query["$or"] = [ { "Tuyx": q2 } ] cursor = collection.find(query) print(cursor) sonuc= loads(dumps(cursor)) id=sonuc[0]["_id"] print(id) client.close() return render(request, 'deletedlisting.html', {'id':id} ) ti want to print _id value as string;