Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Force user authentication in URL dispatcher of Django
I would like to restrict a specific path to authenticated users in urls.py. I know how to do it in views.py, the problem is that this is a module which I have installed using pip, so I do not handle it in my views, and I do not want to modify the source code of this module. ... path('thispath/', include('module.urls')), ... May I force an authentication in urls.py ? Or should do it in views.py as usual (or using decorators): request.user.is_authenticated -
Django for TCP/IP and Websockets connections
I am building a trading back-end that provides live streaming prices (over Websockets) and trading functionality (REST endpoints) to the web client. The back-end was planned to be build with Django. However, the back-end also needs to receive live prices over TCP/IP connection from the 3rd party server and further distribute prices over Websockets to end-users. Django is powerful and has lots of built-in features out-of-the-box including REST framework, admin panel, ORM, etc. However, how I start a TCP connection and distribute price feed over Websockets? Can I use a management command to start a new thread? Should I rather look into a different frameworks like Tornado? Tornado is apparently good for non-blocking network I/O and Websockets. However, it's a complex thing with a lot of state. If I could, I'd rather stick with Django. What would you suggest? -
django rest join two models in one APIview
I got two models class BaseModule(models.Model): name = models.CharField(max_length=255) class CompanyModule(BaseModelFields): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='company_module') module = models.ForeignKey('common.BaseModule', on_delete=models.CASCADE) i need to return API view that looks like this data: { available: [{id:1, name: 'one'}, {id: 5, name: 'five'}], registered: [{id:2, name: 'two'}, {id:3, name: 'three'}, {id:4, name: 'four'}] } also when i register new module he need to show in register and be removed from availabe. I got CompanyModuleSerializer which is ModelSerializer and return only data with registered modules. Im stuck and dont know how to move on. Every help is appreciated -
Saving images in FormWizard Django is not working
I have created a Django application that needed the user to fill in forms in order to create new course. I have use FormWizard to create a multiplestepformsubmission. The form will also ask a user to upload an image for the course cover. However, it is not working as expected & the file is not uploaded to the filesystem. The error that I got when saving to filesystem was that the media is not selected/media is required. Please help. models.py class Course(models.Model): CATEGORY = ( ('IT & Software', 'IT & Software'), ('Mathematics', 'Mathematics'), ('Science', 'Science'), ('English', 'English'), ('Bahasa Melayu', 'Bahasa Melayu'), ) LEVEL = ( ('Easy', 'Easy'), ('Intermediate', 'Intermediate'), ('Advanced', 'Advanced'), ) LANGUAGE = ( ('English', 'English'), ('Bahasa Malaysia', 'Bahasa Malaysia'), ('Chineese', 'Chineese'), ) CERTIFICATE = ( ('Yes', 'Yes'), ('No', 'No'), ) media = models.ImageField(upload_to = 'media/course') title = models.CharField(max_length=30, null = False) subtitle = models.CharField(max_length=50, null = False) description = models.CharField(max_length=2000, null = False) language = models.CharField(max_length=20, null = False, choices=LANGUAGE) level = models.CharField(max_length=20, null = False, choices=LEVEL) category = models.CharField(max_length=30, null = False, choices=CATEGORY) subcategory = models.CharField(max_length=20, null = False) price = models.IntegerField(null = False) roles_responsibilities = models.CharField(max_length=250, null = False) timeline_budget = models.CharField(max_length=250, null = False) req_prerequisite … -
“Oops! The embed code for this video is not valid!”
I am using djago embed video package to embed videos from vimeo and youtube, youtube is working where as vimeo throws this error my models class Video(ModelMeta, models.Model): title = EmbedVideoField( verbose_name='Either Choose video from youtube/vimeo or', blank=True, null=True) and in templates <div class="embed-responsive embed-responsive-21by9 mgb-2"> {% if object.title %} {% object.title 'tiny' %} {% endif %} </div> how to solve the issue, thanks -
upstream prematurely closed connection while reading response header from upstream, client: 192.168.208.1, server: localhost, request
I am trying to deploy my Django project in docker. unfortunately, I get 502 Bad Gateway error, I tried everything that I could find online, but still the same error. The Dockerfile: FROM python:3.9-slim-buster # create directory for the app user ENV APP_HOME=/home/app/web # create the app user RUN addgroup --system app && adduser --system --group app # create the appropriate directories RUN mkdir -p $APP_HOME # where the code lives WORKDIR $APP_HOME # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install python dependencies RUN apt-get update \ && apt-get install -y build-essential python3-dev python2.7-dev \ libldap2-dev libsasl2-dev libssl-dev ldap-utils tox \ lcov valgrind \ && apt-get -y install gcc \ && apt install -y netcat # install psycopg2 dependencies RUN apt-get install -y postgresql-server-dev-all musl-dev # copy project COPY . $APP_HOME # install dependencies COPY ./requirements.txt $APP_HOME RUN pip install --upgrade pip RUN pip install -r $APP_HOME/requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh $APP_HOME RUN sed -i "s/\r$//g" $APP_HOME/entrypoint.sh RUN chmod +x $APP_HOME/entrypoint.sh # chown all the files to the app user RUN chown -R app:app $APP_HOME RUN chmod -R 755 $APP_HOME # change to the app USER app # run entrypoint.sh ENTRYPOINT ["/bin/bash","/home/app/web/entrypoint.sh"] and the docker-compose.yml … -
How to extend PageLinkHandler to accept an anchor on a Page
I want to extend Wagtail's PageLinkHandler to combine an internal PageChooser link with an AnchorLink, so the template output is <a href="/mypage#myanchor". class AnchorPageLinkHandler(PageLinkHandler): identifier = 'page_anchor' @staticmethod def get_model(): return Page @classmethod def get_instance(cls, attrs): return super().get_instance(attrs).specific @classmethod def expand_db_attributes(cls, attrs): try: page = cls.get_instance(attrs) hash_id = attrs["hash_id"] return '<a href="{}#{}">'.format(escape( page.localized.specific.url), hash_id) except Page.DoesNotExist: return "<a>" @hooks.register('register_rich_text_features') def register_link_handler(features): features.register_link_type(AnchorPageLinkHandler) I have got this far, but have 2 problems: i) page_anchor does not show up in the link editor widget, how do I enable this? ii) how do I add the hash_id text input to the widget when I do enable it? -
Use Q object and Paginator together in Django
I've created View which filters data by search query given in textbox. As well as I used Paginator to show data divided into pages. My problem is, when I filter data with Q object then and try to paginate by clicking the next button, all data is refreshed. When I search text by Q object the URL becomes http://127.0.0.1:8000/mael/parties/?q=keyword And from clicking the next button the URL becomes http://127.0.0.1:8000/mael/parties/?page=2 When I manually change URL http://127.0.0.1:8000/mael/parties/?q=keyword&page=2, then it works. But I don't know how to do this in code. Is it possible to use Q object search and pagination together? My View from mael.models import PartyTotalBillsView from django.views.generic import ListView from django.db.models import Q from django.http import HttpResponseRedirect class PartyListView(ListView): paginate_by = 2 model = PartyTotalBillsView def parties(request): # Show all records or searched query record search_text = request.GET.get('q','') try: if search_text: queryset = (Q(party_name__icontains=search_text)) party_list = PartyTotalBillsView.objects.filter(queryset).order_by('party_name') else: # Show all data if empty keyword is entered party_list = PartyTotalBillsView.objects.order_by('party_name') except PartyTotalBillsView.DoesNotExist: party_list = None paginator = Paginator(party_list, 2) # Show 2 rows per page: for Test page_number = request.GET.get('page') party_list = paginator.get_page(page_number) return render(request, 'mael/parties.html', {'party_list': party_list}) Template file <form id="search-form" method="get" action="/mael/parties/"> <input id="search-text" type="text" name="q" placeholder="Enter search … -
dynamic css files dirs django
** note all websites in this django project built with react js i have a small problem please see this screen shot: enter image description here i am create a project that create websites like website builder every thing work file except the static files i cant link the static file for every sigle website every website have his own static files any one have a solve for this please? :) how i can make a dynamic static files dirs -
Combining 2 sets of model objects in alphabetical order
In my code, I currently have 2 models (Company and Individual Model) Now I need to print both sets of data on the same report but it needs to be in alphabetical order This is how I have referenced them in views.py separately modelCompany = CompanyClass.objects.all().order_by('CompanyName') modelIndividual = IndividualClass.objects.all().order_by('Surname') But how would I be able to join them in the same list and organize them alphabetically? -
Error while passing a json field in graphql mutation with django
the below code is to update the "personalize" field in the user model (django), which is a json field, not sure how to pass it has an argument to the mutation class AddPersonalization(graphene.Mutation): ok = graphene.Boolean() class Arguments(): user_id = graphene.Int(required=True) personalize = graphene.JSONString(required=True) def mutate(self, user_id, personalize): try: get_user_model().objects.filter(id=user_id).update(personalize=personalize) except get_user_model().DoesNotExist: raise Exception("User doesn't exist") return AddPersonalization(ok=True) graphql query mutation{ addPersonalization(userId :285 ,personalize:["sample1", "sample2"] ) { ok } } error response : { "errors": [ { "message": "Argument \"personalize\" has invalid value [\"sample1\", \"sample2\"].\nExpected type \"JSONString\", found [\"sample1\", \"sample2\"].", "locations": [ { "line": 2, "column": 47 } ] } ] } -
How to serialize Streamblock in Wagtail?
I have the following code from apps.home.utils.blocks import get_internal_page_api_representation from django.utils.translation import ugettext_lazy as _ # NOQA from wagtail.core import blocks from apps.home.blocks.image_chooser_block import ImageChooserBlock class NavColumnBlock(blocks.StructBlock): """A Nav Column block with title and internal sublinks""" title = blocks.CharBlock( max_length=100, help_text=_('Title of the linked page (max. 45 chars)'), ) link = blocks.PageChooserBlock( required=True, help_text=_('Link to the page') ) sublinks = blocks.StreamBlock([ ('icon', ImageChooserBlock(required=True, min_num=1, max_num=1, help_text=_('Icon of a subpage'))), ('sublink', blocks.PageChooserBlock(required=True, min_num=1, max_num=1, help_text=_('Link to a subpage'))) ], min_num=1, max_num=6) def get_api_representation(self, value, context=None): """Tweaks the API representation so it contains the serialized data""" linked_page = value.get('link', None) sublinks = value.get('sublinks', []) sublinks_child_blocks = self.child_blocks.get('sublinks') return { 'title': value.get('title', ''), 'link': get_internal_page_api_representation(linked_page), 'sublinks': sublinks_child_blocks.get_api_representation( sublinks) if sublinks_child_blocks else [], } class Meta: icon = 'placeholder' label = _('Column') Goal: I need each object inside of the sublinks array to contain an icon and a url. Now I added one test object and the value doesn't have the content I need. Problem: In the api representation, I see that the value of an object inside of a sublinks array needs to be serialized. (Image below) Now value just shows me a number, probably the number of elements (id, icon and url). … -
Optional serializer field in Django Rest Framework
How can I set a serializer field to optional in Django REST Framework? I have the following serializer: class IdSerializer(serializers.Serializer): id = serializers.IntegerField(required=None) required is set to None following the docs. And my view: class MyView(APIView): serializer_class = PostIdSerializer def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): post_id = serializer.validated_data.get("id") return Response() **However, when I send a POST request to the endpoint, I get the error: { "id": [ "This field is required." ] } How can I allow no id to be sent? -
Django return two variables (one related) in for loop
I'm building a school schedule management system With this system, someone can select a module and see the the teachers available on that day and what other classes they have at this specific day. So for example, if someone clicks "Maths", you will see the following: teacher_name1 - Date: 20/2/2022 Other classes on the same day: Physics, History teacher_name2 - Date: 20/2/2022 Other classes on the same day: None I can get the first part of when someone clicks the module, to get a list of teachers for a specific date, but I cannot get the rest of the modules that the teacher is having on the same day My models are the following: class Available_Module(models.Model): module_name = models.CharField(max_length=100, unique=True, blank=True, null=True) slug = models.SlugField(max_length=255, unique=False, null=True) class Teacher(models.Model): teacher_name = models.CharField(max_length=100, unique=True, blank=True, null=True) slug = models.SlugField(max_length=255, unique=False, null=True) class Schedule(models.Model): calendar_date = models.DateField(default=date.today) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=True, related_name="available_teacher") module = models.ForeignKey(Available_Module, on_delete=models.CASCADE, null=True, related_name="module_item") created_at = models.DateTimeField(default=timezone.now) Below the views.py: def teachers_listing(request, module_slug, **date_filters): module = Available_Module.objects.get(slug=module_slug) get_module_id = Available_Module.objects.get(slug = clinic_slug).id default_date = today recent_dates = Schedule.objects.order_by('calendar_date').distinct('calendar_date').filter(calendar_date__range = (today, date_range)) date_filters = recent_dates available_teachers = Schedule.objects.filter(module=get_module_id, calendar_date=default_date).order_by('module') return render(request, 'schedule_core/available_teachers.html', { 'available_teachers': available_teachers, 'module': module, 'date_filters': … -
How can I find all flaky tests that may fail on some days as a result of date being updated by the new code
I have added an update to an existing code base where if an item is due on a weekend I add two days to it.(moved it to a week day) Now the old tests which were not using a fixed mock_timezone_now(self.now) will fail when run on a Thursday for example because the duration is 30 days and this item is likely to be due on a weekend. How can I identify all the tests that will fail? Is there a way of setting a frozen time while running tests. There are over 50 files and I can't manually trace all occurrences of possible fails. -
how to create link in django for substring
I am struggling to understand how to create a link in django's templates. in my views.py file I have a list of lists (so a table). One of the fields may or may not contain links. Views.py #tableToView is a pd.DataFrame() actualTable = [] for i in range(tableToView.shape[0]): temp = tableToView.iloc[i] actualTable.append(dict(temp)) #Returning the 'actualTable' list of lists to be printed in table format in the template return render(response, "manual/manualinputs.html", {'defaultDates':defaultDates, 'prevFilterIn':prevFilterIn, 'actualTable':actualTable, 'DbFailure':DbFailure}) so imagine my actualtable has a field 'News' that may or may not contain a link, e.g.: 'hello there, go to https://www.google.com/' How do I manage the fact that I want in my template to have the same string printed out, but with the address actually being a link? I will also extend this to non-addresses (say twitter hashtags by parsing text). Should I act on views or templates? I did try to go the views way: I substitute the 'hello there, go to https://www.google.com/' with 'hello there, go to <a href="https://www.google.com/" target="_blank">https://www.google.com/</a>' But I get the actual tags printed out, which is not what I want... Any ideas? -
send request to the url if matches otherwise send it to parameterised url in django
urls.py urlpatterns = [ re_path(r'^([-\w]{3,})/$', shop_from_url, name='shop_from_url'), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include('products.urls')), path('authenticate/', include('authenticate.urls')), path('order/', include('order.urls')), path('offers/', include('offers.urls')), path('event/', include('event.urls')), path('product_upload/', include('product_upload.urls')), path('restaurant/', include('restaurant.urls')), path('shop/', include('store.urls')), ] i have these url pattern. If you watch it, the first and other url path, they are exactly same in the way they are written. the difference is only that first url is parameterised url and other are hardcoded urls. But actually when i call any of the url the first urls also called. I have to check if there is any existing url (like authenticate/, product_upload/) matching to any of the app url then it should redirect to that otherwise it should call re_path(r'^([-\w]{3,})/$')(first url) this url Is there any way to call the first url (which lies in this pattern) only when the url does not matches the other urls. Note: I cannot change the urls as it is a requirement. -
Trying to Implement simple API in Django
I am very new to Django and trying to implement small API for social media website where I can monitor if post has been liked and number of likes and later fetch API using JavaScript so I can like without refreshing the page using put method. Problem is that I largely failed because of lack of proper knowledge. I could not get the API working in the first place. models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class New_Post(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) New_Post = models.CharField(null=True, max_length=300) def __str__(self): return f"{self.New_Post}" class Likes(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) like = models.BooleanField(default=False) New_Post = models.ForeignKey(New_Post, null=True, on_delete=models.CASCADE) def serialize(self): return { "id": self.id, "post": self.New_Post, "user": self.user, "like": self.like } views.py fragment def likes(request): like = Likes.objects.all() return JsonResponse(like.serialize()) urls.py urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("Post", views.likes, name="likes"), ] When I try to access Post url I expect json response to be shown on mostly blank page. Should it be like that? How can I get my API working? -
Why Do I Keep Receiving FileNotFoundErrors Despite Having The Correct File Path - Django [closed]
I'm trying to import a spreadsheet into my views.py file to extract the data from it. However, when doing this, despite having the file path, either from the file in which the view code is in or the absolute file path, I keep getting the error. Can anybody explain this as I can't. Also I'm very new to django and don't know what I'm doing with it too well, so if there's anything else that's needed to be seen, let me know. The file path from views.py to routes.xlsx The code I'm using to try import the spreadsheet class Door1ToPlatform3(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format = None): wb = load_workbook('excel/routes.xlsx') ws = wb.active ws = wb[journeys[0]] -
Combining django, sql and a rest api for a backend project
Where I work we produce bed boxes and the way orders are entered into the software the company use is a pretty lengthy process. I decided to build a web application that automatizes it. I decided to build it with python in Django since python is the language I am most familiar with. I have a rough plan in my head as to how to do it. I would really appreciate any insight or direction you can provide or simply new keywords to google. The situation is something like this: 1-Customer may upload(as csv files) orders or manually select order items from a drop-down menu on the webpage. The order text they will input into the webpage can be broken down into its constituents that identify different specs of the bed(Set abcd 100x200 (lorem ipsum) HBxy STab). The unique number of spec identifiers range between 3 to 8. I believe if I want to let the customer choose from a drop-down menu I need a DB to populate that dropdown. However if they upload it as a CSV file, then I just need a DB for storing the CSV input 2-Most of the time the way customer inputs an order … -
Socket io + django rest framework + Vue
I am developing a web application with drf in backend and vue in frontend. I need to add Chat functionality. For that socket io is great solution. But i can not find any tutorials or documentation to do that. Please help me. -
How to fetch data from api and display all fields data in your Django projects
i have some problam in the url_field. how to fetch url data and display the full content of the urlenter image description here -
Django how to implement auto logout and auto login together?
I am working on a project in Django. Everything works well. But I am having some clash in the implementation of Automatic logout after a certain duration of inactivity and Automatic login functionality if a user closes tab without logging out and reopens tab. Problem 1- Need Automatic Logout functionality after 1 hour of inactivity. Implemented and works. 2- Need Automatic Login Functionality. Meaning if a user hasn't logged out and closes tab, and tries to reach the /login url, he must be taken to dashboard as he never logged out. Implemented and works. Both these functionalities work but not when they are implemented together. What has been implemented? 1- For Logout: SESSION_COOKIE_AGE = 60*60 SESSION_SAVE_EVERY_REQUEST = True Implemented in settings.py. 2- For Login: In my login view function in POST case I have implemented cookies. I am setting cookies for username using response.set_cookie('username', username) Then in GET I am checking if the cookie of 'username' is set or not. If it is set I take user to dashboard. Else I take him to login page. 3- In /logout view I am deleting cookie of 'username' as: response.delete_cookie('username') The Problem arising is that if the time of 1 hour is … -
How to pass data from html template (using html form) to views.py python in django?
I am trying to get input from a html form to python views.py file in django. Below is my html and python code: <form action="getsummary" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="exampleFormControlTextarea1">Paste your text here</label> <textarea class="form-control" name="inputText" id="exampleFormControlTextarea1" rows="10" style="width:1000px; "></textarea> </div> </form> <div class="d-flex justify-content-center"> <div class="border d-flex justify-content-center" style="width:160px"> <a href="getsummary"> <button type="submit" class="btn btn-primary">Summarize Now</button> </a> </div> </div> def getsummary(request): if request.method == "POST": title = request.POST.get('inputText') print(title) return render(request, 'get-summary.html' ) I gave input text in my html form. My terminal was supposed to print that text but instead its printing Nothing. [15/Feb/2022 12:20:33] "GET /summary HTTP/1.1" 200 2514 [15/Feb/2022 12:20:36] "GET /getsummary HTTP/1.1" 200 1961 I also tried doing it with GET method. In that case, it is printing None. Kindly help me with this. Same issue I am facing when I am using ajax to pass javascript variable to views.py python file. Thank you. -
Adding a Spreadsheet Attachment in Django and Generating Monthly reports
I am trying a timesheet project. I am using Django rest-framework and using Postgres as my database. My client requested me that he need a spreadsheet functionality like a particular admin must have monthly spreadsheet reports of his employees every month and that process should be automated. As I am new to Django, Kindly guide me through this process **utitles.py** import threading from django.core import mail class EmailThread(threading.Thread): def __init__(self, subject, plain_message, from_email, to_email): self.subject = subject self.plain_message = plain_message self.from_email = from_email self.to_email = to_email super(EmailThread, self).__init__() def run(self): mail_send = mail.send_mail(self.subject, self.plain_message, self.from_email [self.to_email]) print('mail send successfully ', mail_send) **serializers.py** class UserSerializers(serializers.ModelSerializer): def create(self, validate_data): subject = 'Your account was activated' plain_message = 'SAMPLE TEXT' from_email = 'demomaster147@gmail.com' to_email = validate_data['email'] attach_files = ['Client-2022-02-04.xls'] EmailThread(subject, plain_message, from_email, to_email,attach_files).start() return Users.objects.create(**validate_data) **settings.py** EMAIL_HOST = 'smtp.gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_PORT = 587 EMAIL_HOST_USER = 'demoma@gmail.com' EMAIL_HOST_PASSWORD = '**********' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER