Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
data object in Bokeh
I'm trying to generating a Bokeh chart, I have this code: x = { 'Expired': dead_247, 'Unknown': unsure_247, 'Alive': alive_247 } data = pd.Series(x).reset_index(name='value').rename(columns={'index':'status'}) data['angle'] = data['value']/data['value'].sum() * 2*pi data['color'] = ["#c0c4c1", "#009695", "#53e305"] data["value"] = data['value'].astype(str) data["value"] = data["value"].str.pad(10, side = "left") sep = [] for i in range(len(data.index)): sep.append(': ') data['legend'] = data['status'] + sep + data['value'].astype(str) I print 'data' object by print(data) and see this output. Please tell me what type of data structure the 'data' is. Is it a List, or dictionary. web_1 | status value angle color legend web_1 | 0 Expired 1422 1.553859 #c0c4c1 Expired: 1422 web_1 | 1 Unknown 3080 3.365602 #009695 Unknown: 3080 web_1 | 2 Alive 1248 1.363724 #53e305 Alive: 1248 Could you show me how to add 1 more line into data['legend'] : Total = 5750 . (This is the sum of 1422 + 3080 +1248) Thank you. -
Unable to get data of Foreign key tables in same serilizor
Order table class Orders(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, blank=True, null=True) tableid=models.IntegerField() orderid=models.IntegerField() total_amount = models.DecimalField(max_digits=10, decimal_places=2) Articles table to save articles like pizza class OrderArticle(models.Model): order = models.ForeignKey(Orders, on_delete=models.CASCADE) article = models.ForeignKey(Articles, on_delete=models.CASCADE) # article_options = models.ManyToManyField(ArticlesOptions) Article options to save extra topping or any option available class OrderArticleOptions(models.Model): # order = models.ForeignKey(Orders, on_delete=models.CASCADE) article_option = models.ForeignKey(ArticlesOptions, on_delete=models.CASCADE) order_article = models.ForeignKey(OrderArticle, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) price = models.DecimalField(max_digits=10, decimal_places=2) So Now issue is When I try to get all data in one serialize I am not able to get . I am using this example to get https://www.django-rest-framework.org/api-guide/relations/ -
Celery-Progress - progress_recorder.set_progress() returns TypeError: sequence item 1: expected a bytes-like object, NoneType found
I'm inside a Django Project trying to use Celery-Progress to create a progress bar. But when I try to use progress_recorder.set_progress method inside the following function (using a celery worker): def increase_task_progress(): global progress_recorder_current, progress_recorder_total, progress_recorder progress_recorder_current += 1 progress_recorder.set_progress(progress_recorder_current, progress_recorder_total) <<< It's giving the following exception: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/projects/report/excel.py", line 193, in generate_data_sheets increase_task_progress() File "/projects/report/excel.py", line 199, in increase_task_progress progress_recorder.set_progress(progress_recorder_current, progress_recorder_total) File "/projects/report/my_venv/lib/python3.7/site-packages/celery_progress/backend.py", line 38, in set_progress 'percent': percent, File "/projects/report/my_venv/lib/python3.7/site-packages/celery/app/task.py", line 930, in update_state self.backend.store_result(task_id, meta, state, **kwargs) File "/projects/report/my_venv/lib/python3.7/site-packages/celery/backends/base.py", line 342, in store_result request=request, **kwargs) File "/projects/report/my_venv/lib/python3.7/site-packages/celery/backends/base.py", line 714, in _store_result self.set(self.get_key_for_task(task_id), self.encode(meta)) File "/projects/report/my_venv/lib/python3.7/site-packages/celery/backends/base.py", line 590, in get_key_for_task self.task_keyprefix, key_t(task_id), key_t(key), TypeError: sequence item 1: expected a bytes-like object, NoneType found These are my codes until reaching the increase_task_progress function. views.py from django.http import HttpResponse from . import tasts def myView(request): report_id = request.POST.get('report_id', 0) result = tasks.generate_report.delay(report_id) response = HttpResponse(content=task.task_id) return response tasks.py from . import excel from celery import shared_task @shared_task(bind=True) def generate_report(self, report_id): task = excel.generate_xls_report( report_id=report_id task_obj=self ) return task excel.py from celery_progress.backend import ProgressRecorder from xlsxwriter.workbook import Workbook from . import … -
[tag][Django] How to retrieve saved password in raw format
In one of my View i need UserName & Password details in raw format but Django uses PBKDF2 algorithm to store the password. I would like to know how to retrieve the saved password from Authentication Form. Using these Username and password details from my Django app , i need to use the same credentials to access another website to perform web automation on it using selenium chrome webdriver. Please let us know how to get the password in raw format once user authenticated using below LoginForm and login_view. forms.py: class LoginForm(AuthenticationForm): remember_me = forms.BooleanField(required=True, initial=False) def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_action = '.' self.helper.layout = Layout( Field('username', placeholder="Enter Username", autofocus=""), Field('password', placeholder="Enter Password"), Field('remember_me'), Submit('sign_in', 'Log in', css_class="btn btn-lg btn-primary btn-block"), ) def apply_gsp_request_form(request, id=None): if id: action = 'edit' model = get_object_or_404(ApplyGSP, pk=id) else: action = 'submit' model = ApplyGSP() message = "" if request.method == 'POST': form = ApplyGSPForm(request.POST, instance=model) if form.is_valid(): form.save() username = request.user.username print("password:", request.user.password) # How to get password details ? If i get pwd here using request.user.password it is displaying in <SHAalgorithm>$<iterations>$<salt>$<hash> format. # but i need in raw(clear text format) applyselenium(username,password) def applyselenium(): My Views.py: views.py: … -
How to prevent Django from overriding admin URI to /admin instead of /api/admin/
Working on putting a Django API into Kubernetes. Any traffic being sent to / the ingress-nginx controller sends to the React FE. Any traffic being sent to /api is sent to the Django BE. This is the relevant part of ingress-serivce.yaml: - http: paths: - path: /?(.*) backend: serviceName: client-cluster-ip-service servicePort: 3000 - path: /api/?(.*) backend: serviceName: server-cluster-ip-service servicePort: 5000 This is the url.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('auth/', include('authentication.urls'), name='auth'), path('admin/', admin.site.urls, name='admin'), ] The client portion works just fine. The minikube IP is 192.168.99.105. Navigating to that IP loads the react front-end. Navigating to 192.168.99.105/api/auth/test/ brings me to a `"Hello World!" response. However, when I try to go to 192.168.99.105/api/admin. It automatically redirects me to /admin/login/?next=/admin/. Is there anyway to prevent this behavior? I've also just tried this: ingress-service.yaml - http: paths: - path: /?(.*) backend: serviceName: client-cluster-ip-service servicePort: 3000 - path: /api/?(.*) backend: serviceName: server-cluster-ip-service servicePort: 5000 - path: /admin/?(.*) backend: serviceName: server-cluster-ip-service servicePort: 5000 urls.py urlpatterns = [ path('auth/', include('authentication.urls'), name='auth'), path('/', admin.site.urls), ] Which just produces "Not Found". -
Django Timezone
I have a PostgreSql database with localtime UTC: client=# SHOW TIMEZONE; TimeZone ---------- UTC (1 register) And a table with the release date that shows me 12:15 hours, according to UTC: db=# SELECT datetime_register FROM appointment; datetime_register ------------------------ 2018-08-15 12:15:00+00 (1 registro) In the Django project, I have settings.py defined: TIME_ZONE = 'America/Sao_Paulo' When I check the date on the project, it is presented in the same way as in UTC: 12:15 and should show 09:15, which is the time in Sao Paulo, as defined in settings.py. What is left to do for the Django project to display the date as TIME_ZONE set in settings.py? -
Unable to debug or use pdb in Django: bdb.BdbQuit
I'm using Django (2, 2, 4, 'final', 0) within a docker, but I'm able to bash inside to open or execute whatever is required. But I can't debug. (How to debug in Django, the good way? states some methods, none work for me) Within my views.py I'm having various functions, for instance this here. def visGraph(request): showgraph = 'Graphen' selectDB = request.GET.get('selectDB', '') __import__("pdb").set_trace() title += " <i>"+showgraph+"</i> ("+selectDB+")" It works fine until I fill in the pdb, adding the debugger makes my app crash immediately: > /code/DjangoGraphen/views.py(74)visGraph() -> title += " <i>"+showgraph+"</i> ("+selectDB+")" (Pdb) Internal Server Error: /DjangoGraphen/visGraph Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "./DjangoGraphen/views.py", line 74, in visGraph title += " <i>"+showgraph+"</i> ("+selectDB+")" File "./DjangoGraphen/views.py", line 74, in visGraph title += " <i>"+showgraph+"</i> ("+selectDB+")" File "/usr/lib64/python3.7/bdb.py", line 88, in trace_dispatch return self.dispatch_line(frame) File "/usr/lib64/python3.7/bdb.py", line 113, in dispatch_line if self.quitting: raise BdbQuit bdb.BdbQuit ERROR:django.request:Internal Server Error: /DjangoGraphen/visGraph Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response … -
How to allow '%' to pass in IIS
I have a web app developed using DJANGO. Everything works well on the DJNAGO testing server. However, I tried to host it on IIS web server and it works only one problem I am having. I have one form (user input) and I want to allow the users to input wildcard such as SCA80%. The problem is that I get 404 error and it seems that IIS blocks it because the URL contains % sign. How can I make IIS don't check for the % regardless of the security issue concerns? Is there any simple solution to fix it? That's how the URL looks like when I send my request with a wildcard: /pareto/article-description/SAC80%25/?type=failure&is_article_desc=True If I remove the %25 and I put the entire SAC80RKEU211 everything works. Even if I am on the django developing server the %25 works. But not on IIS. -
Django Performance why is there a huge time gap between the total time and SQL time
So, I have a big issue with how long it takes to load my page on the development server. Believe it or not, for one of the pages on the site, it currently takes about a minute to load according to Django's debug toolbar while the toolbar shows SQL time of roughly 1 second (still too long). So, why is there such a gap. I tried loading on other pages that loads the same overhead, e.g. static files like js, fonts, pictures, etc. and they are no where close (around 2-3 seconds). I am using a DetailView and adding some related data to the request using get_context_data. So, I have timed each method call. Here are some more detailed numbers on performance: The get request took: 9.8e-06 The get request took: 9.200000000000007e-06 The get_object call took: 0.0642546 The get_object call took: 0.0660097 The get_object call took: 0.0505043 The get_object call took: 0.048121899999999995 The entire get_context_data took: 1.6127981 The entire get_context_data took: 1.6103409999999998 Notice that each is called twice with the exception of get_object which was called four times! Comparing page to page, I cannot figure out why it takes so long for this page to load vs another page with … -
Django not syncing with sqlite3 (official polls tutorial)
So I'm following the official tutorial (creating a polls app) for django and I'm having db issues. For some reason I didn't have sqlite3 included with python (not a big issue, I just installed it). After installation, I have a connection in settings.py like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I ran python migrate.py migrate. The next step was to run sqlite3 and do this: .schema Nothing shows up, because no DB exists. I'm very confused as to what I may not be doing right (or what I have done to mess it up) to get a proper database connection for the app. -
Django ecommerce: does not count line total
Doing a homework, and wanted to ask, how to calculate line_total (meaning: product.price * quantity). Got no problems w/ grand_total, but cant get my head around this issue. Tried moving line_total from one model to another. Say if its in cart model - it will only calculate line total for a last item, obviously. class Cart(models.Model): grand_total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) class DestCart(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, blank=True, null=True) destination = models.ForeignKey(Destination, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) line_total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) views.py for item in cart.destcart_set.all(): line_total = float(actual_price) * item.quantity item.line_total = line_total grand_total += line_total cart.total = grand_total cart.save() {% for item in cart.destcart_set.all %} <p>Location: {{ item.destination }}</p> <p>Quantity: {{ item.quantity }}</p> <p>Price: {{ item.destination.price }}</p> <p>Line total: {{ item.line_total }}</p> <a href="{% url 'edit_cart' item.destination.id %}?qty=0">Remove</a> {% endfor %} So, as You gather the idea is to have separate column with line total values. Cheers for a help, guys. I know it must be simple, but got stuck for good. So thanks again! -
Is there a good example to learn add, edit and delete posts and comments to posts with AJAX?
I'm wondering is there a good example to learn add, edit and delete posts and comments to posts with AJAX ? I'm using django for server side code but it example doesn't need to be with django. Thanks! -
Is there any way to makemigration on a pre-existing docker database?
I have a pre-existing docker container with a postgres database that I'm connecting to my django app, but when I try to "makemigrations" and "migrate" it doens't affect the container. Any clue how I can do it? Any help will be greatly appreciated. Thanks -
Django JSONField Filtering with Complex JSON
I have the following model: class Websites(models.Model): website_name = models.CharField(max_length=255,null=False) website_json_data = JSONField(blank=True,null=True,default=dict) def __str__(self): return self.website_name json_data contains 2 keys : headers[LIST] and body[DICT] in following with lot of json objects json_data = {"api.google.com": {"headers": ["Accept-User", "Mozilla","etc"], "body": "<html><title>sagsdgsdgsdgsdg</body>"},"api.facebook.com":{"headers":["Content-Type","User-Agent"],"body":"<html><title>this is facebook</title>"} p = Websites.objects.create(website_name="google.com",website_json_data=json_data) p.save() How do I filter the results in such a case? Q1) How do I filter the results based on body contains in such case? EX: I would like to return the results if any of the json object body contains this is facebook -
DRF Foreignkey serialization
I can't save model with Foreignkey field. For example I have simple models: class User(AbstractUser): class Meta: pass email_validator = EmailValidator() username = models.CharField('Name', max_length=150, ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField('Email', blank=True, unique=True, validators=[email_validator], ) ... class Package(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='packages') description = models.CharField('Description', max_length=256, default='description') weight = models.CharField('weight', max_length=256, default='weight') ... View (the user is guaranteed to be in the request): @api_view(["POST"]) def test(request): data = request.data data['user'] = User.objects.get(id=request.user.id) serializer = PackageSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) else: return JsonResponse(serializer.errors) My serializers: class UserSerializer(ModelSerializer): class Meta: model = User fields = '__all__' class PackageSerializer(ModelSerializer): class Meta: model = Package fields = ( 'user', 'description', 'weight', 'dimensions', 'estimated_shipping_cost', 'deliver_to_date') def to_representation(self, instance): self.fields['user'] = UserSerializer(many=False, read_only=True) self.fields['where_from'] = LocationSerializer(many=False, read_only=True) self.fields['destination'] = LocationSerializer(many=False, read_only=True) return super().to_representation(instance) def create(self, validated_data): user = User.objects.get(validated_data.pop('user')) package = Package.objects.create(user=user, **validated_data) return package json in request: { "description": "Some package", "weight": "12", } So, I'have user in database, and want create package for him. But in overridden create in PackageSerializer, validated_data doesn't have user. Please explain what I'm doing wrong. Versions of django and drf: django==2.2.4 djangorestframework==3.10.2 -
Why dou you have this error: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied
i cant work with django when its coming sometimes is coming some times not. -
how to upload image in django CBV(class based Views)createviews
I have been working on creating a blog sharing application using django.Am trying to add an image field so that users will be able to upload images and view them as posts.But the image is not getting uploaded.Django is not even throwing any errors. The code is running fine but the image is not getting uploaded. i have tried adding "enctype" in the template,as well as making the necessary changes in urls.py. I have even specified the MEDIA_ROOT and MEDIA_URL in settings.py. if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have added this in my urls.py. My models.py from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='% (app_label)s_%(class)s_related') picture = models.ImageField(upload_to='images',default='default.png',null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('project-home') My Views.py class PostCreateView(SuccessMessageMixin,LoginRequiredMixin,CreateView): model = Post fields = ['title','content','picture'] success_message = 'Your submission is sucessful!' def form_valid(self,form): form.instance.author = self.request.user return super().form_valid(form) def get_success_message(self): return self.success_message the image is not getting uploaded.Thanks in advance! -
Calling second GET request for separate view in Django
I am trying to call the GET method in my show_page view when the GET method in the main_page view is called. With the code I am using now, I know the show_page GET method is being called because I tested it with a print statement. However, it is not creating the actual GET request so that the page refreshes. Thank you for any help you can provide! class show_page(LoginRequiredMixin, View): template = 'wait/show.html' @classmethod def get(cls, request): username = request.user.username customers = Customer.objects.filter(store_username=username).exclude(exited=True) return render(request, cls.template, {'customers' : customers}) class main_page(LoginRequiredMixin, View): template = 'wait/main.html' def get(self, request): username = request.user.username customers = Customer.objects.filter(store_username=username).exclude(exited=True) refresh = show_page.get(request) return render(request, self.template, {'customers' : customers}) -
Django - Saving object worked one time but now it doesnt
i want to save an object to db and it worked one time but now it doesnt, i suspect that is something to do with the Glossary Everything views.py @login_required def product_form_view(request): if request.method == 'POST': form = Product_Form(request.POST, request.FILES) if form.is_valid(): product_form = form.save() product_form.save() return redirect('product_management_view') else: form = Product_Form() return render(request, 'product-form.html', {'form': form}) models.py class Product (models.Model): sub_chapter = models.ForeignKey(Sub_Chapter, on_delete=models.CASCADE) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) glossary = models.ManyToManyField(Glossary, blank=True ) name = models.CharField(max_length=40, blank=False, null=False) description = models.TextField(null=True) product_image = models.ImageField( upload_to='media/images/product_images', blank=False, null=False) reference = models.CharField(max_length=40, blank=False, null=False) width = models.PositiveIntegerField() height = models.PositiveIntegerField() length = models.PositiveIntegerField() unit_price = models.DecimalField( max_digits=15, decimal_places=4, null=True) polution = models.DecimalField(decimal_places=8, max_digits=15, null=True, blank=True ) technical_implementation = models.TextField(null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse_lazy("manufacter_product_view", kwargs={'id': self.pk}) forms.py class Product_Form(forms.ModelForm): sub_chapter = forms.ModelChoiceField(queryset=Sub_Chapter.objects.all(), required=True, widget=forms.Select()) supplier = forms.ModelChoiceField(queryset=Supplier.objects.all(), required=True, widget=forms.Select()) glossary = forms.ModelChoiceField(queryset=Glossary.objects.all(), required=False, widget=forms.SelectMultiple()) product_image = forms.ImageField( required=True, widget=forms.FileInput()) class Meta(): model = Product fields =[ 'name', 'description', 'reference', 'width', 'height', 'length', 'polution', 'unit_price', 'technical_implementation', 'sub_chapter', 'supplier', 'glossary', 'product_image', ] -
Django: Delete or empty content of a row in UpdateView
I'm looking to delete or empty a specific row in my table/model in my UpdateView. I have a team and employees in the team. I have made an update view that when "yes" is pressed, the team becomes archived. I want to additionally delete or empty the employee's numbers when doing so. How would I approach that? I know it might be weird, but the idea is that the employee's numbers should be destroyed once the team is archived, while the rest of the data still stands. Team Model class Team(models.Model): slug = models.SlugField(max_length=200) teamname = models.CharField(max_length=50, help_text="Indtast holdnavn.", null=False, primary_key=True) is_active = models.BooleanField(default=True) Employee Model class Employee(models.Model): id = models.AutoField(primary_key=True) slug = models.SlugField(max_length=200) emp_num = models.IntegerField(help_text="Indtast medarbejderens MA-nummer. (F.eks 123456)") firstname = models.CharField(max_length=30, help_text="Indtast medarbejderens fornavn.") lastname = models.CharField(max_length=30, help_text="Indtast medarbejderens efternavn.") teamname = models.ForeignKey('Hold', on_delete=models.CASCADE, null=True) UpdateView My updateView is using team, as its that model I'm updating. class ArchiveHoldView(UpdateView): template_name = 'evalsys/medarbejder/archive_hold.html' model = Team form_class = ArchiveForm def archive_view_team_with_pk(self, slug=None): if slug: team = Team.objects.get(slug=slug) else: team = self.team args = {'team': team} return render(self, 'evalsys/medarbejder/archive_hold.html', args) def get_context_data(self, **kwargs): context = super(ArchiveHoldView, self).get_context_data(**kwargs) context['is_active'] = Team.objects.get(slug=self.kwargs.get('slug')) return context def get_success_url(self): return reverse_lazy("evalsys:home") -
DRF - multiple user model and authentication
Let say I need to have this users: - user model from imported package (it is for customer to login, it using SSO from other project), it has their own authentication too. - own user model that different from imported package (it is only for admin to access backend and DRF API for this project) how to implement that? I only know that i have to change settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'imported_user_package', ... ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'imported_user_package.authentication.SSOAuthentication', ), ... } AUTH_USER_MODEL = 'imported_user_package.UserModel' how to create own user model, and use it for access admin backend and API with default rest framework authentication ? -
Django-Rest-Framework- How to make model serializer extra fields respect the depth
I would like to understand/control the depth argument of nested serializers. For some fields it works, for some others it does not. The serializer: class MyUserSerializer(serializers.ModelSerializer): cars = CarSerializer(read_only=True, many=True) class Meta: model = MyUser fields = '__all__' depth = X with depth=0 in the serializer class: { 'name': 'foo', 'cars': [<list of car ids>] } with depth=1: { 'name': 'foo', 'cars': [<list of car objects>] } If the list of cars is a ManyToManyField or a ForeignKey, everything works. If the list of cars is a User Model method, then the depth has no impact. What I mean by User Model method (just an example from models.py): class User(models.Model): ... def cars(self): return models.Car.objects.all() What would you recommend ? My final goal is to dynamically change the depth using query params such as in Django Rest Framework : Nested Serializer Dynamic Model Fields -
Capture print statements and yield them to StreamingHttpResponse
I'm writing a module that prints its progress as it loads data, does some calculations, and saves the result, roughly like this: def process_data(): print('Loading data...') data = load_data() print('Data loaded. Starting calculations...') result = calculate(data) print('Calculations complete. Saving result...') save_result(result) print('Done.') I want to connect this module with a Django view so that the end user can see the progress of the print statements as it runs. This appears to be possible using StreamingHttpResponse, which accepts an iterator and sends any yielded text to the browser as it runs. So far I had some success by changing print to yield in the main function. But when I tried to change print to yield in the calculate function, it got rather messy: from django.http import StreamingHttpResponse def process_data_view(request): return StreamingHttpResponse(process_data()) def process_data(): yield '<pre>Loading data...\n' data = load_data() yield 'Data loaded. Starting calculations...\n' # Here's where it got messy: for printline_or_result in calculate(data): # when calculate function yields a string, take it as a line to print if isinstance(printline_or_result, str): yield printline_or_result # when calculate function yields a non-string, take it as the result else: result = printline_or_result yield 'Calculations complete. Saving result...\n' save_result(result) yield 'Done.\n' Is there any better … -
Celery Periodic Tasks check for database changes
I'm trying to implement Fetcher app. I have DB where I store url and interval(seconds) and django celery beat for periodic tasks to fetch these urls after X seconds periodically. Is it possible to handle database updates(POST's and DELETE's) on my DB while my celery beat and workers are running? Could you give me an example how to achieve that? Example of my problem: 4 tasks, ids: [1,2,3,4] turning on celery beat and worker everything works great till we delete, for example id 2 celery still trying to run periodic task for 4 tasks instead of 3. @app.on_after_finalize.connect def setup_periodic_tasks(sender, **kwargs): logging.info('[*] Setting up periodic tasks...') from api.models import RequestModel queryset = RequestModel.objects.all() for req in queryset: sender.add_periodic_task(req.interval, fetch_url.s(req.id, req.url)) -
Is there any way to get current user from the request? I am getting annonymous user even though user is loggedin
This is my first app in django + react so I am not professional. I am writing viewset and trying to get current user from the request but I got anonymous user even though user is loggedin. My frontend is in react and I am using allauth and rest-auth for django authentication. Please help! I was trying to find out if there is an issue with token but it seems that works fine that. I have also CustomUser so maybe is that... Here is my login func in react redux: export const authLogin = (username, password) => { return dispatch => { dispatch(authStart()); axios.post('http://127.0.0.1:8000/rest-auth/login/', { username: username, password: password }) .then(res => { console.log("RESPONSE LOGIN") console.log(res) const token = res.data.key; const user = username; const expirationDate = new Date(new Date().getTime() + 3600 * 1000); localStorage.setItem('token', token); localStorage.setItem('user', user); localStorage.setItem('expirationDate', expirationDate); dispatch(authSuccess(token)); dispatch(checkAuthTimeout(3600)); }) .catch(err => { dispatch(authFail(err)) }) } } const authSuccess = (state, action) => { return updateObject(state, { token: action.token, error: null, loading: false }); } and here is my viewset and custom user model: class MatchViewset(viewsets.ViewSetMixin, generics.ListAPIView): serializer_class = MatchSerializer def get_queryset(self): user = self.request.user print(user) return Match.objects.filter(creator=user) class CustomUser(AbstractUser): GENDER_CHOICES = ( ("F", "FAMALE"), ("M", "MALE") …