Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django dynamic form with text and **images** through AJAX
I'm trying to create a website for creating articles, and by an article, I mean legit article with arbitrary number of text fields and images. (No just a plain single models.TextField stuff... which is mostly taught to get started with django). I have some priorities for key features to work for as well. User can add as many text field, and image field as possible. As soon as user uploads the image, it gets showed up as a preview. Now recently I learned AJAX, so I've done 90% of the work already, by putting the dynamic content into a JSON format, containing full info about the article as {"title": "...", "heading": "...", "text": "...", "heading": "...", "text": "..."}, and I'm storing that as the article content by using the request.GET in the view, and later I'd loop through that to display all the sub contents of the article in that same order. So here I'm AJAX - const ArticleContent = JSON.stringify(ArticleObject); jQuery.ajax({ url: "{% url 'upload-article' %}", data: { title: ArticleTitle, description: ArticleDescription, content: ArticleContent } }) And then by using that to create and save the new article title = request.GET.get('title', None) description = request.GET.get('description', None) content = request.GET.get('content', … -
Django - Accessing related objects and vice versa
I'm currently facing a design flaw issue I can't fix up myself as I'm out of ideas. I have a written a quite complex forum software in Django which has several post models, each with different pros and cons. Now I have created a "proposals" function that should show the user different posts he may also like to see. The problem now is that I have to access multiple tables as I have multiple post models to generate a list of proposals from. I started to develop a Index so that I can access all my post models from just one index model/table that can resolve the actual Post object. At my post_proposals function I'm currently only able to access the object_id but not the content of the actual object, please see below. What I'm doing wring here? Why can I not access the post_model1 object at my PostCollection Index? models.py collectable_post_models = models.Q(app_label='App', model='post_model1') | models.Q(app_label='App', model='post_model2') | models.Q(app_label='App', model='post_model3') class PostCollection(models.Model): id = models.AutoField(primary_key=True, editable=False) content_type = models.ForeignKey(ContentType, limit_choices_to=collectable_post_models, related_name='collections', related_query_name='collection', on_delete=models.CASCADE, null=True, blank=False) object_id = models.CharField(max_length=36, blank=False) content_object = GenericForeignKey('content_type', 'object_id') date_added = models.DateTimeField(auto_now_add=True, blank=False) class Meta: unique_together = ('content_type', 'object_id') verbose_name = "Post Collection - HELPER … -
Django pre_save, instance is None
I am writing the pre_save method to create the slug for model, for some reason my instance is none. @receiver(pre_save, sender=Employee) def pre_save_employee_receiver(sender, instance, *args, **kwargs): slug = slugify(" ".join([instance.name, instance.surname, instance.id])) instance.slug = slug Error is : File "E:\Work\hire_handler\employees\models.py", line 60, in pre_save_employee_receiver slug = slugify(" ".join([instance.name, instance.surname, instance.id])) TypeError: sequence item 2: expected str instance, NoneType found -
Django App Custom Static Files Cannot be Found when deployed on Heroku
I have a Django app that I test locally using Docker. I'm new to Django but I've followed the advice in their docs/tutorials, and now the structure of the app is the following: project/ - project/ - static/ - admin/ # contains all the css/js/etc for the admin dashboards - django_extensions/ - settings.py - url.py ... - myapp/ - static/ - myapp/ - main.js - views.py ... My settings.py: PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') When I run this locally with Docker, all works fine and all static files (mine and the extensions') are found. But when I deploy (i.e. push) the above to Heroku, it finds the static files for the extensions, but not my custom one (main.js). I have Whitenoise installed. I checked on the Heroku site, and one URL for an admin static file is: /static/admin/css/responsive.css And the URL for main.js is: /static/myapp/main.js Which seems to be the expected/correct output. This seems to be a popular and frustrating issue and each seems to depend on many different variables. I tried the solutions/steps suggested in all the following: Django and Static Assets Configuring Django Apps for … -
Web server or Host for deploying Django Framework
I want to know which web servers or hosts that Django Framework can be deployed. 1. Apecha Tomcat 2. Window IIS 3. Websphere application server Can Django be deployed on Apecha tomcat or websphere? -
"application erorr error error : / " heroku?
I'm beginner in programing(django) and i'm reading django for beginners book, and when i'm trying to deploy my local project to heroku i'm facing to this page: https://afternoon-hollows-30831.herokuapp.com and i do all this steps :screen shot of bookscreen shot of book. "this is my first question in stackoverflow" -
What is djangorest Serializer in Expressjs for node?
I have worked a bit on djangorest(academic projects only). The serializer system is just great. Eg: Serializer validates the Foreign Key attribute received via any request. If the key doesn't exist, it gives the appropriate message. Is there anything like this for Expressjs? I guess Joi is similar, but I'm not sure. Sincere Thanks for your time. Apologies, if I didn't convey my queue well enough - newbie here. -
OperationalError at / no such table: ToDo_todolist
I have run all commands - Python manage.py makemigratinos - python manage.py migrate - python manage.py migrate --run-syncdb I have also registered the model in admin.py file, tried deleting the migrations file multiple times, and recreating them. But nothing worked. Here are some screenshots for a better understanding. Also whenever I click on the table in the admin page, it still shows the same error, also I can't access those items in the admin page. -
Why Django Prefetch is making three query?
Here is my initial query: res = Conversation.objects.filter(pk=pk)\ .prefetch_related( 'message_set' ) print(res) from django.db import connection print("Query count", len(connection.queries)) print("Query", (connection.queries)) Here is the output: Query count 2 Query [{'time': '0.002', 'sql': 'SELECT "messaging_conversation"."id", "messaging_conversation"."is_read", "messaging_conversation"."last_message" FROM "messaging_conversation" WHERE "messaging_conversation"."id" = 8955 LIMIT 21'}, {'time': '0.001', 'sql': 'SELECT "messaging_message"."id", "messaging_message"."conversation_id", "messaging_message"."body", "messaging_message"."file", "messaging_message"."is_read", "messaging_message"."create_date", "messaging_message"."sender_id" FROM "messaging_message" WHERE "messaging_message"."conversation_id" IN (8955) ORDER BY "messaging_message"."create_date" DESC'}] Now i am using Prefetch with prefetch_related like: qs = Message.objects.exclude(file__isnull=True).exclude(file="").only('file') res = Conversation.objects.filter(pk=pk)\ .prefetch_related( Prefetch( 'message_set', to_attr='message_files', queryset=qs ) ) print(res) I am getting 3 queries here: from django.db import connection print("Query count", len(connection.queries)) print("Query", (connection.queries)) Query count 3 Query [{'sql': 'SELECT "messaging_conversation"."id", "messaging_conversation"."is_read", "messaging_conversation"."last_message" FROM "messaging_conversation" WHERE "messaging_conversation"."id" = 8955 LIMIT 21', 'time': '0.001'}, {'sql': 'SELECT "messaging_message"."id", "messaging_message"."file" FROM "messaging_message" WHERE (NOT ("messaging_message"."file" IS NULL) AND NOT ("messaging_message"."file" = \'\' AND "messaging_message"."file" IS NOT NULL) AND "messaging_message"."conversation_id" IN (8955)) ORDER BY "messaging_message"."create_date" DESC', 'time': '0.001'}, {'sql': 'SELECT "messaging_message"."id", "messaging_message"."conversation_id" FROM "messaging_message" WHERE "messaging_message"."id" = 36845', 'time': '0.000'}] Why is it making an extra query: {'sql': 'SELECT "messaging_message"."id", "messaging_message"."conversation_id" FROM "messaging_message" WHERE "messaging_message"."id" = 36845', 'time': '0.000'} -
how to have multiple relations between two models in django
im trying to create models such that a user has record of 1) playlists he has uploaded 2) playlists he has viewed. i tried the following models: class User(models.Model): name=models.CharField email=models.EmailField password=models.CharField isTeacher=models.BooleanField upvotes=models.IntegerField class Playlists(models.Model): creator=models.ForeignKey(User, on_delete=models.CASCADE) viewed_by=models.ManyToManyField(User, on_delete=models.CASCADE) name=models.CharField size=models.IntegerField but i hope you get what i want to do. obvoiusly this scheme doesn't work. but i want to do something on similar grounds -
How to remove unwanted subfolders when creating an archive?
When creating a rar archive in Ubuntu, the archive file eventually contains several subfolders, which are formed from the file path. Actual result: folder.rar /home /y700 /projects file.xlsx Expected result: folder.rar file.xlsx script new_file_name = self.generate_file_name() # geberate file name path_to_temp_folder = os.path.dirname(BASE_DIR) if not os.path.exists(f'{path_to_temp_folder}/files'): pathlib.Path(f'{path_to_temp_folder}/files').mkdir(parents=True, exist_ok=True) # directory creation wb.save(f'{path_to_temp_folder}/files/{new_file_name}') # save excel file archive = self.generate_zip_name(rfi) # generate name for new archive to_rar = f'{path_to_temp_folder}/files' # path to file to_download = f'{path_to_temp_folder}/{archive}' # path to .rar file for djngo response os.system("rar a {} {}".format(archive, to_rar)) # create archive if os.path.exists(to_download): try: with open(to_download, 'rb') as fh: response = HttpResponse(fh.read(), content_type="content_type='application/vnd.rar'") response['Content-Disposition'] = 'attachment; filename= "{}"'.format(archive) return response finally: shutil.rmtree(to_rar, ignore_errors=True) default_storage.delete(to_download) else: raise ParseError -
Why do I need nginx with daphne?
I've seen most people recommend using Nginx as reverse proxy for Daphne to serve a Django application. Why do I need Nginx? Can Daphne not handle everything on its own? -
How do I change currency symbol on django-oscar dashboard?
As the title explains, I want to change the default currency on Django-oscar dashboard. It's showing it as £ and I need R which is South Africa. I have changed my settings.py to South African timezone(johannesburg) and I have added the i18n path. I read that the frontend will check the users local language to set the currency but I know my browser is all set to South African locale. in settings.py I have also added the following which I could be doing wrong: OSCAR_CURRENCY_LOCALE = 'ZAR' OSCAR_CURRENCY_FORMAT = { 'ZAR': { 'format': u'R #,##', } } I'm not sure if this is the correct way to do it or not but the frontend still shows me £ every time. Django-oscar 2.0.4, Python 3.7.4, Django 2.2.12 -
DRF SimpleJWT remove password and add date field
I created a custom user model extending from AbstractBaseUser where the only data I'm getting from the user is a userID, user (the username field) and date (required and in the format dd-mm-yyyy) and the creation of the user works fine as you can see from the DB in the next image Used password = None and last_login = None to refer i didn't want password and last_login tables. Then, created a view where only authenticated users can access. To handle the authentication, used simpleJWT. In urls.py # JWT Token path('api/token/', TokenObtainPairView.as_view(), name='token_obtain'), # Get a new token before the old expires. path('api/token/refresh/', TokenRefreshView.as_view, name='token_refresh'), And by going to http://127.0.0.1:8000/api/token/ , this is what I see (which works as expected) I've tested previously with User and Password in a different project with user model that included that data (User and Password) and worked fine. Now, here, if I try Posting with an existing user but with no password, I get a warning and not being able to Post This field may not be blank. If i add anything other than a blank space, the following error appears TypeError at /api/token/ object of type 'NoneType' has no len() How can I … -
Static Files not Serving in Django React
I am trying to serve static files using ReactJs Build. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "../frontend/build/static"), os.path.join(BASE_DIR, "../frontend/build/assets"), os.path.join(BASE_DIR, "../frontend/build/material-ui-static"), ] It is running, but only loading these file content - ../frontend/build/static But it is not loading static file from ../frontend/build/assets and ../frontend/build/material-ui-static Always giving error - Not Found: /assets/fonts/meteocons/style.css -
Converting Django DelteView to work with ajax
I have a django delte view. I want to use this with ajax. Right now the view is working but the CSRF Token doesnt render. Can someone please help ? view.py -
Multi-tenant socks
So I have a this awesome multi-tenant project I made with Django. I have it deployed on heroku and everything is good to go. BUT its multi-tenant so I need things like customer1.site.com and customer2.site.com I got this working on my side because my computer has a static IP address so I can just route *.site.com to my IP address and then everything works. Heroku doesn't have this ability of static ip addresses. So how can I get past this? I need a cost effective way to solve this. The solutions I see are mainly addons for outbound traffic only. I simply need to route all traffic to *.site.com to an ip address that will show my application on heroku. I in theory can do something like *.app.site.com and route all that traffic to app.herokuapp.com but customer.app.site.com seems way to much honestly. Plus it looks tacky. Has anyone does anything to figure this out?strong text -
How to optimize queryset filtering
I have a little bit of code as follows: for prop in Property.objects.all(): for platform_device in prop.platformdevice_set.all(): if platform_device.platform == cur_platform: if platform_device.applicable_devices.filter(name=cur_device).exists(): if platform_device.applicable_events.filter(name=cur_event).exists(): print("Found my correct even and need to continue processing.") else: for group in platform_device.event_group.all(): if group.applicable_events.filter(name=cur_event).exists(): print("Found my correct even and need to continue processing.") It is a bit messy but it is working so far. Where I am stuck at is this portion: if platform_device.applicable_events.filter(name=cur_event).exists(): print("Found my correct even and need to continue processing.") else: for group in platform_device.event_group.all(): if group.applicable_events.filter(name=cur_event).exists(): print("Found my correct even and need to continue processing.") Basically what I am doing is checking the platform_device.applicable_events to check if inside of that contains my cur_event. If it does then I need to continue processing from that point. Else I am going to look through a event_group (which is just a grouping of events) and checking if cur_event is inside of one of those groups and then continue processing. My question is how can I make both of those avenues end up in the same spot. I am just trying to prevent having the same code in both of those locations. -
Django and bootstrap, why my widget does not work?
I have the following html's boostrap code: <div class="input-group date col-2" id="datetimepicker1" data-target-input="nearest"> {{form.data_contabile|as_crispy_field}} <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker"> <div class="input-group-text"><i class="far fa-clock"></i></div> </div> </div> <script> $(function () { $("#datetimepicker1").datetimepicker({ format: 'DD/MM/YYYY', }); }); </script> And in my form the following code: class MaterialeForm(forms.ModelForm): class Meta: model = Materiale fields = "__all__" exclude = ['iva_amount'] widgets = {'data_contabile': forms.DateTimeInput(attrs={ 'type':'text', 'class':'form-control datetimepicker-input', 'data-target': '#datetimepicker1'})} and finally my models: class Materiale(models.Model): data_contabile=models.DateField('Data di acquisto', default="GG/MM/YYYY") But the layout are the following: Where is the error? -
The `fields` option must be a list or tuple or "__all__". Got str
I am trying to create comment for my article model but i am having issue in the serializer part where it says The `fields` option must be a list or tuple or "__all__". Got str. I already included the parts that are needed,but i don't know where the problem is coming from. Models.py class Comment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.OneToOneField(UserProfile, on_delete=models.CASCADE, related_name='author1') article = models.OneToOneField(Article, on_delete=models.CASCADE, related_name='author2') content = models.CharField(max_length=100) Serializers.py class CommentCreateSerializer(serializers.ModelSerializer): content = serializers.CharField(required=False) class Meta: model = Comment fields = ('content') def create(self, validated_data): return Comment.objects.create(**validated_data) Does anybody know why? -
Get data from a APIview in django rest framework
In my app I am trying to get the User data using a get request and it works in Postman but the problem occurs when I try to send the data from FrontEnd as we cannot send Body in get Request URL: path('user/meta/', UserDetails.as_view()), Views.py class UserDetails(APIView): """Get basic details of user""" def get(self, request): username = request.data["username"] if User.objects.filter(username = username).exists(): user = User.objects.get(username = username) print(user) return Response({ 'verified': user.verified, }) else: return Response("User doesn't exists", status=status.HTTP_400_BAD_REQUEST) How should I modify it such that I can get the data from get request? -
Assigning a Group to a user at signup - Django allauth
Trying to change the authorization of my website from the main django auth to allauth. I've made a custom SignupForm based on the standard SignupForm in allauth. I've added a choicefield based on the pre added Group objects in the database. Now I am trying to assign the user to the Group based on the choice he/she makes in the signupform. I am overwriting the signup method to add the user choice to the user in the database. The user gets registered but is not assigned to any group at all. I'm stuck on how to solve this. forms.py: class CustomSignupForm(SignupForm): user_group = forms.ModelChoiceField(queryset=Group.objects.exclude(name='admin').exclude(name='personeel'), widget=forms.RadioSelect, initial=('particulier') ) first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') fields = ('user_group', ) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] role = self.cleaned_data['user_group'] group = role or None g = Group.objects.get(name=group) user.groups.add(g) user.save() return user settings.py ACCOUNT_FORMS = { 'signup': 'users.forms.CustomSignupForm', } Thanks in advance! Sincerely, Rick -
Real Time Chat using Django channels in DRF
I want to implement real-time chat features in the mobile app, I need to create RESTFUL APIs for this purpose. Chat modes are as follows: One-to-one: Between Individual Users, can include images in chat One-to-Many: In a Group of Users, can include images in chat There is no admin flow right now, How can I achieve this? any helping resource, please? I also want to store chat and chat history, what should be my DB structure any expert opinion? I am using Postgres database. Further, how is it possible to use Firebase? As the mobile app will be communicating with the REST APIs and REST API will be communicating to firebase, I think we can not achieve REAL-TIME COMMUNICATION in this case. AM I CORRECT? -
Why create method is not called in django serializer?
I am want to be able to POST an entry to a ManyToManyField (ImageTag) one by one. I am using extra actions to make a nested endpoint under an Image. I want to be able to POST an entry one POST at a time. localhost:8000/my_app/images/IMG_123/image_tags/ I want to override the create method on the Serializer to do this. But the problem is its not getting called. Why? This is my source code: #models.py class ImageTag(models.Model): name = models.CharField() description = models.CharField() class Image(models.Model): image_id = models.CharField(unique=True) image_tags = models.ManyToManyField(ImageTag, blank=True) ... #serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = '__all__' class ImageTagSerializer(serializers.ModelSerializer): image_tags = serializers.StringRelatedField(many=True) class Meta: model = Image fields = ('image_tags',) def to_internal_value(self, data): return data def create(self, validated_data): print("GOTHERE") print("VALI", validated_data) return validated_data #views.py class ImageExtraAction(viewsets.ModelViewSet): @action(detail=True, methods=['get', 'post', 'delete']) def image_tags(self, request, capture_id=None): capture = self.get_object() serializer = ImageTagSerializer(capture, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ImageTagViewSet(ImageExtraAction, viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer lookup_field = 'image_id' ... #urls.py router.register(r'images', ImageTagViewSet, basename='image') -
Django logging to multiple files at once even with RotatingFileHandler?
I am using Django with logging config as follow: LOGGING = { 'version':1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{asctime} {process:d} {thread:d} {levelname} {name} {module} {funcName} {message}', 'style': '{', } }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': BASE_DIR+'/logs/django_logs.log', 'backupCount': 14, 'maxBytes': 52428800, 'formatter': 'verbose' } }, 'loggers': { '': { 'handlers': ['file'], 'level': 'INFO' } }, } I am running 16 processes of django, few daphne for websockets and few gunicorn. But when I am looking at logs, multiple files are getting logged at once. For ex, django_logs.1 .... django.logs.14 are getting logged into simultaneously. Do I have to add something else to make it work. For extra info, I am using python 3.6.8 and I generally initialize logger in each file as follow: import logging logger = logging.getLogger(__name__)