Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I personalize an URL path in Django?
I am trying to build an website which renders some books and the corresponding pages. I want to make possible to access a page like this: path('/<str:book_pk>-<int:book_page>/', views.TestClass.as_view(), name='book-test') I want a user to access it very simple, something like: mysite.com/5-12/ - which redirects him to the book nr 5 at page 12. The problem is that when I access this page from the website itself, using href, the real path becomes: mysite.com/%2F5-13/ If I want to write in the browser, the following path: myste.com/5-13/, it throws me 404 page not found, because the real path is mysite.com/%2F5-13/ . This is pretty obvious, but my question is: How can I stick to my initial path, and make it possible to be accessed via myste.com/5-13/? For some reason, Django URL Patterns, adds an extra %2F string at the beginning. Can somebody explain me why, and how to solve this issue? I much appreciate your time and effort! Thank you so much! -
Can a dynamic username used as an object in django to access class members?
In views.py, def func(request): request.POST['username'] = cls() request.POST['username'].clsfunc() print(request.POST['username'].var) class cls(): var = 0 def clsfunc(self): self.var += 1 Will this work and print 1 in the console? -
Handling exceptions in permission classes
I am using Django REST Framework with simple JWT, and I don't like how permission classes generate a response without giving me the final say on what gets sent to the client. With other class-based views not restricting permissions (login, registration, etc.), I have control over how I handle exceptions, and I can choose how the response data is structured. However, anytime I introduce permission classes, undesired behavior occurs. My desired structure is best represented in my LoginView (see try/except block): NON_FIELD_ERRORS_KEY = settings.REST_FRAMEWORK['NON_FIELD_ERRORS_KEY'] class LoginView(GenericAPIView): """ View for taking in an existing user's credentials and authorizing them if valid or denying access if invalid. """ serializer_class = LoginSerializer def post(self, request): """ POST method for taking a token from a query string, checking if it is valid, and logging in the user if valid, or returning an error response if invalid. """ serializer = self.serializer_class(data=request.data) try: serializer.is_valid(raise_exception=True) except AuthenticationFailed as e: return Response({NON_FIELD_ERRORS_KEY: [e.detail]}, status=e.status_code) return Response(serializer.data, status=status.HTTP_200_OK) However, what happens when I try to define a view using a permission class? class LogoutView(GenericAPIView): """ View for taking in a user's access token and logging them out. """ serializer_class = LogoutSerializer permission_classes = [IsAuthenticated] def post(self, request): """ POST … -
Django: How to subtract two model fields in Django templates(html file)?
I have one model called Installment and it has one field called balance. My models.py is given below: models.py class Installment(models.Model): client = models.ForeignKey(Client, null=True, on_delete=models.CASCADE) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField() installment_date = models.DateTimeField(default=timezone.now) balance = models.IntegerField(default='0') # Calcuting balance def calculate_balance(self): #self.aggregate(sum=Sum('installment_amount')) balance = (self.client.total_price - self.client.down_payment) return balance # Saving balance def save(self,*args, **kwargs): self.balance = self.calculate_balance() super().save(*args, **kwargs) I am calculating this balance field from two fields of other model called Client. Now, my views for showing the list of installment of each particular client is below: views.py class InstallmentListView(ListView): model = Installment template_name = 'client_management_system/installment_detail.html' context_object_name = 'installments' # This function is to show the installments of the client, the details of which we are seeing currently, and # pk=self.kwargs['pk'] is to get the client id/pk from URL def get_queryset(self): user = get_object_or_404(Client, pk=self.kwargs['pk']) return Installment.objects.filter(client=user).annotate( total=Window( expression=(self.balance - Sum('installment_amount')), order_by=F('installment_date').asc(), frame=RowRange(end=0) ) ) In the views above, we are calculating a new field called totalusing window function, and I have written self.balance here in the expression to subtract the Sum of installment_amount from balance and save the results in total. But I am getting the following error: Error: AttributeError at /1/Installment-History/ 'InstallmentListView' … -
convert base64 string into image in python
I am trying to convert base64 string into image, so far I have been following this: How to convert base64 string to image? here is pas of the code image = stringToRGB(request.POST.get("image", None)) #request.POST.get("image", None) = /9j/4QL2RXhpZgAATU0AKgAAAAgACwEPAAIAAAAIAAAAkgEQAAIAAAAJAAAAmgESAAMAAAABAAgAAAEaAAUAAAABAAAApAEbAAUAAAABAAAArAEoAAMAAAABAAIAAAExAAIAAAA8AAAAtAEyAAIAAAAUAAAA8AITAAMAAAABAAEAAIdpAAQAAAABAAABBIglAAQAAAABAAAC6AAAAABzYW1zdW5nAFNNLU0xMTVGAAAAAABIAAAAAQAAAEgAAAABbTExcW5zeHgtdXNlciAxMCBRUDFBLjE5MDcxMS4wMjAgTTExNUZYWFUxQVRKMiByZWxlYXNlLWtleXMAMjAyMTowNDoyMCAwOTo1OTozMgAAHIKaAAUAAAABAAACWoKdAAUAAAABAAACYogiAAMAAAABAAAAAIgnAAMAAAABAi8AAJAAAAcAAAAEMDIyMJADAAIAAAAUAAACapAEAAIAAAAUAAACfpEBAAcAAAAEAQIDAJIBAAoAAAABAAACkpICAAUAAAABAAACmpIDAAoAAAABAAACopIHAAMAAAABAAIAAJIJAAMAAAABABgAAJIKAAUAAAABAAACqpKQAAIAAAAHAAACspKRAAIAAAAHAAACupKSAAIAAAAHAAACwqAAAAcAAAAEMDEwMKABAAMAAAABAAEAAKACAAQAAAABAAAFAKADAAQAAAABAAAC0KAFAAQAAAABAAACyaIXAAMAAAABAAAAAKMBAAcAAAABAQAAAKQCAAMAAAABAAAAAKQDAAMAAAABAAAAAKQFAAMAAAABAAAAAKQGAAMAAAABAAAAAAAAAAAAAAABAAAAGAAAAMgAAABkMjAyMTowNDoyMCAwOTo1OTozMgAyMDIxOjA0OjIwIDA5OjU5OjMyAAAAEegAAAPoAAAAyAAAAGT////MAAAAZAAACsgAAAPoMTYwMzA2ADAxNjAzMDYAMDE2MDMwNgAAAgABAAIAAAAEUjk4AAACAAcAAAAEMDEwMAAAAAAAAAAAAAAA/9sAhAA def stringToRGB(base64_string): imgdata = base64.b64decode(str(base64_string)) image = Image.open(io.BytesIO(imgdata)) return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB) the result is I get an error that say "Incorrect padding" is there a way to solve this case ? -
Django model, how to add the user not as Instance?
I'm trying to return a JSON format but I get an error User object is not JSON serializable I did debug and found the problem, but I'm stuck with fixing it. Right now if I print my object i get format like this [ { 'id': 1, 'poster': <User: stackoverflow>, 'description': 'test', 'date_added': 'Apr 20 2021, 02:52 AM', 'likes': 1 } ] How can I return the "poster" as a string with the username only? models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class NewPost(models.Model): poster = models.ForeignKey("User", on_delete=models.PROTECT, related_name="posts_posted") description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=1) def serialize(self): return { "id": self.id, "poster": self.poster, "description": self.description, "date_added": self.date_added.strftime("%b %d %Y, %I:%M %p"), "likes": self.likes } views.py - the function that makes a new object @csrf_exempt def compose_post(request): # Composing a new post must be via POST if request.method != "POST": return JsonResponse({"error": "POST request required."}, status=400) # Check post words data = json.loads(request.body) words = [word.strip() for word in data.get("description").split(" ")] if words == [""]: return JsonResponse({ "error": "At least one word required." }, status=400) # Convert post to NewPost object description = data.get("description", "") new_post = NewPost(poster=request.user, description=description) new_post.save() return JsonResponse({"message": "Post … -
Error Handling in Django Admin (Import-Export)
When I try to import a file to the DB that the app is connected to with an intentional mistake like NULL values in columns that do not allow NULLs, the application displays this very unappealing error message on the screen. Useful for development/debugging, and better than crashing the application, but still not so pleasant users. I have seen some solutions that impose form validity checks in a forms.py or even views.py, but my application has neither of these, just an admin.py file. @admin.register(Substation) class ModelAdminView(ImportExportModelAdmin): class Meta: model = MyModel #def save_model(self, request, obj, form, change): #try: #super().save_model(request, obj, form, change) #return super(ModelAdminView, self).save_model(request, obj, form, change) #obj.save() #except Exception as err: #raise ValidationError(err) #messages.error(request, err) #return super(ModelAdminView, self).save_model(request, *args, **kwargs) #return HttpResponseRedirect(request.path) Commented are some of the unsuccessful hacks I've tried so far. Hoping someone else has an idea about this! -
How to switch my django app created in Pycharm over to Visual Studio Django Web Project
I have created a django app using Pycharm and it is stored as a git repository on Github. And I need to switch it over to Visual Studio Project. I could create a new Django Web Project in Visual Studio, but I can't see where I can clone an already-existing repository from Github. First time, I thought I can just clone when I start a new project and I could clone it, but I noticed that it's not the way to develop a Django app in Visual Studio. Visual Studio has some project types depending on which programming language to use and what kind of framework I use. I chose python as a programming language and "Django Web Project" as a project type. Can anyone help me how to open an already-existing Django app in Visual Studio with the project type "Django Web Project". -
How to modify the Django Auth templates
I am currently learning django and started using djangoauth to manage all about the authentication. The problem is that I don't know where are the files that show all the login, logout, signup. I pasted the "account" folder onto the templates folder on my project, but even if I modify or put something, it does nothing like that wasn't the file. So the question is that where are those files, and how can I modify them? And if I am pasting this folder with the supposed template files, why if I modify them is like that's not the one. I have follow all the instructions from here -
Having a ModuleNotFoundError! in Django
i have this project where there is a Login app and there is a Homepage app. The project files look like this login homepage models.py login settings.py urls.py usersignup models.py manage.py Here is usersignup/models.py ''' from django.db import models class UserDetail(models.Model): first_name = models.CharField(max_length=225) middle_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255) email = models.EmailField() def __str__(self): return self.first_name class WebDetail(UserDetail): # user = models.OneToOneField(UserDetail, on_delete=models.CASCADE, primary_key=True,) username = models.CharField(max_length=255) password = models.CharField(max_length=255) ''' and here is homepage/models.py ''' from django.db import models from login.usersignup.models import UserDetail class UploadProfilePicture(models.Model): caption = models.CharField(max_length=2000) image = models.ImageField(upload_to='images/') class Profile(models.Model): user = models.ForeignKey(UserDetail, on_delete=models.CASCADE) ''' and when i run ''' python manage.py check ''' i get this error 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 "C:\Users\user\Documents\McDonald\Login\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\user\Documents\McDonald\Login\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\user\Documents\McDonald\Login\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\Documents\McDonald\Login\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\user\Documents\McDonald\Login\venv\lib\site-packages\django\apps\config.py", line 211, in import_mod els self.models_module = import_module(models_module_name) File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_modul e return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", … -
Django: groupby with getting first row
I have table as Model name: Test id col1 col2 col3 col4 ..... 1 A 1 2 A 1 3 A 3 4 B 1 5 B 1 6 B 4 7 D 2 8 D 3 9 D 3 10 F 3 11 B 4 I want to get all the rows with unique combination of col1 and col2 and the row with recent id and also the total count of the unique combination of col1 and col2 count id col1 col2 col3 col4 ..... 2 11 B 4 1 10 F 3 1 9 D 3 1 7 D 2 2 5 B 1 1 3 A 3 1 2 A 1 How can i get this I am using mysql -
Djstripe - Stripe webhook 404 error: how to resolve?
For my Django project, I am using djstripe. Using test data, I have confirmed that payments are successful. However, when testing a webhook, I get errors of 404 and then it sometimes changes to 503 (for the same webhook). I am using Heroku free tier so I am not sure if that is the problem, or if I am configuring the webhooks entirely wrong (likely since this is my first project). Any help is appreciated. Stripe endpoint I have as [heroku domain]/users/accounts/webhook/ and my project urls is path('users/accounts/', include('allauth.urls')), -
Django - python manage.py runserver error
after python manage.py runserver using VScode that $ python manage.py runserver Python I don't know why it works like this. How can I make it work according to the instructions? enter image description here -
Django: GroupBy: and also show the other columns
In Django, in table with multiple columns i want to get the symbolName and its count TestModel.objects.values('symbolName').annotate(total=Count('symbolName')).order_by('-id') I have other column id,col1,col2,,,,,,,,, in the same table Now is there a way i can now get the First record for other columns as i am ordering them desc order Is there any function in annotate called First('colname') -
Django - Combine a model object with a list of file information to send as JSON Response
I have a django function "get_message_details" that initially collected data from a model object then sent it via JSON response for an AJAX function. I now need to also include a list of files that are associated with the object. I am having difficulty figuring out a way to include the file list in the json response. views.py def get_message_details(request, msg_id): if request.is_ajax and request.method == "GET": data = list(RequestMessage.objects.filter(id=msg_id)) request_msg_obj = RequestMessage.objects.filter(id=msg_id).values("request_number") service_request_pk = request_msg_obj[0]['request_number'] service_request_obj = ServiceRequest.objects.filter(id=service_request_pk).values("request_number") service_request_number = service_request_obj[0]['request_number'] request_msg_obj = RequestMessage.objects.filter(id=msg_id).values("request_message_number") request_message_number = request_msg_obj[0]['request_message_number'] print(request_message_number) file_path = os.path.join(settings.MEDIA_ROOT, "request files", service_request_number, '-' + str(request_message_number) ) import urllib.parse x = 0 file_list = [] if os.path.exists(file_path): request_file_list = os.listdir(file_path) for file in request_file_list: x = x + 1 file_data = {"file" + str(x): {"name": file, "remove_url": request.path + "?" + urllib.parse.urlencode( {"f": "-" + str(request_message_number) + "/" + str(file)}), "url": settings.MEDIA_URL + "request files" + "/" + service_request_number + "/" + '-' + str( request_message_number) + "/" + file, "temp_id": uuid.uuid4(), "delete_type": "POST"}} file_list.append(file_data) else: file_data = [] # I have the file information stored in file_list. But, I need to figure out how to append the file_list to the object data list. print(file_list) print(data) data = … -
How to make S3 presigned URL expiration time longer? [duplicate]
I use I use S3 for media file storage on my Django project with Boto3. DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I need to make S3 presigned URL's expiration time longer as long as 7 days which is max length set limited by AWS. I wonder if I change settings on Boto3 or I change settings on AWS console. -
TypeError Django, Object of type User is not JSON serializable
Whenever I try my views method in the shell it works and returns a JSON response with what I need but why Do I get Object of type User is not JSON serializable (TypeError at /all_posts) when I try to show them on the website? I'm trying to show each post (Object) with its own attributes. models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class NewPost(models.Model): poster = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=1) def serialize(self): return { "poster": self.poster, "description": self.description, "date_added": self.date_added.strftime("%b %d %Y, %I:%M %p"), "likes": self.likes } views.py @csrf_exempt def compose_post(request): # Composing a new post must be via POST if request.method != "POST": return JsonResponse({"error": "POST request required."}, status=400) # Check post words data = json.loads(request.body) words = [word.strip() for word in data.get("description").split(" ")] if words == [""]: return JsonResponse({ "error": "At least one word required." }, status=400) # Convert post to NewPost object description = data.get("description", "") new_post = NewPost(poster=request.user, description=description) new_post.save() return JsonResponse({"message": "Post saved successfully."}, status=201) def show_posts(request): all_posts = NewPost.objects.all() all_posts = all_posts.order_by("-date_added").all() return JsonResponse([post.serialize() for post in all_posts], safe=False) urls.py # API Routes path("posts", views.compose_post, name="compose_post"), path("all_posts", views.show_posts, name="show_posts"), index.js function … -
Image URL django media file using AWS S3 expires after a while
I use S3 for media file storage on my Django project. DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' From my iOS project I receive image URLs from Django like https://my-bucket.s3.amazonaws.com/image-name.jpg?AWSAccessKeyId=<AccesKey>&Signature=<Signiture> It seems the image URLs are expired after a while(and they probably should). However this causes a problem. When iOS app user left the app and came back after a while and the app memory was alive, the app tries to load images from expired urls(ex. cell reuse) resulting request error. I wonder what is a right solution for this. -
How do I adjust id increment when sending data to erp program with django?
There is an actively used desktop erp software. I want to reach this from the field and process data. I created the models by connecting to the active database with Django. When entering record from Erp, "id = 1" works. Then when I log in from django, I get an error because the id key is in use. Or vice versa, I get an error from erp. I'm sorry for my bad english.enter image description here -
django-3 Object of type PosixPath is not JSON serializable
How to build a serializer that converts the PosixPath property into a string? I tried: class ObjSerializer(serializers.ModelSerializer): class Meta(): model = MyObject fields = ('slug', 'name', 'path') name = serializers.SerializerMethodField() path = serializers.SerializerMethodField() def get_name(self, instance): return instance.name def get_name(self, instance): return str( instance.path ) Using Django 3. -
Django - Pass Object ID after redirect
Apologies if the question title is wrong but I am unsure of exactly what I need to do. I am building a scrum app where users can create user stories and add them to sprints. I want to have two separate ways of creating stories. If the user is creating a story from the backlog, the story that has been created will not be assigned to a sprint, but the user can also add a story from a sprint's detail screen. I want to make it so that if they add a story from a specific sprint's page, that story's sprint field is populated with that sprint. The way I have tried to go about this is by creating two different functions in my views.py file and two separate templates. I am able to create the story without relating to a sprint as intended, but I cannot think of a way to get the id of the sprint where I navigated from to get to the new template. For reference I have included my function for creating stories without relating to a sprint: user = response.user if response.method == "POST": form = CreateNewUserStory(response.POST) if form.is_valid(): name = form.cleaned_data["name"] description = … -
django template tag url only work when empty url pattern is last
iam learning django and there is something i don't quite understand if that's django behavior or iam doing something wrong. so basically iam trying use django template tag to create a fixed html header and footer to extend from it the base.html is like this <a href="{% url "index" %}" style="text-decoration:none;"><h1 style="text-align: center;color: green">Welcome to HireMe</h1></a> {% block title %} {% endblock title %} {% block content %} {% endblock content %} <a href="{% url "about" %}" style="text-decoration:none;"><h4 style="text-align: left;color: purple;margin-top:256px;">About us</h4></a> and the index.html is like this {% extends 'base.html' %} {% block content %} <body style="background-color: rgb(243,220,245) "> <div align="center"> <p>Fugiat commodo officia laborum esse magna nisi commodo eu est non sunt in ut adipisicing nulla cupidatat dolor.</p> <img src="https://media4.giphy.com/media/3pZipqyo1sqHDfJGtz/giphy.gif"> </div> </body> {% endblock content%} and when i use the url template tag here href="{% url "index" %}" it should take me to the index page accourding to my naming in url patterns urlpatterns = [ path('admin/', admin.site.urls), path('test/', include('pages.urls'), name='test'), path('about', include('pages.urls'), name='about'), path('', include('pages.urls'), name='index'), ] and it does as long as the "" pattern is last but if i changed the lines to this urlpatterns = [ path('admin/', admin.site.urls), path('test/', include('pages.urls'), name='test'), path('', include('pages.urls'), name='index'), … -
Question about hire a managed database on DigitalOcean
I developed a small SaaS, with Django + PostgreSQL, and I will deploy it on DigitalOcean, using a basic droplet plan. I am newbie with this subject and I would like to know if I am required or not to hire a database plan (Managed Databases). Thank you very much! -
How can I use settings.py or python's logging module to log different levels to different files
I am fairly new to Django. My initial goal in this project is to separate logs based on their level. I want to write specific logs in specific files; therefore, I am using logging.info logging.warning and logging.error to differentiate between what message goes where. logging.info("I am an info") logging.warning("I am a warning") logging.error("I am an error") My settings.py looks like this: # setup logger import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', datefmt="%Y-%m-%d %H:%M:%S", filename=os.path.join(BASE_DIR, '..', 'logs', 'app_log.log'), filemode='a+') At the moment all log types are being written into app_log.log file. But I want to write everything that is logged with logging.error into app_error.log, logging.warning into 'app_warning.log', and etc. Is there an easy way to do this in settings.py or I have to create a class that uses logging to set the logging.basicConfig(filename='app_error.log', level=logging.ERROR)? -
i keep getting this error anytime i run createsuperuser not working TypeError: create_superuser() missing 1 required positional argument: 'username'
I am trying to create a RESTful API using Django and DRF. I have a User model which extends AbstractUser. I'm neither able to create normal users nor a superuser. When I run: python manage.py createsuperuser I get the following error: TypeError: create_superuser() missing 1 required positional argument: 'username' Here's the models.py file: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django_countries.fields import CountryField # from parent.models import Parent class UserManager(BaseUserManager): def create_user(self, username, email, password=None, **other_fields): if username is None: raise ValueError("users should have a username") if email is None: raise ValueError("users should have an email") # if birth_date is None: # raise TypeError( # "users must include their birth date for validation") user = self.model(username=username, email=self.normalize_email( email)) user.set_password(password) user.save() return user def create_superuser(self, username, email, password): if password is None: raise TypeError("Password should not be none") user = self.create_user(username, email, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True) fullname = models.CharField(max_length=255) birth_date = models.DateField() email = models.EmailField(max_length=255, unique=True) # parent = models.OneToOneField(Parent, on_delete=models.CASCADE) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) country = CountryField() created_at = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUEIRED_FIELDS = ['username', 'email'] objects …