Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django dynamic change of LANGUAGE_CODE to use 1 template and 3 translated model fields
I want to use one single template to be displayed in 3 different languages depending on the LANGUAGE_CODE, so I would like to alter the value of LANGUAGE_CODE value and selecting the language from a dropdown menu in my template. My model contains translated fields in 3 languages class Recipe(AuditBaseModel): recipe_id = models.AutoField(primary_key=True) recipe_code = models.CharField(max_length=30, null=False, blank=False) recipe_name = models.TextField(verbose_name=_('recipe_name'), blank=True, null=True) recipe_name_eng = models.TextField(blank=True, null=True) recipe_name_nor = models.TextField(blank=True, null=True) My template is able to show each field depending on the LANGUAGE_CODE {% get_current_language as LANGUAGE_CODE %} {% if LANGUAGE_CODE == 'en-gb' %}<h2>{{ recipe_form.recipe_name_eng.value }}</h2> {% elif LANGUAGE_CODE == 'nb' %}<h2>{{ recipe_form.recipe_name_nor.value }}</h2> {% elif LANGUAGE_CODE == 'es' %}<h2>{{ recipe_form.recipe_name.value }}</h2> {% endif %} Also, in my template, I have a dropdown menu for language selection <li><a href="">Language</a> <ul class="sub-menu"> <li><a href="">English</a></li> <li><a href="">Norsk</a></li> <li><a href="">Espanol</a></li> </ul> </li> How can I dynamically alter the value of LANGUAGE_CODE in my settings.py when the user selects a specific language from the template menu? Any better idea without using i18n? Many thanks in advance -
ERROR: MySQL_python-1.2.5-cp27-none-win_amd64.whl is not a supported wheel on this platform
So i am setting up an old project its python2 and django1 where i'm stuck with installtion of requirement.txt This is the main error i'm getting while installing Building wheel for MySQL-python (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/rehman/projects/comparedjs/bin/python2 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-KyvPG6/MySQL-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-KyvPG6/MySQL-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-jCT7NK cwd: /tmp/pip-install-KyvPG6/MySQL-python/ Complete output (38 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mariadb -I/usr/include/mariadb/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o In file included from _mysql.c:44: /usr/include/mariadb/my_config.h:3:2: warning: #warning This file should not be included by clients, include only <mysql.h> [-Wcpp] #warning This file should not be included by … -
is it ok to use formview instead of updateview, createview in Django?
so I'm new here in django and have already get the point of some generic views but it really gives me a hard time to understand the UpdateView, CreateView and DeleteView all information that I search still not giving me a point on how to use them. So I have a form registration which have username and password but they are in different table or model to save; you may take a look on the forms.py, And trying UpdateView its giving me only an error to my project. So as I found in some forums, i can't use UpdateView to a foreign key table for its looking only a primary key So instead of using them I use FormView replacing by the 3 generic view for now. Is it ok to use the FormView as an option aside the 3 generic view? Here is my source code. forms.py: from django import forms class UserCredentialForm(forms.Form): username = forms.CharField(label = 'Email', widget = forms.TextInput( attrs = { 'id': 'id_login_username', 'class': 'form-control', 'autocomplete': 'off', } ), required = False) password = forms.CharField(label = 'Password', widget = forms.PasswordInput( attrs = { 'id': 'id_login_password', 'class': 'form-control', } ), required = False) class UserInfoForm(forms.Form): year = … -
do i need to learn all functions of programming language? [duplicate]
I am new to programming, i know basics of programming. I also write some code in python, php and javascript. Every programming language has hundreds of builtin functions. For example, every programming language has different functions of string, array, int and file I/O etc. Plus framework functions like django, laravel and codeiginter etc. Do i need to learn all builtin functions? for example if i learn php do i need to learn all functions of php plus laravel/codeiginter or if i learn asp.net do i need to learn all functions of c# and asp.net? i don't think it is possible, because there are hundreds of functions in programming language, functions return types and functions parameters? -
Order Union by created_at
I have a graphene.Union of two models and i'm tying to order the response by created_at field, witch is a matching field for both models. Is there of doing that? Schema.py class PostUnion(graphene.Union): class Meta: types = (PostType, Post2Type) @classmethod def resolve_type(cls, instance, info): # This function tells Graphene what Graphene type the instance is if isinstance(instance, Post): return PostType if isinstance(instance, Post2): return Post2Type return PostUnion.resolve_type(instance, info, search) class Query(graphene.ObjectType): all_posts = graphene.List(PostUnion, search=graphene.String(), limit=graphene.Int()) def resolve_all_posts(self, info, search=None, limit=None): if search: filter = ( Q(id__icontains=search) | Q(title__icontains=search) ) return (list(Post.objects.filter(filter)) + list(Post2.objects.filter(filter)))[:limit] return (list(Post.objects.all()) + list(Post2.objects.all()))[:limit] { allPosts(Order: "created_at") { ... on PostType { id title createdAt } ... on Post2Type { id title createdAt } } } -
SMTPSenderRefused (530, b'5.7.0 Authentication Required)
I make a website with django and im having some troubles whit the reset password feature in deployment with heroku (works fine locally), when i try to use it, an error pops up: SMTPSenderRefused at /password-reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError a68sm8842573qkd.10 - gsmtp', 'webmaster@localhost') Request Method: POST Request URL: https://mytobiapp.herokuapp.com/password-reset/ Django Version: 3.0.4 Exception Type: SMTPSenderRefused Exception Value: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError a68sm8842573qkd.10 - gsmtp', 'webmaster@localhost') Exception Location: /app/.heroku/python/lib/python3.6/smtplib.py in sendmail, line 867 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.10 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] settings.py EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST="smtp.gmail.com" EMAIL_PORT=587 EMAIL_USE_TLS= True EMAIL_HOST_USER = os.environ.get("GMAIL") EMAIL_HOST_PASSWORD = os.environ.get("CONTRASEÑA_GMAIL") I already tried to allow acces to less secure apps and use the displayunlockcaptcha feature of google, but nothing seems to work. Any help will be apreciated -
setting django project for production / development enviroment
I am writing a Django project that it needs to be divided as production/development, but however my project looks like this, how can I organize in order to execute python manage.py runserver for dev or prod. . ├── apps │ ├── account │ │ ├── migrations │ │ │ └── __pycache__ │ │ └── __pycache__ │ ├── course │ │ ├── migrations │ │ └── __pycache__ │ ├── quizgame │ │ ├── migrations │ │ │ └── __pycache__ │ │ └── __pycache__ │ └── site │ └── __pycache__ └── app └── __pycache__ 16 directories -
how do i fix this warning?
i wanted to create a simple web aplication using django, and when i run through the terminal the command: django-admin startproject my site and i get the error ''django-admin'' is not recognized as an internal or external command, operable program or batch file. i have tried running cmd as administrator but at the end the same result the problem i guess is this warning: WARNING: The script sqlformat.exe is installed in 'C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. can anyone help me how to find a solution p.s i'm very new to programming -
GeoDjango maps on Django forms
I want to have a GeoDjango LeafLet map on my form. On another page I succesfully implemented this, but I do struggle on my forms (CreateView and UpdateView). I do get this errorin my browser console: Uncaught ReferenceError: L is not defined at loadmap (new:109) forms.py from leaflet.forms.fields import PointField from leaflet.forms.widgets import LeafletWidget from django.contrib.gis import forms class TourStepForm(forms.ModelForm): required_css_class = 'required' place = forms.PointField( widget=LeafletWidget(attrs=LEAFLET_WIDGET_ATTRS)) class Meta(): model = Toursteps exclude = ('tour',) views.py class CreateTourStepView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'tour_admin/tour_list.html' success_url = '/' form_class = TourStepForm model = Toursteps template_name = 'tour_admin/toursteps_form.html' def get_context_data(self, **kwargs): context = super(CreateTourStepView, self).get_context_data(**kwargs) return context def get(self, request, *args, **kwargs): self.tour_id = get_object_or_404(Tour, pk=kwargs['tour_id']) return super(CreateTourStepView, self).get(request, *args, **kwargs) def form_valid(self, form): if form.is_valid(): self.tour_id = self.kwargs.get('tour_id') form.instance.tour_id = self.tour_id form.instance.save() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('tour_detail', kwargs={'pk':self.tour_id}) steps.html {% extends 'tour_admin/admin_base.html' %} {% load crispy_forms_tags %} {% load leaflet_tags %} {% leaflet_css plugins="forms" %} {% leaflet_js plugins="forms" %} {% block content %} {% if user.is_authenticated %} <div class=""> <h1>Step:</h1> <form enctype="multipart/form-data" class="tour-form" method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> {% else %} <h1>Not authorised!</h1> {% endif %} {% endblock %} -
want to convert response from django api into java object in android
want to convert response from django api into java object in android. Im currently able to display it in logcat but cant convert it to string or object to process it. this is my code. ''' final RequestQueue requestQueue= Volley.newRequestQueue(getActivity()); JsonArrayRequest arrayRequest=new JsonArrayRequest(Request.Method.GET, URL, null, new Response.Listener() { @Override public void onResponse(JSONArray response) { Log.e("Rest Response",response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Rest response",error.toString()); } }); requestQueue.add(arrayRequest); ''' -
How to query reverse foreign key in django?
I am trying to filter queryset for a reverse foreign key. Here are my two models:- class BranchModel(basemodel.BaseModel): company = models.ForeignKey(CompanyModel, on_delete=models.PROTECT) name = models.CharField(max_length=30, default="Head Office") user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='branch_owner') class User(AbstractUser): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) objects = UserManager() I want to get all the users of a branch. I tried to use this queryset:- User.objects.filter(branchmodel__user=self.request.user) but it is giving me empty result. how can i modify this? -
Running Django on Windows Using an IIS Server
I'm trying to run Django on Windows Using an IIS Server, I'm following a nice tutorial: https://www.youtube.com/watch?v=CpFU16KrJcQ&fbclid=IwAR37FtYd2ZveEIxBy1FAiqOkp3jpwwjyMQwuGnnaUW_renNHogfrMEbXNUs I get stuck at the point where I wfastcgi-enable Here is the output of the error .. ERROR ( message:Configuration error Filename: redirection.config Line Number: 0 Description: Cannot read configuration file due to insufficient permissions . ) An error occurred running the command: ['C:\\Windows\\system32\\inetsrv\\appcmd.exe', 'set', 'config', '/section:system.webServer/fastCGI', '/+[fullPath=\'"C:\\Users\\\\pyt hon.exe"\', arguments=\'"C:\\lib\\site-packages\\wfastcgi.py"\', signalBeforeTerminateSeconds=\'30\']'] Ensure your user has sufficient privileges and try again. I don't know how to set privileges to accept the command .. can anybody help? -
Django signals for two types of users
I'm trying to build an app that will have two different user types. Currently I have one type of user called - Tenant Profiles. I'm trying to add in Landlord Profiles type also. Both profiles are derived from Django's in-built auth_users. I have taken last_name field from auth_users to True or False and I'm trying to build Landlord/Tenant profiles based on this condition. I have tried to modify the signals.py file, but have had no luck so far. With code attached below it allows you register, but only creates account for auth_users. If I use commented code in signals.py it will create Tenant Profile. signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Tenant_Profile, Landlord_Profile # This function aims to create a profile everytime a user registers @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): #if created: #Tenant_Profile.objects.create(tenant=instance) if created and User.last_name == False: Tenant_Profile.objects.create(tenant=instance) elif created and User.last_name == True: Landlord_Profile.objects.create(landlord=instance) # kwargs just accepts any additional keyword arguments on the end of the function @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): #instance.tenant_profile.save() if User.last_name == False: instance.tenant_profile.save() elif User.last_name == True: instance.landlord_profile.save() views.py def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if … -
Pagination in Wagtail with {%for %} cycle
I have some problem with understanding django pagination in Wagtail cms. I read this topic Pagination in Wagtail So it is not works well for me. In my templates for get products i use this code {% for product in page.get_children.specific %} <div class="col-12 col-sm-6 col-lg-4"> <div class="single-best-receipe-area mb-30"> {% image product.product_photo width-400 %} <div class="receipe-content"> <a href="{% pageurl product %}"> <h5>{{ product.title }}</h5> </a> </div> </div> </div> {% endfor %} and then: <ul class="pagination"> {% if product.has_previous %} <li><a href="?page={{ product.previous_page_number }}"><i class="fa fa-angle-left"></i></a></li> {% endif %} {% for page_num in product.paginator.page_range %} <li {% if page_num == product.number %}class="active" {% endif %}><a href="?page={{ page_num }}">{{ page_num }}</a></li> {% endfor %} {% if product.has_next %} <li><a href="?page={{ product.next_page_number }}"><i class="fa fa-angle-right"></i></a></li> {% endif %} </ul> in my models.py i use this: class ProductsPage(Page): body = models.CharField(max_length=255, blank=True, help_text = 'Описание страницы') product_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name='+', help_text='Фотография Категории' ) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), ImageChooserPanel('product_image'), ] def get_context(self, request): context = super(ProductsPage, self).get_context(request) all_product = OneProduct.objects.live() paginator = Paginator(all_product, 1) # Show 3 product per page page = request.GET.get('page') try: product = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first … -
AH01630: client denied by server configuration wsgi.py
I just configured my apache server and I did it patiently but I'm getting this error Forbidden You don't have permission to access this resource. Apache/2.4.41 (Ubuntu) Server at 139.162.198.195 Port 80 [authz_core:error] AH01630: client denied by server configuration: /home/project/project/wsgi.py Thanks in advance. -
Django auto primary key field increments instead of taking released ids
I'am using models.AutoField(primary_key=True) for my model, so id field is automatically incremented. Number of rows in a table stays always under 1000, because outdated rows are always deleted, so AutoFiled could use released ids, but it doesn't - it always increments. Can i make it to take free integers from released ids? -
NoReverseMatch at /products/drama/ - Reverse for 'product' not found. 'product' is not a valid view function or pattern name
Creating Product tag works alone, but if I add any entry in product (which should be linked with product tag) it produced error. Here is Url from app: from django.contrib.auth import views as auth_views from django.urls import path, include from django.views.generic import TemplateView from django.views.generic.detail import DetailView from main import views from main import forms from main import models path( "products/<slug:tag>/", views.ProductListView.as_view(), name="products", ), Here is models.py: class ProductTag(models.Model): name = models.CharField(max_length=40) slug = models.SlugField(max_length=48) description = models.TextField(blank=True) active = models.BooleanField(default=True) objects = ProductTagManager() def __str__(self): return self.name def natural_key(self): return (self.slug,) class ActiveManager(models.Manager): def active(self): return self.filter(active=True) class Product(models.Model): name = models.CharField(max_length=40) description = models.TextField(blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) slug = models.SlugField(max_length=48) tags = models.ManyToManyField(ProductTag, blank=True) active = models.BooleanField(default=True) in_stock = models.BooleanField(default=True) date_updated = models.DateTimeField(auto_now=True) objects = ActiveManager() def __str__(self): return self.name class ProductImage(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE ) image = models.ImageField(upload_to="product-images") thumbnail = models.ImageField( upload_to="product-thumbnails", null=True ) Here is views.py: class ProductListView(ListView): template_name = "main/product_list.html" paginate_by = 4 def get_queryset(self): tag = self.kwargs["tag"] self.tag = None if tag != "all": self.tag = get_object_or_404( models.ProductTag, slug=tag ) if self.tag: products = models.Product.objects.active().filter( tags=self.tag ) else: products = models.Product.objects.active() return products.order_by("name") I think problem is somewhere in 'joining' between … -
Pwa and allauth with django/python
I enabled PWA installation withn django-pwa plugin correctly. I'm also using allauth for loggin/registration and authentication which works from the accounts/ url (for eg: accounts/login). With these allauth urls, the PWA installation is not working, manifest file is not found. Do you know what shall I configure to enable the installation for those URLs as well? Here are my PWA settings: PWA_APP_NAME = 'asdfadsfasdf' PWA_APP_DESCRIPTION = "asdfadsfasf" PWA_APP_THEME_COLOR = '#0A0302' PWA_APP_BACKGROUND_COLOR = '#3F214B' PWA_APP_DISPLAY = 'standalone' PWA_APP_SCOPE = '/' PWA_APP_ORIENTATION = 'any' PWA_APP_START_URL = '/' PWA_APP_ICONS = [ { 'src': '/static/images/logo192.png', 'sizes': '192x192' } ] PWA_APP_ICONS_APPLE = [ { 'src': '/static/images/logo512.png', 'sizes': '512x512' } ] PWA_APP_SPLASH_SCREEN = [ { 'src': '/static/images/logo512.png', 'sizes': '512x512' } ] #PWA_APP_DIR = 'ltr' PWA_APP_LANG = 'en-US' PWA_APP_DEBUG_MODE = True here is my urls.py settings urlpatterns = [ path('', include('withdraw.urls')), path('', include('users.urls')), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('pwa.urls')), ] -
How do I get an appropriate loader to handle this file type in Django?
I have just started a django and react project. Whenever I try and load some css be it plain css or from bootstrap I get the following error: I followed the following tutorial: https://www.valentinog.com/blog/drf/ I move my .bablrc and my webpack.config.js into my project root folder. Previously it was inside the frontend app folder. Please let me know what I am missing! ERROR in ./src/components/App.js 39:6 Module parse failed: Unexpected token (39:6) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | render() { | return ( > <Table striped bordered hover> | <thead> | <tr> @ ./src/index.js 1:0-35 Below are my files: My webpack.config.js: module.exports = { module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } }; My package.json: { "name": "frontend", "version": "1.0.0", "main": "index.js", "scripts": { "dev": "webpack --mode development ./src/index.js --output ./static/frontend/main.js", "build": "webpack --mode production ./src/index.js --output ./static/frontend/main.js" }, "keywords": [], "author": "", "license": "ISC", "description": "", "devDependencies": { "@babel/core": "^7.9.0", "@babel/plugin-proposal-class-properties": "^7.8.3", "@babel/preset-env": "^7.9.0", "@babel/preset-react": "^7.9.4", "babel-loader": "^8.1.0", "css-loader": "^3.4.2", "react": "^16.13.1", "react-dom": "^16.13.1", "ts-loader": "^6.2.2", "webpack": "^4.42.1", "webpack-cli": "^3.3.11" }, "dependencies": { … -
Python: Append a dictionary as a new object to a dictionary key
I am developing a Django API to populate certain sets of data under different sections/categories. In there each section/catergory will have multiple dictionaries. Requirement: "data": { "engineers": { {"id": 1, "name": "aaa"}, {"id": 2, "name": "bbb"}, {"id": 3, "name": "ccc"}, }, "doctors": { {"id": 5, "age": "50"}, {"id": 6, "age": "60"}, {"id": 7, "age": "70"}, }, } In this example I need to append new engineer objects to "engineers" node, and new doctor objects to "doctors" node. The method I've tried is as follows. data = {} data["engineers"].append({"id": 4, "name": "ddd"}) data["doctors"].append({"id": 8, "age": "45"}) Error: During handling of the above exception ('set' object is not subscriptable), another exception occurred: How can I do this? -
Django LDAP and docker: how i can manage to store a dynamic config?
i'm using Django-ldap-auth module (Git Repo), now, considering those deployment scenario: The container of the web application runs in a Docker swarm environment and it can be scaled I can't mount ANY volume, so, config files are out of questions due to data persistance The config needs to live in the settings.py How i can store the django-ldap-auth configuration that can be changed by the user directly from the frontend web application? I was considering to use docker secrets, but with docker-py i'm unable to retrieve a created secrets data. Does anyone has some ideas to solve this puzzle? -
What happens when data on Redis is not consumed?
I just got started with Redis and i'm trying to understand how does it work, so i apologize if what i'm gonna say is not correct. I want to build a real time system where a Python application retrieves stock market trades from around 600 markets. Those trades should be sent to a Django application and shown on the frontend in real time, so i would have Python retrieves the trades > Django receives them and sends them to the page. I did not know how would Django receive the trades, so i thought of making some research on Redis, to see if it would be useful for my case, so here is what i thought: i'm retrieving the trades from 600 markets, so for every market i would create a Redis channel, whenever a trade is received, my Python app will push it to the right Redis channel. On my Django app, whenever an user opens the market page, a connection will be established to the right Redis channel (according to the specifi market that the user requested), and in this way the user will receive the trades on their page. So it would be: Python app updates the … -
How do I hash passwords in DRF?
I have a problem with serialized data that Django REST Framework outputs because the password fields aren't hashed (especially the ones created direct from DRF). The user that I created using createsuperuser command has the serialized password hashed (pbkdf2) which is fine, but the ones that I create using DRF aren't. The serializer that I use looks like this (serializers.py): from users.models import User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(style={'input_type': 'password'}) class Meta: model = User fields = '__all__' The model class looks like this (models.py): from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): class Role: ADMINISTRATOR = 'Administrator' PHARMACIST = 'Pharmacist' PATIENT = 'Patient' choices = { (ADMINISTRATOR, 'Administrator'), (PHARMACIST, 'Pharmacist'), (PATIENT, 'Patient'), } role = models.CharField(max_length=100, choices=Role.choices, default=Role.ADMINISTRATOR) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) email = models.EmailField(max_length=100, unique=True) birth_date = models.DateField(auto_now_add=False, blank=True, null=True) address = models.CharField(max_length=255) And the queryset looks like this (views.py): from django.shortcuts import render from users.models import User from rest_framework import viewsets from users.serializers import UserSerializer # Create your views here. class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() I am looking forward for your help. -
Django 2.2 disabled form field not passed to widget
I'm using the same form for creating and editing an object. One field cannot be edited when editing the object, so I passed it to self.fields['my_field'].disabled = True since django 1.9+ allow that (and it's cleaner). But whatever, the html doesn't change, the input is still editable and there's no disabled attribute on it. Checked in the view's context_data, my context_data['form'].fields['my_field'].disabled is True. So I don't understand what's happening. From what I saw here when the disabled is passed to the widget attributes. Am I missing somehting? When I manually do self.fields['my_field'].widget.attrs['disabled'] it's actually working. Do I have to add it myself to the widget ? Thanks in advance -
Non-pages in Django wagtail menu
I use wagtailmenus for my menus in Wagtail. This works fine for Wagtail pages. But sometime I wan't to include Django apps (e.g. photoalbum etc.) in the menu or submenu. Any ideas how to go about this?