Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ordery_by is not working for boolean field in Django
i am running the query, but the ordery_by is not working for boolean field value. Any help, would be much appreciated. thank you. queryset = ShopOffer.objects.filter(added_by__user_id=user).order_by('-is_active') -
What is the right way to use service methods in Django?
As an example, let's say I am building an Rest API using Django Rest Framework. Now as part of the application, a few methods are common across all views. My approach is that in the root directory, I have created a services.py file. Inside that module, is a class (CommonUtils) containing all the common utility methods. In that same services.py module I have instantiated an object of CommonUtils. Now across the application, in the different views.py files I am importing the object from the module and calling the methods on that object. So, essentially I am using a singleton object for the common utility methods. I feel like this is not a good design approach. So, I want to get an explanation for why this approach is not a good idea and What would the best practice or best approach to achieve the same thing, i.e use a set of common utility methods across all views.py files. Thanks in advance. -
Django DLL load failed after trying to setup django project on pycharm
I just made a django project using pycharm professional in order to try and make an API that way. I try to run the django server using python manage.py runserver command and I get the following error:[[the errors][1]] 2 -
How to add formating options in django forms?
I just wanted to know how I can add formating options to a website powered by django for example stack overflow has this default editing option: example Is there any plugin or am I supposed to do this manusally if I wanted to add this functionality to my website, how would I go about doing it? -
Angular 9, Leaflet, Django: Add multiple HTTP get request layers to leaflet map
I have about 20 or so layers I need to add to a leaflet map from a django backend. The only way I've successfully implemented this, while also add those layers to layerControl is by using the following: map.component.ts layers: L.Layer[]; layersControl: any; constructor(private http: HttpClient) {} getFeatureOne = this.http.get<any>('http://localhost:8000/api/layerOne'); getFeatureTwo = this.http.get<any>('http://localhost:8000/api/layerTwo'); etc... ngOnInit() { this.getFeatureOne.subscribe( featureOne => { this.getFeatureTwo.subscribe( featureTwo => { etc.. const layerOne = L.geoJSON(featureOne); const layertwo = L.geoJSON(featureTwo); this.layers = [layerOne, layerTwo]; this.layersControl = { baseLayers: { 'Open Streets': this.openStreets }, overlays: { 'Layer One': layerOne, 'Layer Two': layerTwo } }; } ); } ); } map.component.html <div id="map" leaflet [leafletLayers]="layers" [leafletLayersControl]="layersControl" [leafletCenter]="center" [leafletZoom]="zoom" [leafletFitBounds]="fitBounds3"> </div> Surely there's something I'm missing, but I haven't been able to find it here or anywhere else. Any help would be greatly appreciated. -
How to implement Python in Django .html templates
I'm trying to build a web page using Django. I'm writing a simple stopwatch script in Python that I want to then have show up on my home.html file. So two questions : How can I put python code into my HTML file? Where can I create .py files in the Django framework so it can be located? Thanks in advance -
Django error 'URLs with hostname components are not permitted'
I have deployed a django application which invokes a python file to send captured data on django form to a third party independent server. The problem is that when the python file is invoked from django form, it leads to this error as seen on the browser - file: URLs with hostname components are not permitted Request Method: POST Request URL: http://127.0.0.1:8000/phone_associate_form/ Django Version: 3.1.3 Exception Type: ValueError Exception Value: file: URLs with hostname components are not permitted Exception Location: E:\INVOKEDID\lib\site-packages\requests_file.py, line 34, in send Here is the output for local variables as seen kwargs {'cert': None, 'proxies': OrderedDict(), 'stream': False, 'timeout': 20, 'verify': False} request <PreparedRequest [GET]> self <requests_file.FileAdapter object at 0x000001DBB1302B88> url_parts ParseResult(scheme='file', netloc='E:', path='/INVOKEDID/NumberRepo/MASTERHANDLER/axlsqltoolkit/schema/current/AXLAPI.wsdl', params='', query='', fragment='') Here is pip freeze output from django - appdirs==1.4.4 asgiref==3.3.0 attrs==20.3.0 beautifulsoup4==4.9.3 cached-property==1.5.2 certifi==2020.6.20 chardet==3.0.4 defusedxml==0.6.0 diff-match-patch==20200713 Django==3.1.3 django-crispy-forms==1.9.2 django-easy-audit==1.3.0 django-import-export==2.4.0 django-shibboleth-remoteuser==0.12 et-xmlfile==1.0.1 idna==2.10 isodate==0.6.0 jdcal==1.4.1 lxml==4.6.1 MarkupPy==1.14 numpy==1.19.4 odfpy==1.4.1 openpyxl==3.0.5 pandas==1.1.4 psycopg2==2.8.6 python-dateutil==2.8.1 pytz==2020.4 PyYAML==5.3.1 requests==2.24.0 requests-file==1.5.1 requests-toolbelt==0.9.1 six==1.15.0 soupsieve==2.0.1 sqlparse==0.4.1 tablib==2.0.0 urllib3==1.25.11 xlrd==1.2.0 xlwt==1.3.0 zeep==4.0.0 -
Is there a way to add middleware for a particular url route in django?
Say I have some URLs: urlpatterns = [ path('', Home.as_view()), path('games/', include('games.urls', namespace='games')), ] Is there a way that I can get a given middleware to run only when accessing urls under games? E.g. to check auth or to pre-fetch some data that will be useful to all views in the games app. -
Django model designing problem when creating a follower / following relationship
I'm trying to create a followig system for my application, and when I thought it worked, I realised that when account a started following account b, account b also started following account a My models: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): followers = models.ManyToManyField('self', blank=True, related_name='followers') following = models.ManyToManyField('self', blank=True, related_name='following') class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='p_author') body = models.TextField(max_length=500) time = models.TextField() #Added when creating object with the API likes = models.IntegerField(default=0) def serialize(self): return { 'id': self.id, 'author': self.author.username, 'body': self.body, 'time': self.time, 'likes': self.likes } class Comment(models.Model): post_commented = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='c_post') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='c_author') body = models.TextField(max_length=500) time = models.TextField() #Added when creating object with the API likes = models.IntegerField(default=0) The view that handles the follow action (called via a JS fetch call): ef follow(request, profile_name): user_object = User.objects.get(username=profile_name) if request.method == 'PUT': print(request.user) data = json.loads(request.body) if data.get('follow') == True: followers_set = user_object.followers followers_set.add(request.user) user_object.save() return JsonResponse({'status': 'success'}, status=204) I'm supposing that I will need to restructure my whole database and project to fix this bug, how would you suggest I do it? -
Course Details are not showing
I'm trying to get course details from enrolled course but it returns only the course ID. I tried with nested serializers but it went wrong. How can I get course details with the following setup models class Course(models.Model): course_name = models.CharField(max_length=300,default=None) author = models.ForeignKey(TeacherProfile,on_delete=models.CASCADE,null=True,default=None) course_description = models.TextField(null=True) course_cover = models.ImageField(null=True,blank=True,upload_to='course_covers/') def __str__(self): return self.course_name class Enrollment(models.Model): enroll_key = models.CharField(max_length=100,default="Text here",null=True) course = models.ForeignKey(Course,on_delete=models.CASCADE,null=True,related_name='enrollment') student = models.ForeignKey(StudentProfile,on_delete=models.CASCADE,null=True) def __str__(self): return self.course.course_name serializer class MycoursesSerializer(serializers.ModelSerializer): class Meta: model = Enrollment fields = "__all__" View @api_view(['GET']) @permission_classes([IsAuthenticated]) def MyCourses(request): student = StudentProfile.objects.get(user=request.user) courses_enrolled = Enrollment.objects.filter(student=student) serializer = MycoursesSerializer(courses_enrolled,many=True) return Response(serializer.data) response { "id": 1, "enroll_key": "Text here", "course": 1, "student": 1 } -
Test django allauth socialAccount creation
When a user signs up using a socialAccount (google in my case) I have a user_signed_up signal that tests if the user signed up using a socialAccount, and if they did then it associates data from the socialAccount instance with the User model instance. How would I create a user using the socialAccount method as part of a test, using pytest? the signal definition is: import logging from allauth.account.signals import user_signed_up from django.contrib.auth import get_user_model from django.dispatch import receiver User = get_user_model() logger = logging.getLogger("email_app.apps.users") @receiver(user_signed_up, sender=User, dispatch_uid="apps.users.signals") def associate_social_data_with_user_model(user, **kwargs): if user.socialaccount_set.filter(provider='google').count() < 1: logger.info(f"social account single sign on not used. user signed up the old fashioned way. {user = }") else: extra_data = user.socialaccount_set.filter(provider='google')[0].extra_data user.name = extra_data['given_name'] user.save() -
how can i handle multiple files (photos/videos) in single post Django template?
i want to upload multiple file like (photos&videos) in a single post like Facebook. i don't know how can i handle or show photo or videos in template side? anybody know how to arrange in template side? models.py class Article(models.Model): title = models.CharField(max_length=300,) file_data = models.FileField(upload_to='stories', blank=True, null=True) def __str__(self): return self.title def extension(self): name, extension = os.path.splitext(self.file_data.name) return extension forms.py class ArticleForm(forms.ModelForm): file_data = forms.FileField(required=False, widget=forms.FileInput( attrs={'accept': 'image/*,video/*', 'multiple': True})) class Meta: model = Article fields = [ 'title', 'file_data', ] {% for object in newss %} <div class=" card"> {% if object.file_data %} <img src="{{object.file_data.url}}" alt="article" height="400"> {% endif %} {% if object.file_data %} <video class="afterglow" id="myvideo" width="1280" height="720" data-volume=".5"> <source type="video/mp4" src="{{object.file_data.url}}#t=0.9" /> </video> {% endif %} </div> -
Failed to create virtual environment directory in cmd
Unable to create venv using python 3x; python -m venv myclub Error: Command '['C:\Users\Sibasankar Panigrahi\myclub\Scripts\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101. -
Is this example of model object property usage unique to a logged-in session in django?
I know django optimises with some model instance re-use. So - the question is really - is the value of 'imprints' shown below unique to a logged-in session in django? Lets say I have a django deployment in which, with this model. Class Thing(models.Model): example_field = models.UUIDField(default=uuid.uuid4, editable=False) imprints = None # placeholder for imprints to be added dynamically def add_imprints(self, cc): """ Adds an imprints object associated with this instance for passed cc to this instance. """ self.imprints = cc.imprint_set.get(entity=self) using the ORM, an instance of this Thing model in the db is pulled up in a view, say with. object = Thing.objects.get(pk=thing_id) a value is then assigned to the imprints field which is intended just as an addition to the instance so that when it is passed to another function that added information is there - like this object.add_imprints(cc) To emphasise - the imprints value is only used to pass information with the instance of Thing during the processing of a view and through some related functions, there is no need for further persistence and it must be unique to the session. Normally there is no problem with this kind of practice - however there may be a … -
How to store multiple userids in same model?
I'm fairly new to Django and attempting to store a model which will hold transaction information for a purchase between 2 users; a buyer and seller. I therefore want to store 2 UserIDs: class Transaction(models.Model): transactionid = models.AutoField(primary_key=True) # USERID OF SELLER # USER ID OF BUYER orderid = models.ForeignKey('Order', db_column='orderid', on_delete=models.SET_NULL, blank=True, null=True) status = models.CharField(choices=PAYMENT_STATUS, default='pending', max_length=50) timestamp = models.DateTimeField(auto_now_add=True) I want to use the following foreign key: seller = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) however, to my understanding, this will only store the current logged in user which means I wouldn't be able to set both? Is there a better way to do this rather than modifying the model twice (esentially from both accounts)? Any reccomendations or advice appreciated, thank you! -
How to create a django-admin import / export who impacts multiples models?
I need to create a way to import / export data using django-admin in a way the user uploads an excel sheet and the content of this excel impacts 3 different models. I already saw https://django-import-export.readthedocs.io/ but it appears to impact only one model. So how is the best approach to accomplish this? -
Can I use global variables in Django?
I am solving a problem with Django, and the best way, how I think, is using global variables. For example, I need a variable page. When one user sends a request to the fifth page on my site, page=5. But when the second user watches the third page, page should be 3, but for the first user it must be still 5. So for different users, one variable must has different value in one time. I want to make page a global variable and change its value in function. Are there some risks? What can you advise me? -
Authentication credentials were not provided when sending request from React JS axios
I'm building a simple API, but right now I'm having some issues with the back-end. I always used the Django-rest-framework serializers, but now I'm trying to code a function-based view. My back-end server uses knox token authentication as a default, I have this set up in the Django settings (below) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication', ) } So the thing is that when the POST request is sent from the postman, the server identifies the user which calls the request, but when the request is sent from React JS the server couldn't find the user. This is my views.py function-based view: @csrf_exempt @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) def hello_world(request): print(request.data) print(request.headers) print('user', request.user.username) This is what I get when sending the request from POSTMAN - {'report': 'testas'} {'Content-Length': '28', 'Content-Type': 'application/json', 'Authorization': 'Token 024f51b3f210082302ceb1fff29eff3fcefd50437c6909ca7d6647a1ce1d66bb', 'User-Agent': 'PostmanRuntime/7.26.8', 'Accept': '*/*', 'Postman-Token': '5e9be4f1-cbf5-4f8f-bf7c-f44761c30798', 'Host': '192.168.0.30:8000', 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive'} user 3nematix And this comes from React JS : {'headers': {'Content-Type': 'application/json', 'Authorization': 'Token d8bce38c58d07ade11446147cab60ac7795813232cc44d93e9d0da46bd16384e'}} {'Content-Length': '136', 'Content-Type': 'application/json;charset=UTF-8', 'Host': '192.168.0.30:8000', 'Connection': 'keep-alive', 'Accept': 'application/json, text/plain, */*', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36', 'Origin': 'http://192.168.0.30:8000', 'Referer': 'http://192.168.0.30:8000/reports/view', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9'} user How can I fix … -
Make LEFT JOIN query in ORM
Hello everyone i want to write this query in ORM help please: SELECT *, COALESCE(widgets_userwidget.sort,0) as sort,COALESCE(widgets_userwidget.column,1) as column FROM widgets_widgetcatalog LEFT JOIN widgets_userwidget ON (widgets_widgetcatalog.uid=widgets_userwidget.uid) and widgets_userwidget.user_id=%s' % self.request.user.id I make this query using raw but he doesn't display all fields but in pgadmin this query display all fields. Serializers class WidgetCatalogSerializer(serializers.ModelSerializer): class Meta: model = models.WidgetCatalog fields = "__all__" class WidgetSerializer(serializers.ModelSerializer): widget = WidgetCatalogSerializer(read_only=True) class Meta: model = models.UserWidget fields = "__all__" -
Django choose in what location images are loaded in model's save method
Here's my save method for model with field image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True): def save(self, *args, **kwargs): if self.image: self.image = compress(self.image) if self.second_image: self.second_image = compress(self.second_image) if self.third_image: self.third_image = compress(self.third_image) if self.fourth_image: self.fourth_image = compress(self.fourth_image) super().save(*args, **kwargs) It works fine and compresses all images but changes image's directory every time when I click save in django admin. It makes all images' paths be like: before edited and saved: products/2020/11/05/img.jpeg after: products/2020/11/05/products/2020/11/05/img.jpeg click save one more time: products/2020/11/05/products/2020/11/05/products/2020/11/05/img.jpeg And then I get this error: SuspiciousFileOperation at /admin/shop/product/6/change/ Storage can not find an available filename for "products\2020\11\05\products\2020\11\05\products\2020\...... .jpeg". Please make sure that the corresponding file field allows sufficient "max_length". How can I fix this problem? I think I need to choose location where saved images would be stored. Django doesn't let me use absolute path in upload_to field so I have no idea. -
Django pagination in html template
i want to use pagination , but i can not do it in html. views.py def blog_list(request): articles = Blogmodel.objects.all() page = request.GET.get('page', 1) paginator = Paginator(articles, 20) try: page = paginator.page(page) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) args = {'articles':articles,'page':page} return render(request,'blog.html',args) html <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"><a class="page-link" href="#">Previous</a></li> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item"><a class="page-link" href="#">2</a></li> <li class="page-item"><a class="page-link" href="#">3</a></li> <li class="page-item"><a class="page-link" href="#">Next</a></li> </ul> </nav> can anyone help me , how to do this in html ? -
Unable to apply I18n with Django/Docker
I have develop a Django app with Docker it works but I want to internationalize (i18n) my app I connect to my container docker exec -it my_container_1 sh I try to run python manage.py makemessages -l fr but got an error When conatiner is built, requirements.txt is applyed and python-gettext is installed I am newbie with Django with docker and probably i missunderstand. requirements.txt Django==2.2.5 psycopg2-binary==2.8.5 django-bootstrap4==1.0.1 django-crispy-forms==1.7.2 django-debug-toolbar==2.0 django-extensions==2.2.9 django-maintenance-mode==0.15.0 django-partial-date==1.2.2 django-safedelete==0.5.2 django-simple-history==2.7.3 django-widget-tweaks==1.4.5 Pillow==6.2.2 python-gettext==4.0 <-- ****************************** pytz==2019.2 reportlab==3.5.32 selenium==3.141.0 six==1.12.0 soupsieve==1.9.3 sqlparse==0.3.0 urllib3==1.25.6 xlwt==1.3.0 settings.py MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', ... ] LANGUAGES = ( ('en', _('English')), ('fr', _('French')), ) LOCALE_PATHS = [ os.path.join(BASE_DIR,'locale'), ] Dockerfile # Pull the official base image FROM python:3.8.3-alpine # Set a work directory WORKDIR /usr/src/app # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN apk --update add libxml2-dev libxslt-dev libffi-dev gcc musl-dev libgcc openssl-dev curl RUN apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev RUN pip3 install psycopg2 psycopg2-binary # Install dependencies COPY requirements/ requirements/ RUN pip install --upgrade pip && pip install -r requirements/dev.txt COPY entrypoint.sh . # Copy the project's files … -
How to count occurrences from db in django
I have simple table in SQLite with id, process and step in process id. I need to display how many steps have every process. I have something like this but it doesn't work as I need: for steps in StepsInProcesses.objects.all(): activ_count = activ_count + proc.steps.count() -
How to load static images in a function not in view
I am using a django template to generate pdf via feeding it a context object from the function but not the view, it works fine in case of view, but I am not able to load the local static images on the template from the function. but this is possible in view because there I can tell which base path to use. But I not able to do the same in the function. As you can see I can how I am getting the base url from the view. Here I can get because I have requests object but in function I do not have any requests object. So images are not loading. html = HTML(string=html_string, base_url=request.build_absolute_uri('/')) This is how I am trying to do in the function: html_string = render_to_string('experiences/voucher.html', data) html = HTML(string=html_string, base_url=settings.STATIC_ROOT) result = html.write_pdf("file_new.pdf", stylesheets=[css],optimize_images=True) I would like to know how can I tell, where are my images so that images can be rendered on the pdf. -
ProgrammingError column Users_student.school does not exist in django
I've been struggling with this issue for hours now. I have a model in my app which goes like this class Student(models.Model): school = models.CharField(max_length=100, null=True, blank=True) field_of_study = models.CharField(max_length=100, null=True, blank=True) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='Student') courses = models.ManyToManyField('StudentDashboard.Course', related_name="student_courses") And whenever I try to view details of this class through django admin panel, I face the error ProgrammingError column Users_student.school And if I comment school, that happens for field_of_study. And if that is commented too, It works fine. But I actually do need those 2 fields so I can't just comment them and go on. Anyone knows a solution to this? Thanks in advance!