Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I fix "ValueError: time data '\nJuly 4, 2022\n' does not match format '%B %d, %Y'"?
While scrapping a site for data i got that error. Some of the dates are in mm d, yyyy format while others are in mm dd,yyyy. I've read the documentation and tried different solutions on stackoverflow but nothing seems to work. import requests from datetime import datetime def jobScan(link): the_job = {} jobUrl = link['href'] the_job['urlLink'] = jobUrl jobs = requests.get(jobUrl, headers = headers ) jobC = jobs.content jobSoup = BeautifulSoup(jobC, "lxml") table = soup.find_all("a", attrs = {"class": "job-details-link"}) postDate = jobSoup.find_all("span", {"class": "job-date__posted"})[0] postDate = postDate.text date_posted = datetime.strptime(postDate, '%B %d, %Y') the_job['date_posted'] = date_posted closeDate = jobSoup.find_all("span", {"class": "job-date__closing"})[0] closeDate = closeDate.text closing_date = datetime.strptime(closeDate, '%B %d, %Y') the_job['closing_date'] = closing_date return the_job however i get this error ValueError: time data '\nJuly 4, 2022\n' does not match format '%B %d, %Y' and when i try the other format i get this ValueError: '-' is a bad directive in format '%B %-d, %Y' What could I probably be doing wrong? -
Is there any way to have my html page refresh/reload itself after a function in the django view.py tab completes?
I want to have my page refresh itself after a successful download of a zip file since successive attempts to click the submit button result in an error, and the only way to remedy it fairly easily is to manually refresh/reload the page. I was wondering if there is a way to set it up so that once the zip is completed the page will refresh itself without the user having to worry about it. Doing it this way also kills two birds with one stone, since I want to disable the submit button to prevent users from spamming it, but if I end up having the page refresh I could just out right remove it after it's clicked. Here is my HTML code: {% load static %} <html> <head> <link rel="stylesheet" href="{% static '/styleSheet.css' %}"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edstore"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--BOOTSTRAP ASSETS--> <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@400;700&display=swap" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} <div class="main_Body"> <div class="section"> <h1>Fileconverter</h1> <br> <label for="file_field" class="custom-file-upload"> <i class="fa fa-cloud-upload"></i>Updload File(s)</label> <input type="FILE" id="file_field" name="file_field" class="file-upload_button" multiple> <label id="file_name"></label> <br> <br><br><br> <br> <button type="submit" class="file-submit__button" onclick="formDisableButton()" id="submitButton">Testing</button> <!--onclick="formDisableButton"--> </div> </form> </body> <footer> <p>Click "Choose File(s)" and select … -
For loop inside a IF condition to show right category on django template
i'm trying to show the correct articles in the category section using a if condition with a for loop inside, so far i'm displaying all the categories and not the only ones that suposed to be in the certain place. here my template: {% if articles.category == Sports %} {% for article in articles %} <div class="position-relative"> <img class="img-fluid w-100" src="{{article.cover.url}}" style="object-fit: cover;"> <div class="overlay position-relative bg-light"> <div class="mb-2" style="font-size: 13px;"> <a href="">{{article.title}}</a> <span class="px-1">/</span> <span>{{article.created_at}}</span> </div> <a class="h4 m-0" href="">{{article.description}}</a> </div> </div> {% endfor %} {% endif %} and here my views.py: def home (request): cats = Category.objects.all() articles = Article.objects.filter( is_published=True).order_by('-category') return render (request,'pages/home.html', context={ 'cats': cats, 'articles': articles }) -
jwt token expiring every 5 minunts in django SIMPLE_JWT
I have added expire functionality in SIMPLE_JWT on login but every 5 minutes token is expiring this is my code. added I want to expire token in 7 days. Can you see and tell me what is the issue in my code. Thanks PyJWT==2.4.0 class LoginAPIView(APIView): def post(self, request): email = request.data.get('username') password = request.data.get('password') user = Users.objects.filter(email=email).first() if user is None: db_logger.error('User not found!') raise AuthenticationFailed('User not found!') if not user.check_password(password): db_logger.error('Invalid password!') raise AuthenticationFailed('Invalid password!') if user.is_verified: payload = { "id": user.id, "email": user.email, "exp": datetime.datetime.now(tz=timezone.utc) + datetime.timedelta(minutes=1440), "iat": datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() user = db.table('users').where('email', email).first() response.data = { "token": token, "data": { "user": user, "is_admin": True if user.role == 'admin' else False, }, "message": "Logged in successfully!" } db_logger.info('Logged in successfully!') #if password correct return response else: db_logger.error('Your account is not activated!!') return Response({'message': 'Your account is not activated!!'}, status=status.HTTP_400_BAD_REQUEST) -
Deploying a Django app on azure - No module named django
I am trying to deploy a django web app on azure but I am having no success with it! I have tried different methods for deployment (VSCode, Zip file, github..)and have followed different Qs on StackOverflow and other forums but in vain. Now I am trying to deploy using a zip file and getting the following error in logs: 2022-07-07T17:48:18.453487609Z Traceback (most recent call last): 2022-07-07T17:48:18.453492410Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-07-07T17:48:18.453496310Z worker.init_process() 2022-07-07T17:48:18.453515311Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-07-07T17:48:18.453519511Z self.load_wsgi() 2022-07-07T17:48:18.453522711Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-07-07T17:48:18.453526111Z self.wsgi = self.app.wsgi() 2022-07-07T17:48:18.453529411Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-07-07T17:48:18.453532912Z self.callable = self.load() 2022-07-07T17:48:18.453536112Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-07-07T17:48:18.453539512Z return self.load_wsgiapp() 2022-07-07T17:48:18.453542712Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-07-07T17:48:18.453546112Z return util.import_app(self.app_uri) 2022-07-07T17:48:18.453549312Z File "/opt/python/3.9.7/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2022-07-07T17:48:18.453552813Z mod = importlib.import_module(module) 2022-07-07T17:48:18.453556013Z File "/opt/python/3.9.7/lib/python3.9/importlib/__init__.py", line 127, in import_module 2022-07-07T17:48:18.453559413Z return _bootstrap._gcd_import(name[level:], package, level) 2022-07-07T17:48:18.453562713Z File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2022-07-07T17:48:18.453566713Z File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2022-07-07T17:48:18.453570113Z File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2022-07-07T17:48:18.453573514Z File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2022-07-07T17:48:18.453576814Z File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2022-07-07T17:48:18.453580214Z File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2022-07-07T17:48:18.453583614Z File "/home/site/wwwroot/CricketWebsite/wsgi.py", line … -
Send list of filtered users to redis instance when function is triggered in frontend
Trying to create a function that when triggered in the frontend, will get a list of all users who are currently logged in and create key value pairs for all these users in my redis cache. This is what I am currently trying. I have this function in my views: def postToRedis(request): online_users = User.objects.filter(is_online='true').order_by('-date_joined') queue_of_users = { d['username'] for d in online_users } keys = list(queue_of_users.keys()) values = list(queue_of_users.values()) for i in range(0, len(keys)): redis_instance.set(keys[i], values[i]) response = { 'msg': f"{keys} successfully set to {values}" } return Response(response, 201) My intention here is to get a list of all users, filter for users who are online, get a list of all keys and correspondent values, loop through these lists and write each pair as a key value pair in my redis instance. I then have an API end point for my frontend to interact with my backend and trigger this function to run path("/post", postToRedis, name="postToRedis"), However when I try to trigger this function I do not get any of the desired output written into my redis_instance. Would love to get help on this -
Django AppRegistryNotReady when running another multiprocessing.Process
Problem I needed to run multiple UDP servers on different ports that exchange data with a Django core, so I defined a Django command which calls a method (start_udp_core) that runs each UDP server in a separate process. I used socketserver.UDPServer and stored the needed data for the socket using a Django model called ServerData. The Django version is 4.0.5 So I came up with this code: from core.models import ServerData from .data_receiver import UPDRequestHandler def create_and_start_server(host, server_data): with UDPServer((host, server_data["port"]), UPDRequestHandler) as server: try: logger.info(f"server is listening ... {server.server_address}") server.serve_forever() except KeyboardInterrupt: print("... going off ...") except Exception as e: logger.error(str(e)) def start_udp_core(): all_servers = ServerData.objects.values() logger.info(f"servers data ... {all_servers}") db.connections.close_all() default_host = "0.0.0.0" for server_data in all_servers: multiprocessing.Process(target=create_and_start_server, args=(default_host, card_data)).start() After running the command using manage.py, AppRegistryNotReady: Apps aren't loaded yet is being raised: INFO - start_udp_core - servers data ... - <QuerySet [{'id': 1, 'type_id': 1, 'ip': '192.168.0.50', 'port': 5000}, {'id': 2, 'type_id': 1, 'ip': '192.168.0.51', 'port': 5001}]> Traceback (most recent call last): File "<string>", line 1, in <module> Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\...\python\python39\lib\multiprocessing\spawn.py", line 116, in spawn_main File "c:\...\python\python39\lib\multiprocessing\spawn.py", line 116, in spawn_main exitcode = _main(fd, parent_sentinel) File … -
DJANGO TO HEROKU ImportError win32 only
i'm a begginer and i've been trying to upload my first django project to heroku and all worked fine untill i tried to run the app in heroku. I get this win32 only error and I can't seem to find an answer. This is the error I get and I cant figure it out. If you need any further info about the project so here is the git to it https://github.com/dngbr/Marut . Thank you Exception Type: ImportError Exception Value: win32 only Exception Location: /app/.heroku/python/lib/python3.10/asyncio/windows_events.py, line 6, in Python Executable: /app/.heroku/python/bin/python -
How can I set an attribute to use in both POST and GET methods in django class-based views?
So I'm building a class-based view that uses data from a table on my db, both on POST and GET methods. I've been trying to set an attribute with the table to mitigate the time that it would take to pull the table again for the sake of performance. Because of how functions/methods work I can't set an attribute like this: class MyClass (View): @md(login_required(login_url='login',redirect_field_name=None)) def get(self, request): con = create_engine('mysql+mysqlconnector://user:password@localhost:8000/schema') #function to get a dict with db tables tabs = get_tables(con) #Trying to make the attribute self.table = tabs['table_That_I_need'] context{'data':tabs} return render(request, 'markowitz/markowitz.html',context) @md(login_required(login_url='login',redirect_field_name=None)) def post(self, request): #this gives me an error since the attribute was not set table = self.table form = MarkowitzForm(request.POST,table) if form.is_valid(): pass return render(request, 'markowitz/results.html') I've been trying to use setattr but it doesn't seem to be working -
Why adding FilteredSelectMultiple widget to ModelMultipleChoiceField form field is not posting values selected?
I've been stuck around this issue for a while now and no existing post helped me solve it. I have a form with the following field declared in my forms.py: class SignRequestForm(forms.ModelForm): dental_codes = forms.ModelMultipleChoiceField( label='Select Proccedure Codes', queryset = CDTADACodes.objects.all() ) And this is processed in the views.py as it follows: class CreateInsuranceView(CreateView): def post(self, request, *args, **kwargs): #Declare and process patient_valid object if request.POST.get('eligibility_type') != 'Orthodontic': patient_valid.save() patient_valid.dental_codes.set\ (CDTADACodes.objects.filter\ (pk__in=request.POST.getlist('dental_codes'))) patient_valid.save() which works as expected. The problem is that when i want to add the FilteredSelectMultiple widget to dental_codes field the field is no longer posted in the form Here is the forms.py with the widget applied: class SignRequestForm(forms.ModelForm): class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) dental_codes = forms.ModelMultipleChoiceField( label='Select Proccedure Codes', queryset = CDTADACodes.objects.all(), widget = FilteredSelectMultiple('Dental Codes Selection', is_stacked=True) ) Finally this is the html template for the field INSIDE the <form>: <section> <div class="row justify-content-md-center"> <label>{{form.dental_codes.label}}</label> </div> <div class="row justify-content-md-center"> <div class="form-group" id="dental_codes"> {{form.media}} {{form.dental_codes.errors}} {{form.dental_codes}} </div> </div> </section> No errors are raised, it's just that in the request payload the field is no longer posted. Any help is more than welcomed, thanks in advance -
Can`t verify the email address with Django Rest and React
friend, I'm new and trying to figure it out. I have some problems with verification user via email. I have backend on 8000 port with Django rest framework and frontend on 3000 port with React. After registration I receive an email with link to submit email, like this: http://localhost:8000/activate/NDQ/b87jb3-6f86c3a304f606f584203f4d4e5ecfe8 If I click on this link, I receive an error Page not found (404). But if I change in address string Port on 3000: http://localhost:3000/activate/NDQ/b87jb3-6f86c3a304f606f584203f4d4e5ecfe8 verification submit and have no problem. What do I need to do to get verification through the link that comes in the letter, because there is port 8000, and the frontend has 3000 -
an exception on Route method of Router in python
I created a small road map application and used the Router class from pyrolib3 but when I call the method doRoute(location, destination) I have an error SAXParseException at /"unclose token" -
How to pass comma seperated query parameters to SerializerMethodField - Django Rest Framework
I'm trying to pass comma seperated query parameters to serializer and return SerializerMethodField value in JsonResponse views.py: class MyModelViewSet(ModelViewSet): serializer_class = serializers.MyModelSerializer def get_serializer_context(self): context = {'request': self.request} years = self.request.GET.get("years") if names: context['years'] = "years" return context serializers.py: class MyModelSerializer(ModelSerializer): age = serializers.SerializerMethodField() class Meta: model = models.MyModel fields = ["id","first_name","last_name"] get_age(self): years = years.split(',') qs = list(models.MyModel.objects.filter(year__in=years) /* here I should call function my_func() for each object and return value in json response which looks like this */ [ { "id" : 1, "first_name" : "John", "last_name" : "Doe", "age": 31 } ] but I have no idea how to implement this part of serializer. Any help will be appreciated, thank you in advance! -
Dynamically updating values of a field depending on the choice selected in another field in Django
I have two tables. Inventory and Invoice. InventoryModel: from django.db import models class Inventory(models.Model): product_number = models.IntegerField(primary_key=True) product = models.TextField(max_length=3000, default='', blank=True, null=True) title = models.CharField('Title', max_length=120, default='', blank=True, unique=True) amount = models.IntegerField('Unit Price', default=0, blank=True, null=True) def __str__(self): return self.title InvoiceModel: from django.db import models from inventory.models import Inventory class Invoice(models.Model): invoice_number = models.IntegerField(blank=True, primary_key=True) line_one = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='+', verbose_name="Line 1", blank=True, default='', null=True) line_one_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_one_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_one_total_price = models.IntegerField('Line Total(₹)', default=0, blank=True, null=True) line_two = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='+', verbose_name="Line 2", blank=True, default='', null=True) line_two_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_two_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_two_total_price = models.IntegerField('Line Total(₹)', default=0, blank=True, null=True) line_three = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='+', verbose_name="Line 3", blank=True, default='', null=True) line_three_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_three_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_three_total_price = models.IntegerField('Line Total(₹)', default=0, blank=True, null=True) line_four = models.ForeignKey(Inventory, on_delete=models.CASCADE,related_name='+', verbose_name="Line 4", blank=True, default='', null=True) line_four_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_four_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_four_total_price = models.IntegerField('Line Total(₹)', default=0, blank=True, null=True) line_five = models.ForeignKey(Inventory, on_delete=models.CASCADE, related_name='+', verbose_name="Line 5", blank=True, default='', null=True) line_five_quantity = models.IntegerField('Quantity', default=0, blank=True, null=True) line_five_unit_price = models.IntegerField('Unit Price(₹)', default=0, blank=True, null=True) line_five_total_price = … -
how to specify hourly time range in djagno?
I want to accept orders within specific timeframe, simply i want to validated orders if they are within 8:00-19:00 no matter what day it is or what date it is. -
How to pass django variable as parameter inside {% url %} tag?
Let's say I have a view function like this: def view(request): x = 5 y = 10 context = { 'x': x, 'y': y, } return render(request, 'index.html', context) and a result function like this: def result(request, number): square = int(number) * int(number) return HttpResponse(str(square)) I am passing context from the view function to the index.html template, which looks like this: <body> <h1>{{ str(x) }}</h1> <a href="{% url 'app:result' number=str(y) %}">Square it</a> </body> The template renders x successfully as a header, but I don't know how to pass y as the number parameter in the result view. -
What is the correct way to change html dynamically using django
Suppose we have a login page where, in the first stage, we are asked to enter our email. We send this information to the server, which searches whether there is an account with this email, and if there is, our goal is to change the state of the page, to a page where the user is asked to enter the password for this account. If, on the other hand, there is no account with that email, the state of the page changes to one where the user signs up. And let's say that, for the sake of aesthetics, all this happens using the same url. My question is, what is the correct way to inform the client's page to what stage to go into? Sending the whole html code is an option, but this seems like it will put too much pressure on the server. Is there a cleaner way, that we can send less information, and still be able to have the same result? I am new to django and web dev so please explain thoroughly. -
Object is not iterable in Django while returning objects to API
I'm using Django rest framework and Django to create a website showing events. I'm filtering my existing models in the database and outputting the new objects in a new API. So far I am returning all objects in the database while returning the filtered objects cases this error: TypeError: 'type' object is not iterable. In models.py Here you're seeing that I don't actually filter by date. Instead, I'm testing the code by filtering on status. from django.db import models class EventQuerySet(models.QuerySet): def today(self): return self.filter(status="Publish") class EventManager(models.Manager): def get_queryset(self): return EventQuerySet(self.model, using=self._db) def today(self): return self.get_queryset().today() class Event(models.Model): CATEGORY = ( ('Smiles', 'Smiles'), ('Laughter', 'Laughter'), ('Crazy', 'Crazy'), ('Food', 'Food'), ('Outside', 'Outside'), ) STATUS = ( ('Publish', 'Publish'), ('Draft', 'Draft'), ) title = models.CharField(max_length=200, blank=False) status = models.CharField(max_length=200, null=True, choices=STATUS) startDate = models.DateField(blank=True) endDate = models.DateField(blank=True) link = models.CharField(max_length=200, blank=False) category = models.CharField(max_length=200, null=True, blank=True, choices=CATEGORY) objects = models.Manager() date = EventManager() class Meta: unique_together = ('title', 'link') def __str__(self): return self.title Using python manage.py shell to test the query works and outputs the correct objects. Here is an example of some of the data that I'm getting: <EventQuerySet [<Event: Positivus Festival 2022>, Central European zone stage in equestrian show jumping … -
Django REST framework - additional field in JsonResponse
I've APIView, which should return model's field and one additional field - the value of which is returned by function. class MyView(APIView): def get(self,request): qs = list(MyModel.objects.values('name','last_name')) for q in qs: q['age'] = get_age(1980) return JsonResponse({'results': qs}) What is the better way to return combined - model fields and additional field in response? -
ProgrammingError at column "" does not exist
I added a custom extension to djangos User model and now I'm getting this error: return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column users_account.birthday does not exist LINE 1: ... "users_account"."id", "users_account"."user_id", "users_acc... ^ It only appears when I try to either edit an existing User or create a new one. models.py: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday = models.DateTimeField(blank=True, null=True) def __str__(self): return self.user admin.py: class AccountInline(admin.StackedInline): model = Account can_delete = False verbose_name_plural = 'Accounts' class CustomUserAdmin(UserAdmin): inlines = (AccountInline,) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) My original guess was the error was due to the fact that my existing Users have no birthday but that doesn't explain why I can't create a new User. Which makes me think I am unaware of what the actual problem is. I'm newish to django/SQl so I don't really understand the error itself. Any help what be greatly appreciated. -
Getting error when trying to log into admin page using django
I am trying to log into the admin page on django. I have a superuser account but when I try to login I get this error: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'django_session'. -
Джанго форма "Выбор" [closed]
Я хочу сделать форму select с выбором страны, но не знаю, как засунуть options в select средствами django. В документациях искал, но в основном была не та информация или было не понятно, по итогу я не нашел. Я хочу сделать форму select с выбором страны, но не знаю, как засунуть options в select средствами django. В документациях искал, но в основном была не та информация или было не понятно, по итогу я не нашел Нужно, чтобы в пуcтом месте были options Код страницы: <html> <head> <meta charset="UTF-8"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- 0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> </head> <body> <div class="col-md-7 col-lg-8 container"> <h4 class="mb-4 mt-4" style="text-align: center">Заполните форму</h4> <form class="needs-validation m-auto" novalidate="" method="post"> {% csrf_token %} <div class="row g-3"> <div class="col-sm-6"> <label for="country" class="form-label">Страна</label> {{ form.country }} </select> <div class="invalid-feedback"> Please select a valid country. </div> </div> <div class="col-sm-6"> <label for="lastName" class="form-label">Место</label> {{ form.title }} <div class="invalid-feedback"> Valid place is required. </div> </div> <div class="col-12"> <label class="form-label">Описание <span class="text-muted">(Optional)</span></label> {{ form.task }} <div class="invalid-feedback"> Please enter a valid email address for shipping updates. </div> </div> <hr class="my-4"> <button class="w-100 btn btn-primary btn-lg container" type="submit" >Continue to checkout</button> </form> </div> Код forms.py: from django import forms from django.forms import models, Textarea, TextInput, Select, SelectMultiple … -
Email not sending probably because of my service provider
I am searching if there is possibly a way to solve this problem. SMTPConnectError at /accounts/signup/ (421, b'Service not available') This error occurs when I use my home wifi during development, I know for the fact that it's the WiFi because connecting to another internet source solves this particular problem. Is there a work around this? Because I am in a situation where the only internet connectivity I have is this router and this happens with django/python development. -
How do I serve media files in Django DRF testing using APILiveServerTestCase?
I have some Django DRF tests that look like this: from django.conf import settings from rest_framework.test import APILiveServerTestCase, RequestsClient class APITests(APILiveServerTestCase): def setUp(self): self.client = RequestsClient() def test_endpoints(self): with self.settings(MEDIA_ROOT=f"{settings.BASE_DIR}/test_media/"): # Upload file self.client.post( URL, files={"my_file": ("filename", b"abc")}, ) # Download the file we just uploaded response = self.client.get( URL_to_FILE, ) The upload works fine, but the download fails with a 404, because the test webserver isn't serving media files, and more specifically, not serving them from my custom MEDIA_ROOT=f{settings.BASE_DIR}/test_media/ folder. Adding entries to urls.py to have Django serve media files didn't work. Django appears to have a TestCase subclass specifically designed for this: django.contrib.staticfiles.testing.StaticLiveServerTestCase. DRF doesn't have anything like this, but I figured I could make one like this: from django.contrib.staticfiles.testing import StaticLiveServerTestCase from rest_framework.test import APIClient class APIStaticLiveServerTestCase(StaticLiveServerTestCase): client_class = APIClient class APITests(APIStaticLiveServerTestCase): .... This didn't work either. Is there a way to make this work? -
unit testing for celery periodic task
I have a celery periodic task implemented to send email to users on certain date set on the model,How can i write the unit test for the following celery task. @app.task(bind=True) def send_email(self): send_date = timezone.now() records = Model.object.filter(due_date=send_date) for record in records: template_data = { 'homepage_url': settings.WWW_ROOT, 'domain_name': settings.DOMAIN_NAME, 'inq': record.inq, 'task_name': record.name, 'task_created': record.created, 'date': record.send_date, } user_emails = [] if record.send_email_to_users: **Boolean Flag on model** assignees_emails = [] for user in record.users.all(): user_emails.append(user.email) send_email_function( subject_template_path='', body_template_path='', template_data=template_data, to_email_list=user_emails, fail_silently=False, content_subtype='html' )