Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to delete the reference object that will not delete the referred object in Django?
Here I've two models. one is Contact and another one is Sent_replies. If client wants to contact with admin his information will be stored in Contact model. So here I want that if admin replies to that client, that specific information will be deleted from Contact model without deleting the record which is in Sent_replies. How can I do that. models.py class Contact(models.Model): message_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) comment = models.TextField(max_length=100) subject = models.TextField(max_length=100) reply = models.TextField(max_length=500); date = models.DateField() def __str__(self): return self.name class Sent_replies(models.Model): message = models.ForeignKey(Contact,on_delete=models.CASCADE, null=True) subject = models.TextField(max_length=100) reply = models.TextField(max_length=500) def __str__(self): return self.message.name -
populate price section by selecting product in django formset
I have a Django formset with 6 input field. Whenever a user select a product for every row it will auto populate 3 fields named dp_price, tp_price and mrp. I have tried some but failed to do it by myself. my formset looks like this and my tried js file is add_purchase.js var send_data = {} for(var i=0; i<10; i++){ $(document).ready(function (prefix) { $('#id_form-' +prefix+ '-product').on('change', function () { console.log("On Product selected") let id = $(this).children('option:selected').val(); console.log(id); $.ajax({ url: 'product-info', data: { 'pk': id }, dataType: 'json', success: function (data) { console.log(data); $("#id_form-"+prefix+"-dp_price").val(data.dp_price); $("#id_form-"+prefix+"-tp_price").val(data.tp_price); $("#id_form-"+prefix+"-mrp").val(data.mrp_price); } }); })(i); }); } forms.py PurchaseChildFormset = modelformset_factory( PurchaseChild, form=PurchaseChildFormCreateForm, extra=1, widgets={ 'product': forms.Select(attrs={'class': 'form-control', }), 'dp_price': forms.NumberInput(attrs={'class': 'form-control', }), 'tp_price': forms.NumberInput(attrs={'class': 'form-control', }), 'mrp': forms.NumberInput(attrs={'class': 'form-control', }), 'qty': forms.NumberInput(attrs={'class': 'form-control'}), 'line_total': forms.NumberInput(attrs={'class': 'form-control'}), }, ) -
How to add extra field other than user in django group
I have one application where users(admin) can create groups and add users. But the admin wants to share some credits with group members. For example, Admin has purchased 100 credits. Out of 100 credits, he can give any number of credits to any user who belongs to that group. -
Can't encode cyrillic characters xhmt2pdf in django
# libraries from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa from django.utils.encoding import smart_str # defining the function to convert an HTML file to a PDF file def html_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None In HTML I have some Russian words. When I tried to encode these characters, in my pdf, I have bunch of unclear charactets appeared. I have tried to change coding format to "UTF-8", "UTF-16" but it did not help. -
Use <select> tag in django template to pass data to a view
I'm new to Django and I'm learning forms, templates, and views building a simple web app. I currently have a view that generates data as below and passes them to the template using the context dictionary. This data are taken by the template and coordinated with a <select> tag views.py my_dictionary = {0: {'title': 'Beyond the Soul', 'id': '2Uy66My5oKcBEIW7DvVk3V'}, 1: {'title': 'The Groove Cartel Selection', 'id': '1pHtICGI68RmWEKnnP5wGr'}, 2: {'title': 'STMPD RCRDS TOP 50', 'id': '1OIzwJTbrOeZTHvUXf5yMg'}, 3: {'title': 'House Party by Axwell', 'id': '1tl4L77FJju5zp9bJC83u8'}} return render(request, 'show_playlist.html', {"my_dictionary": my_dictionary}) template <select class="form-select" aria-label="Default select example"> <option selected>Choose the element</option> {% for key, value in my_dictionary.items %} <option value="{{value.id}}">{{value.title}}</option> {% endfor %} </select> Obviously, the select form does nothing. I was wondering what was the best way to, after having selected an item, redirect to a new template/view passing the actual selection (so {{value.id}} and {{value.title}}). Do I need to use a Django form or can I use some sort of redirect on the select like <a href="{% url 'redirect_url' %}">? -
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 …