Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The best way to run Spark application within Django project in Docker Swarm mode
I have a Django project in which I am supposed to exploit Apache Spark ML library. Moreover, I am using Docker in Swarm mode because I want to utilize a cluster of nodes for gaining better performance. What is the best architecture for my goal? I have thought about using pyspark within my Django project, and on request, connect to Spark master container and submit the intended application. The problem is I have not found anything about this approach; thus, I'm not sure if it's possible at all. Another solution might be submitting application using docker exec command. The problem arising here is that I do not have just one python file but a large scale Django project. It doesn't seem feasible too. -
can i do some preprocessing on image and use it whitout save changes?
Recently I wrote a code which reads image from an object storage. then I do some simple image processing on image. but i don't want to save changes on main image, also i don't want to copy image because of performance reasons. I just want to send manipulated image to a vies function in django in order to open it as a data file. is it any way to do this job? this is my function's schema. def watermark_image(image_name): # do some image processing on input image # cv2.imwrite(image_name, image) return image and this is a part of my function view: if request.method == 'GET': new_image = watermark_image(local_path + object_name) # image_data = open(??? , "rb").read() image_data = open(new_image , "rb").read() return HttpResponse(image_data, content_type="image/png") i don't know what should to wirte insetead of this line : image_data = open(new_image , "rb").read() -
Django Front End
I have a few questions. I'm learning Django and I have mastered a large part of BACKEND. Is classic Django with css html and JS sufficient for nice pages? What do I need to master to make these pages look good (html, css, js)? Is it necessary to learn django rest framework and some JS framework (REACT, ANGULAR)? Thank you for your help. -
Advanced filtering in Django ORM. Need a one query solution instead of recursion
I have a question regarding advanced filtering in Django ORM. MODEL: class ClubAgentPlayer(models.Model): club = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='club_agent_players') agent = models.ForeignKey(User, on_delete=models.CASCADE, related_name='agent_club_players') member = models.ForeignKey(User, on_delete=models.CASCADE, related_name='member_club_agents') created_at = models.DateTimeField(auto_now_add=True) Goal is like this: For example I have initial agent_id = 15 and I need to find all agents id of agents that are connected to the initial agent. I know how to do it via recursion. On the small sample is fine but on a bigger sample it would slow down DB drastically. So that I need to pull all data in 1 query. Resulting query set should be [ 15, 19, 22] – agent_id How to read chart: Initial agent has id= 15 (yellow). Members with id [18, 19, 27, 28] attached to this agent(orange). One of this members is an agent himself, number 19 (green). On a next level we have initial agent 19 (green) and he has members [22, 31, 32] attached to him. One of them is an agent himself 22 (red). Next level agent ID=22, his members are [37, 38, 39] . None of them is an agent. So we done here. At the end I need to have id of all connected … -
How to configure ajax request with jquery in django?
So i was doing a django project by following a youtube video.And I got this error "Forbidden (403) CSRF verification failed. Request aborted." everytime when i submit any data in my sign-up.html file. Then i realize i did not configure ajax correctly.So i search online and saw the django documentation of ajax.i made some changes in my html code. still, it did not solve my problem. I am still getting the same result.What is my mistake here.Did i made any mistake while configuring ajax? Its been a while since i am stuck in this problem. Thank you for your time My sign-up.html file: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Instapic</title> <link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/styles.css' %}"> </head> <body> <div class="login-clean"> <form method="post"> {% csrf_token %} <h2 class="sr-only">Login Form</h2> <div class="illustration"> <div style="display: none" id="errors" class="well form-error-message"></div> <img src="{% static 'assets/img/logo.jpg' %}"> </div> <div class="form-group"> <input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4"> </div> <div class="form-group"> <input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6"> </div> <div class="form-group"> <input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6"> </div> <div class="form-group"> … -
I Download Also Numpy From Pypi but its con't work
Traceback (most recent call last): File "C:/Users/Waqar Ahmad/PycharmProjects/Generic_summary/generic_base_summary.py", line 2, in import numpy as np File "C:\Users\Waqar Ahmad\Anaconda3\envs\website\lib\site-packages\numpy__init__.py", line 142, in from . import core File "C:\Users\Waqar Ahmad\Anaconda3\envs\website\lib\site-packages\numpy\core__init__.py", line 97, in from . import _add_newdocs File "C:\Users\Waqar Ahmad\Anaconda3\envs\website\lib\site-packages\numpy\core_add_newdocs.py", line 6839, in """.format(ftype=float_name))) File "C:\Users\Waqar Ahmad\Anaconda3\envs\website\lib\site-packages\numpy\core\function_base.py", line 467, in add_newdoc _add_docstring(getattr(new, doc[0]), doc[1].strip()) AttributeError: type object 'numpy.float16' has no attribute 'as_integer_ratio' Process finished with exit code 1 -
Django: Ho to set user name in session and get the user name in other view methods
I'm new to Python and Django. I'm using PHP form for login mechanism and once the login is successful, I'm sending the user name to Django application to carry on with other operations but I'm stuck in finding a best way to store the user name in session so that it can be used in other view methods Below are some of my tries which failed: 1) Storing the user name in a global variable and access throughout the application but when another user login from their machine, user name gets changed in my machine. 2) Storing the user name in Django DB session but another user logs in with different user, it's showing the old user only. 3) I tried storing in the cache but still, it's not working. DB session handler: It works fine when I access in sessionHandler method but it throws key error when i try to access in login method. def sessionHandler(request): userName = request.GET.get('uname') request.session['user'] = userName print("current logged in user: " + request.session['user']) return JsonResponse({'Response': 'success'}) def login(request): uname = request.session.get('user') UserName = {"Name": uname} return render(request, 'login/login.html', UserName) My use case is that any user who logs in their own machine and … -
Django - Inherit CustomQuerySetMixins
I have a class namend CustomQuerySetMixin and I would like a class to inherit from that class. In this class, I want to create a custom Queryset. Here's my code: CustomQuerySetMixin: class CustomQuerySetMixin(models.Model): class Meta: abstract = True objects = CustomQuerySetManager() class QuerySet(CustomQuerySet): pass CustomQuerySetManager and CustomQuerySet: class CustomQuerySetManager(models.Manager): """A re-usable Manager to access a custom QuerySet""" def __getattr__(self, attr, *args): try: return getattr(self.__class__, attr, *args) except AttributeError: # don't delegate internal methods to the queryset if attr.startswith('__') and attr.endswith('__'): raise return getattr(self.get_query_set(), attr, *args) def get_queryset(self): return self.model.QuerySet(self.model) def get_querySet(self): return self.get_queryset() def get_query_set(self): return self.get_queryset() class CustomQuerySet(models.QuerySet): def __getattr__(self, attr, *args): try: return getattr(super().__class__, attr, *args) except AttributeError: return getattr(self.model.QuerySet, attr, *args) My model: class Article(""" Some other mixins """, CustomQuerySetMixin): # Some fields class QuerySet(CustomQuerySetMixin.QuerySet): def my_awesome_function(self): return self When I now try to call that function (using this code -> Article.objects.my_awesome_function()) it throws this error: TypeError: Cannot create a consistent method resolution order (MRO) for bases TaggedQuerySet, CastTaggedQuerySet I know this has to do because in my CustomQuerySetMixin I'm inheriting from models.Model. When I remove this, it throws this error: AttributeError: 'CastTaggedManager' object has no attribute 'not_voted' -
django storages - save absolute path in database?
How can I save absolute paths (like /var/files/.. , or s3://bucket/path) in a table containing file field? Django by default uses MEDIA_ROOT as a prefix, and store relative paths. I use the django-storages package for S3 backend. -
What is the correct way to install and run a django project?
I am very new to Python and Django and trying to find the correct way to set up a basic Django project to start learning it. Following are my Python, Pip, and Django version details - Commands to find the versions - python --version pip --version python -m django --version I used the following commands to create a project and a module inside it - django-admin startproject djangoCrud cd djangoCrud/ python manage.py startapp api I was able to run the project using the following command - python manage.py runserver Then I read that I will need a virtual environment for further development, for which I used the following commands to create and run it - pip install virtualenv virtualenv env . env/bin/activate But when I tried to run the manage.py file after activating the environment, It throws an error - ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? But I can run the manage.py without activating the environment Can someone please guide me what's wrong and how do I fix this? -
I implemented Email settings on settings.py, but it doesn't work when I submit the form
here is my settings.py from .email_info import * # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = EMAIL_HOST EMAIL_HOST_USER = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = EMAIL_HOST_PASSWORD EMAIL_PORT = EMAIL_PORT EMAIL_USE_TLS = EMAIL_USE_TLS DEFAULT_FROM_EMAIL = EMAIL_HOST_USER I define values on email_info.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my id' EMAIL_HOST_PASSWORD = 'my pass' EMAIL_PORT = 587 here is my view.py def sendemail(request): if request.method =='POST': name = request.POST.get("name", "") email = request.POST.get("email","") contact = request.POST.get("contact","") date = request.POST.get("date_time","") address = request.POST.get("address","") subject = '시연 신청(' + name + ')' message = '이름: ' +name + '\n' + '연락처: ' + contact + '\n' + '시연 날짜: ' + date + '\n' + '주소: ' + address + '\n' + '이메일' + email send_mail(subject, message, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER]) messages.success(request, 'Thank you') return redirect('index') I tested send_mail module at console, and it works, but when I submit the form, it doesn't work. >>> send_mail('test', 'test', 'iuncehiro@gmail.com', ['iuncehiro@gmail.com']) 1 Where do I need to fix some settings? -
Django look css images into wrong directory
I have following settings for static files STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_my_proj'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'static_root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'media_root') In the css file I do this #mydiv{ background-image: url('/img/myimg.png'); } And my directory structure project root - static_my_proj - css - img - js I can see from network tab that it looks for the image in static/css/img/myimg.png. However, if I do this then it works. How can I make it without using ../ at the beginning? #mydiv{ background-image: url('../img/myimg.png'); } -
How do I write a Django query that does date math when executed as PostGres SQL?
I'm using Django and Python 3.7. I'm writing a Django query to be run on a PostGres 9.4 db, but having trouble figuring out how to form my expression wrapper so that I add a number of seconds (an integer) to an existing date column. I tried the below hour_filter = ExtractHour(ExpressionWrapper( F("article__created_on") + timedelta(0, F("article__websitet__avg_time_in_seconds_to_reach_ep")), output_field=models.DateTimeField) ), ) but I'm getting the error unsupported type for timedelta seconds component: F Any ideas how I can rewrite my ExpressionWrapper to do the date math inside the PostGres query? -
How to indent Django templates properly
I work in SublimeText 3. When writing Django templates I have a mixture of html and functions. I like to indent my code so that block, if and other such statements are indented. For example: Manual formatting {% extends "accounts/base.html" %} {% block content %} <h1>Password changed</h1> <p>Your password was changed.</p> {% endblock %} However, when I run any autoformatter HTML-CSS-JS-Prettify it ignores these brackets and treats them as text: After formatting {% extends "accounts/base.html" %} {% block content %} <h1>Password changed</h1> <p>Your password was changed.</p> {% endblock %} Although plugins like Djaneiro give great tag highlighting, I haven't been able to find a way to get SublimeText to treat these as tags. Has anyone had any luck? -
i can't reach the new url after defined the view function and write the url and adding some data
strong texti was creating a new URL route after write the view function and creating the template and adding some data to use it and i still can't reach my URL views.py def new_topic(request, pk): board = get_object_or_404(Board, pk=pk)7 return render(request, 'new_topic.html', {'board': board}) urls.py urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^boards/(?P<pk>\d+)/$', views.board_topics, name='board_topics'), url(r'^boards/(?P<pk>\d+)/$', views.new_topic, name='new_topic'), url(r'^admin/', admin.site.urls), ] new_topic.html {% extends 'base.html' %} {% block title %}Start a New Topic{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li> <li class="breadcrumb-item active">New topic</li> {% endblock %} {% block content %} {% endblock %} ''' i expected when i write in the url that : 127.0.0.1:888/boards/3/new/ i see what i wrote in new_topic template but it show me this error: Page not found (404) Request Method: GET Request URL: `http`://127.0.0.1:8000/boards/4/new Using the `URLconf` defined in `myproject`.`urls`, `Django` tried these URL patterns, in this order: ^$ [name='home'] ^boards/(?P<pk>\d+)/$ [name='board_topics'] ^boards/(?P<pk>\d+)/$ [name='new_topic'] ^admin/ The current path, boards/4/new, didn't match any of these. -
Django User Rating System
I have an e-learning project with courses on different topics and I want to implement a rating system for the users. I started with a ManyToManyField to the user model. The rating of a user increases when he gets rated by other users. But I want to link the rating to the courses, so that it increases on every completed course. Im thinking of a button at the end of every course that says "completed" and that will increase the rating of the user when he gets there and clicks on it. But if I then want the courses to have different levels of difficulty, I would need to add different ratings to the buttons, which does not make sense. So the rating must be connected to the level of the course in a manner that they both add up. Thank you for any suggestions -
How to interrupt input reading in Django view when clicking a link
I'm working on a django based lock/access system with an RFID reader. The problem is that if while waiting for the reader to detect a tag, I click a link on the template already displayed, the server keeps waiting for the card in the background. It follows that if then I come back to the access page and reload the reading function, it puts that request below the one before. The problem also occur if I use basic input() function instead of reader.read_id() function from mfrc522 library import mfrc522 # ... other imports # main access view def access_result(request): reader = mfrc522.SimpleMFRC522() # CRITICAL PART card_id = reader.read_id() try: if RFIDCard.objects.get(card_id=card_id): card = RFIDCard.objects.get(card_id=card_id) if card.remaining_accesses > 0 and card.expiration_date >= datetime.date.today(): card.remaining_accesses -= 1 # ... some other lines of code (not relevant) except RFIDCard.DoesNotExist: message = 'Card not registered' description = 'It seems that we haven\'t registered this card. ' \ 'Please ask for help at the reception' return render(request, 'rfid/access_result.html', { 'message': message, 'description': description }) I'd like to interrupt the reading if the user goes elsewhere clicking on a link of the page displayed before (and during) the reading. Is there a simple way I could … -
Highcharts - Pass a dictionary as data for a timeline series
So, I've been using Highcharts for quite a while, and I was trying to make a Timeline Chart. I've seen some example code on the internet and noted that the data attribute is basically a dictionary. So I made a dictionary from some data, using python/pandas etc, and it looks like this: [{'name': '2017-12-07 - Chat', 'label': 'some text', 'description': 'some text'}, {'name': '2017-12-15 - Whatsapp', 'label': 'some text', 'description': 'some text'}] I pass this in a context in django and then call it in the html template, together with the js code for the chart: <script type="text/javascript"> var _dict = {{dict|safe}}; </script> <script src="/static/vendors/highcharts/cs_timeline.js"></script> And then in the javascript file, I use the dict as the data attribute, using some code I've got from the official Highcharts example: Highcharts.chart('hist', { chart: { type: 'timeline' }, xAxis: { visible: false }, yAxis: { visible: false }, title: { text: 'Timeline of Space Exploration' }, subtitle: { text: 'Info source: <a href="https://en.wikipedia.org/wiki/Timeline_of_space_exploration">www.wikipedia.org</a>' }, series: [{ dataLabels: { connectorColor: 'silver', connectorWidth: 2 }, data: _dict }] }); This works fine for every chart I've done, but isn't working for this one. I'm having trouble identifying where the problem is; the format, the … -
Webpack use folder name instead of Url for public path
I am using react and django. I am trying to use code-splitting in my components, so in my webpack.config.js I have this output: { path: path.join(__dirname, "frontend/static/frontend"), filename: "[name].bundle.js", chunkFilename: "[name].chunk.js", publicPath: "/frontend/static/frontend/" }, but when it requests it in the browser it goes to /en/account/quiz/drug-abuse/frontend/static/frontend/2.chunk.js instead of static/frontend/2.chunk.js my javascript files are located in my static folder for django but react routing starts at /en/, I am guessing that is why the confusion is happening. Is there anyway to make the webpack file look for http://domainblahblah.com/static/frontend/2,chunk.js -
Django race condition in simultaneous ModelForm submission
My model has a field working_hour which is IntegerField, I am using ModelForm and django-crispy-forms.Assume tow different people has rendered form with working_hour value 20 and both of them want to increase working_hour by 10 and they updates the working_hour form field from 20 to 30.When they both submit the form, updated working_hour becomes 30 in database, but it should be 40. models.py class OverallHour(models.Model): working_hour = models.PositiveIntegerField() forms.py class OverallHourForm(ModelForm): class Meta: model = OverallHour def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Submit('submit', 'UPDATE')) overall_hour_form.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="row justify-content-center"> <div class="col-md-8"> <div class="card bg-light"> <div class="card-body"> {% crispy form %} </div> </div> </div> </div> {% endblock content %} Can you please advice me how to fix this problem? -
I Wagtail how to disable certain admin menu items for the certain users?
For the group of users I want to disable some menu items. I thought I will use the following: from wagtail.contrib.modeladmin.options import ModelAdmin as WModelAdmin class WPartnerAdmin(WModelAdmin): ... def get_menu_item(self, order=None): menu_item = super().get_menu_item(order=order) # if (user_discrimination_logic): # menu_item.is_shown = lambda *a: False return menu_item But it seems that I don’t have access to the request object in the ModelAdmin, therefore don’t know how to extract the user data. Is there a way? -
Django __init__() takes at least 2 arguments (1 given)
Im getting this error when I try to login to my django app. I dont know what is happening, it worked 30 minutes ago and I havent touched anything since then. views.py def login_page(request): form = LoginForm(request.POST or None) context = { "form": form } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request,username=username,password=password) if user is not None: login(request,user) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path,request.get_host()): return redirect(redirect_path) else: request.notifications.add('Hello world.') messages.add_message(request, messages.INFO, 'Hello world.') return redirect("/") else: print("Error") return render(request, 'accounts/login.html',context) forms.py class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control","placeholder":"Your Username"})) password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"form-control","placeholder":"Your Password"})) Traceback File "/usr/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/django_project/accounts/views.py" in login_page 42. user = authenticate(request, username=username,password=password) File "/usr/local/lib/python2.7/dist-packages/lockout/decorators.py" in wrapper 43. result = function(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/contrib/auth/init.py" in authenticate 68. for backend, backend_path in _get_backends(return_tuples=True): File "/usr/lib/python2.7/dist-packages/django/contrib/auth/init.py" in _get_backends 29. backend = load_backend(backend_path) File "/usr/lib/python2.7/dist-packages/django/contrib/auth/init.py" in load_backend 23. return import_string(path)() Exception Type: TypeError at /login/ Exception Value: init() takes at least 2 … -
Django pass parameter when using urls include
In urls.py I dynamically create objects and want to create urls for each of them. I can iterate over them and include another urls file into my main urls.py like this: urlpatterns = [path(object.url, include('bar.urls')) for object in objects] However, in my application I want to pass the variable object to bar.urls that can be passed to the views afterward. I wonder if I can do something like this: urlpatterns = [path('foo', include('bar.urls', my_var=object)) for object in objects] and in bar: # bar.urls (got my_var somehow) urlpatterns = [path('foo', views.foo, object=my_var)] # bar.views def foo(request, object) # use object -
Django store foreign then submit form
How to use foreign key to create a new value and use that to submit the form before failing the if form.is_valid(). Issue is the foreign key is doesn't exit, want use to input the data and which like to use that as foreign key value and submit the form. MODEL: class AirportCode(models.Model): name = models.CharField(max_length=4, default=None, blank=True, unique=True) class AddData(models.Model): airportcode = models.ForeignKey(AirportCode, on_delete=models.SET_NULL, null=True) FORM: class Airportcode_Form(forms.ModelForm): class Meta: model = AirportCode fields = ('name',) class AddData_Form(forms.ModelForm): class Meta: model = Pull fields = ('airportcode',) def __init__(self, *args, **kwargs): super(AddData_Form, self).__init__(*args, **kwargs) self.fields['airportcode'].queryset = CODE.objects.none() if 'airportcode' in self.data: c = self.data.get('airportcode') self.fields['code_pull'].queryset = CODE.objects.filter(name=c) VIEW: def save(request): if request.method == 'POST': if form.is_valid(): add = form.save(commit=False) add.airportcode = form.cleaned_data['airportcode'] add.save() return redirect(save) else: messages.error(request, form.errors) context = {'form': form } return render(request, template_name, context) Getting error when submitting form, as the field Airportcode is not selected. Thanks for the help in advance -
Django. REST Framework. Rename SerializerMethodField()
In the django rest framework, I have a serializer, it takes fields from the model, combines it under one tag, and displays it in xml. Everything is simple. I understand how it works. But what I don’t understand is how to rename the parent tag. I will show: #serializers.py class kvSerializerLivingSpace(serializers.ModelSerializer): unit = serializers.CharField(default='qm') class Meta: model = kv fields = ['unit', 'value'] class kvSerializer(serializers.ModelSerializer): living_space = serializers.SerializerMethodField() class Meta: model = kv fields = ['living_space'] def get_living_space(self, obj): return kvSerializerLivingSpace(obj).data I need living_space through a hyphen. To make it look like living-space I know that i can rename tags as follows: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields.update({ 'living-space': kvSerializerLivingSpace() }) But this does not work for serializers.SerializerMethodField() Thank!