Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Automatically calculating a ModelForm field on users click
I currently have a section in my form that looks like this: With this form , I need to calculate Provisional Tax Date 1 and Provisional Tax Date 2 based on the Financial Year End Field ( Provisional Tax Date 1 must be 6 months after Financial Year End & Provisional Tax date 2 needs to be on the 31st of December on the year of the Financial Year End) I would also need this to happen live, so as soon as the user changes the Financial Year End field it will update the other 2 If anyone has some sample code to assist with this, it would be highly appreciated. Please see the below code from my project: Views.py: def newCompany(request): form = CompanyForm() if request.method == 'POST': form = CompanyForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: print(form.errors) content = {'form':form} return render(request, 'main/newCompany.html', content) Models.py class CompanyClass(models.Model): CompanyName = models.CharField(max_length=50 , blank=False) RefNo = models.CharField(max_length=50 , blank=False ) FinancialYearEnd = models.DateField(auto_now=False, auto_now_add=False, null=False) ProvisionalTaxDate1 = models.DateField(auto_now=False, auto_now_add=False) ProvisionalTaxDate2 = models.DateField(auto_now=False, auto_now_add=False) ARMonth = models.DateField(auto_now=False, auto_now_add=False) checklist=models.ManyToManyField(Task) def __str__(self): return ( self.CompanyName) Forms.py class CompanyForm(ModelForm): class Meta: model = CompanyClass fields = '__all__' widgets = { 'FinancialYearEnd' : forms.SelectDateWidget, … -
Django receives multiple posts from the browser, Does the browser cache POSTs?
During developement it happens like this: if I am working on a piece of code to receive a POST request; Django will serve up an error page because the code is buggy. Then I fix a syntax error, refresh, a different error, fix that, repeat the process say 8 times. But on the 8th time the code works, and then Django receives and stores 8 Post entries, not just the last one! A similar behavior happens in production very occasionally. I am not sure if it is the browser caching the POSTs, then sending them all through at the same time or Django? I wrote javascript code to disable the submit button once clicked. I also check for duplicate entries (within a 5 seconds window) before saving, but it only works if one manually submits twice in quick succession, not if it auto sends a bunch of POSTs at the same time. These both are "hacks" that don't address the root cause. Any clue on how to debug or ways to attempt to solve/debug the issue? -
NameError at/ name 'Product' is not defined
I've been working on this ecommerce website and its been working perfectly but today when I ran the server it's showed me " NameError at/ name 'Product' is not defined" I've looked Into the code several times and didn't spot any error Models.py Class Product(models.Model): "" "" def __str__(self) self.name Views.py From .models import * def ShowProducts(request): items= Product.objects.all() context = {'items':items} return render(request, 'home.html', context=context) urls.py from . import views urlspatterns=[ Path ('', views.ShowProducts, name ='showproducts') ] My greatest surprise is , when I change the line, 'item= Product.objects.all()' to 'items= ()' in views.py,. It deplays the website correctly although without any product in it, please what should I do -
Joinging Query Django
class PopSummary(models.Model): available_pop = models.PositiveIntegerField(default=0) email = models.EmailField( verbose_name="email address", max_length=255, unique=True, default='' ) requested_pop = models.PositiveIntegerField(default=0) approved_pop = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) approve = models.BooleanField(default=False) popuser = models.ForeignKey(RequestPop, on_delete=models.CASCADE,related_name='popuser',null=True) def __str__(self): return "{}-{}".format(self.email,self.available_pop) Another Table: class RequestPop(models.Model): request_pop = models.PositiveIntegerField(default=0) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE,unique=False,null=True) created_at = models.DateTimeField(auto_now_add=True) available_pop = models.PositiveIntegerField(default=0) def __str__(self): return "{}-{}".format(self.user,self.request_pop) I want to make the query in inner join or other way so that: select all from RequestPop where PopSummary.approve=True I run the follwing query. queryset = RequestPop.objects.filter(popuser__approve=True).all() but it seems to be incorrect. So what should be the solution for it please. -
How to undo a path command in cmd
I am learning django and was trying to run a webapp but I mistakenly pasted "path('admin/', admin.sites.urls)" (without double quotes) and it ran automatically. Now none of the python commands are working, and I can't come out of my virtual environment. How can I revert this? Here is the command -
Django view exception logs with INFO level, not ERROR
views.py def error(request): logger.error('logger.error - test error') raise Exception('raise Exception - test error') 1st logging settings: # 1 LOGGING = { 'version': 1, 'disable_existing_loggers': False, # True in dictConfig default 'formatters': { 'syslog': { 'format': 'django %(levelname)s %(name)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { 'syslog': { 'class': 'logging.handlers.SysLogHandler', 'formatter': 'syslog', 'facility': 'local1', 'address': '/dev/log' }, }, 'loggers': { 'django': { 'handlers': ['syslog'], 'level': 'ERROR', 'propagate': True, }, '': { 'handlers': ['syslog'], 'level': 'ERROR' }, }, 'root': { 'handlers': ['syslog'], 'level': 'ERROR' } } 1st logs (2 files in django dir) sudo tail /var/log/my_proj/django/syslog.info <*NO log!> sudo tail /var/log/my_proj/django/syslog.error 2022-02-15T09:49:43.019832+05:00 my_proj-stage-main1 django ERROR apps.demo.views 180029 140050762920576 logger.error - test error 2nd logging settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, # True in dictConfig default 'formatters': { 'syslog': { 'format': 'django %(levelname)s %(name)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { 'syslog': { 'level': 'INFO', 'class': 'logging.handlers.SysLogHandler', 'formatter': 'syslog', 'facility': 'local1', 'address': '/dev/log' }, }, 'loggers': { 'django': { 'handlers': ['syslog'], 'level': 'INFO', 'propagate': True, }, '': { 'handlers': ['syslog'], 'level': 'INFO' }, }, 'root': { 'handlers': ['syslog'], 'level': 'INFO' } } 2nd log (2 files in django dir) sudo tail /var/log/my_proj/django/syslog.info 2022-02-15T10:00:37.377018+05:00 my_proj-stage-main1 django INFO django.request 185769 140536088752768 OK: /ru/demo/error#012Traceback … -
list indices must be integers or slices, not dict in django
I just want to iterate through the list of JSON data which I get in the payload but getting an error as list indices must be integers or slices, not dict payload: [{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":150,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"},{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":151,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"}] views.py: @api_view(['POST']) def SaveUserResponse(request): for ran in request.data: auditorid = request.data[ran].get('AuditorId') ticketid = request.data[ran].get('TicketId') qid = request.data[ran].get('QId') answer = request.data[ran].get('Answer') sid = '0' TicketType = request.data[ran].get('TicketType') TypeSelected = request.data[ran].get('TypeSelected') agents = request.data[ran].get('Agents') supervisor = request.data[ran].get('Supervisor') Comments = request.data[ran].get('Comments') action = request.data[ran].get('Action') subfunction = request.data[ran].get('AuditSubFunction') region = request.data[ran].get('AuditRegion') cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s,@TicketType=%s,@TypeSelected=%s,@agents=%s, @supervisor =%s, @Comments=%s, @action=%s, @subfunction=%s, @region=%s', (auditorid,ticketid,qid,answer, sid,TicketType, TypeSelected, agents, supervisor, Comments, action, subfunction,region)) return Response(True) -
Is it possible to use complex logic in DRF ViewSet Permission Classes?
In the app I'm working on, I'd like it so that to create a task for a committee, you must be a member of the committee, the head of the committee, or an admin user, but you must also be authenticated. I understand this can be done with a few OR operators, but in the case that I need something more complex, I was hoping I could use nested lists of permission classes as such: permission_classes = [ IsAuthenticated & [ IsCommitteeHead | IsCommitteeMember | IsAdminUser ] ] Will this syntax work properly, or does rest_framework not understand this?