Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelMultipleChoiceField not saving
I got a ManyToMany field with the django-admin's ModelMultipleChoiceField working: When I add one element from the left side to the right side and click "Save" in the admin UI, then reload the Detail-Page where this ModelMultipleChoiceField is showing up, the saved elements can clearly be seen on the right side. The code for this working model looks like this: # project/account/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from model_utils import Choices class User(AbstractBaseUser, PermissionsMixin): following = models.ManyToManyField('self', related_name='followers', blank=True, symmetrical=False) # project/account/forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.admin.widgets import FilteredSelectMultiple from .models import User class UserChangeForm(forms.ModelForm): following = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Following', is_stacked=False ) ) followers = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Followers', is_stacked=False ) ) class Meta: model = get_user_model() fields = ('following', 'followers') def __init__(self, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) if self.instance and self.instance.pk: self.fields['following'] = forms.ModelMultipleChoiceField( queryset=User.objects.all().exclude(pk=self.instance.pk), required=False, widget=FilteredSelectMultiple( verbose_name='Following', is_stacked=False ) ) self.fields['followers'] = forms.ModelMultipleChoiceField( queryset=User.objects.all().exclude(pk=self.instance.pk), required=False, widget=FilteredSelectMultiple( verbose_name='Followers', is_stacked=False ) ) self.fields['followers'].initial = self.instance.followers.all() # project/account/admin.py from django.contrib.auth import get_user_model from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .models import User from .forms import UserChangeForm, UserCreationForm class Admin(BaseUserAdmin): form … -
Unable to handle webhooks for srs RTMP live streaming server with django
I returning 200 OK with HttpResponse fro django but the other side SRS is printing the following in the log http post on_connect uri failed. client_id=115, url=http://127.0.0.1:8000/livestream, request={"action":"on_connect","client_id":115,"ip":"127.0.0.1","vhost":"__defaultVhost__","app":"live","tcUrl":"rtmp://127.0.0.1:1935/live","pageUrl":""}, response=, code=2128, ret=1018(Bad file descriptor) as per SRS docs callbacks expect 200 ok with 0 to indicate success. Am I missing anything? -
Django Dumpdata file contains debug logs
I'm dumping some data from my django app with the command python manage.py dumpdata > db.json Unfortunately the db.json contains some startup logs in the first lines of the files. The file looks like: DEBUG $HOME=/home/web DEBUG matplotlib data path /usr/local/lib/python3.5/dist-packages/matplotlib/mpl-data DEBUG loaded rc file /usr/local/lib/python3.5/dist-packages/matplotlib/mpl-data/matplotlibrc DEBUG matplotlib version 2.2.2 DEBUG interactive is False DEBUG platform is linux [{ ... then the json file ... }] I guess it's coming from my logs configuration, but I couldn't figured it out. Here is my logs config in setting.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'verbose': { 'format': '%(asctime)s %(levelname)s [%(module)s:%(funcName)s:%(lineno)d] %(message)s', }, 'simple': { 'format': '%(levelname)s %(message)s', }, }, 'handlers': { 'console_simple': { 'class': 'logging.StreamHandler', 'filters': ['require_debug_true'], 'formatter': 'simple', 'level': 'DEBUG', }, 'console_verbose': { 'class': 'logging.StreamHandler', 'filters': ['require_debug_false'], 'formatter': 'verbose', 'level': 'INFO', }, }, 'loggers': { 'django.request': { 'handlers': ['console_simple', 'console_verbose'], 'level': 'ERROR', 'propagate': False, }, }, 'root': { 'handlers': ['console_simple', 'console_verbose'], 'level': 'DEBUG', }, } Any ideas? -
error Session in SSR React app with Django
I'm building an app with server-side rendered app and using Django as an API server. The Django server handles the session and to manage the session properly I should get the session ID and send it with each request but in serve-side rendering I need to make a request on the Node.js server and after the page renders I make it on the front-end, the problem is the when I fetch any data from the Django server it sends the correct sessionId from cookies but only from on the front-end side but on the Node server-side it doesn't send the cookies to the Django API server so every time I order some data I get it assoiciated a new session. Notes: I'm sending the credentials with the request. I'm using req.universalcookies on the node back-en from universal-cookie-express -
How to fix Django error name 'username' is not defined
I am a beginner so please keep that in mind when answering my question. I have set up my views.py to include a register user function. The username variable is throwing NameError at /register name 'username' is not defined when I try and register. I know that means that the username has not been defined, however I thought it was inheriting from the Django class models.User which I have imported? I have made a registration page before and have not had to define the User variables such as username, email, password, etc. for it to function. Many thanks. views.py def register_view(request): if request.method == 'POST': # Post request. form = UserRegisterForm(request.POST) if form.is_valid(): username == form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('home') else: # Get request. form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from . import views from users import views as register_view urlpatterns = [ path('register', views.register_view, name='register'), ] forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ] -
django-tables2 permissions in TemplateColumn
I feel like I have read about this a hundred times but I still can't figure out how to use permissions within a django-tables2 TemplateColumn. My goal is to be able to render buttons in a column based on permissions that a user may have or may not have on a given model. That does not sound complicated to me and from what I have read I should be able to use something like {% if perms.myapp.delete_mymodel %} to achieve what I'd like to do. Here is the code I'm trying to get to work as I expect: import django_tables2 as tables MY_MODEL_ACTIONS = """ {% if perms.myapp.change_mymodel %} <a href="{% url 'myapp:my_model_edit' pk=record.pk %}" class="btn btn-sm btn-warning"><i class="fas fa-edit"></i></a> {% endif %} {% if perms.myapp.delete_mymodel %} <a href="{% url 'myapp:my_model_delete' pk=record.pk %}" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></a> {% endif %} """ class MyModelTable(tables.Table): # some columns actions = tables.TemplateColumn( verbose_name="", template_code=MY_MODEL_ACTIONS, ) class Meta(BaseTable.Meta): model = MyModel fields = ( # some columns "actions", ) When rendering the table no issues are triggered but the column just do not display any buttons (yes I do have the permissions for them to show up). Removing the {% if … %} … -
set and configure django project on cpanel
I have finished the development of my Django application and I'm ready to deploy it. I rented a host for deploying C Panel and installing Django on it. until this level everything is OK but I have a problem in uploading my configuration of my local project on my C Panel. but I don't know how should I do this and deploy it? i'm new in Django,please help me. thanks a lot. -
Django: Show different view based on User
I'd like to create a school management system for my personal project. Let's say there is an Admin for every School. But there is some Admin that can manage more than one schools, and they can switch between schools to manage each school. I've thought one way to do it, by using different URL path eg. urlpatterns = [ url(schools/<int:pk>/, SchoolView.as_view()), ] Is there a way so I do not separate by using different URL path for each schools? So, for each admin, they have similar URL path, but the view render different school based on Admin user. But I don't really know how to do that? Can I get an advice how to do it. Many thanks! -
Using Django Models in standalone script - database not updating
I am trying to update records in my SQLite3 db using the Django ORM and the update() function. I can see that after running the update() function in my standalone script, the database has in-fact been updated, but the changes are not reflected on my website until I run on my server: sudo systemctl restart gunicorn I suspect the issue has to do with the way I import my models into my standalone script. ROOT_DIR = /path/to/root/dir sys.path.insert(0, ROOT_DIR) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AppName .settings') import django django.setup() from main.models import Bet, Investment, Profile from django.contrib.auth.models import User Bet.objects.filter(id=4).update(revenue=10) I would expect to see the updates reflected on my site without having to restart gunicorn. More context: I am running a create() function in the same standalone script which is updating the database and being reflected on my site as expected without having to restart gunicorn. -
working with real dabatbase in testing _ django Restframework
I need an actual connection to my database for testing not testing environment. I have to request: 1. fetching data from a web service and stores to the database with post request. 2. getting those result stored in the database. so with RequestsClient() and CoreAPIClient() I figure out these are for working with Live and production environments but when I try to request to my endpoints. comes with 500 internal error. I found a parameter allow_database_queries when you want to request. I thought that should establish the connections to mySQL but there are no documentations about it. self.client = RequestsClient() # or CoreAPIClient() self.client.headers.update(allow_database_queries='yes', Authorization="bmhh "+ self.token) self.client.post('http://127.0.0.1:8000/stations/') -
Django: How to use modal as a form to update an object
I'm trying to use modal as a edit form but I don't know good way. Currently my views.py is like this. def edit_entry(request, entry_pk): entry = get_object_or_404(Entry, pk=entry_pk) if request.method != 'POST': form = EntryForm(instance=entry, user=request.user) else: form = EntryForm(instance=entry, data=request.POST, user=request.user) if form.is_valid(): form.save() and I have a template for this view. What I want to do is from the page that lists a bunch of entry objects, the edit form for the object is shown when I click edit button. {% for entry in entries %} ... <button class="btn btn-outline-primary" data-toggle="modal" data-target="#editEntryModal">Edit</button> <!-- modal for the object --> Anyone who could give me tips? -
Why serving static file in production, using django it's discouraged?
I have developed a web application that uses (obviously) some static files, in order to deploy it, I've chosen to serve the files with the WSGI interpreter and use for the job gunicorn behind a firewall and a reverse proxy. My application uses django_compressor to minify those files without using the OFFLINE_COMPRESSION, this why I'm generating dynamically some templates and I need the "On-demand js/CSS compression" Everything works fine and I don't have any issue regarding the performances...but, really, I can't understand WHY the practice to serve those static files using directly the WSGI interpreter it's discouraged (LINK), says: This is not suitable for production use! For some common deployment strategies... I mean, my service it's a collection of microservices: DB-Frontend-Services-Etc...If I need to scale them, I can do this without any problem and, in addition, using this philosophy, I'm not worried about the footprint of my microservices: for me, this seems logical, but maybe, for the rest of the world this is a completely out-of-mind strategy. -
How to hide options from a drop down menu search that won't find anything? Jquery
The website filter is implemented with three drop-down menus, each has its own list of options(color, model, engine). I need to hide color/model/engine options that won't give any result(i.e. not found| response.items.length == 0). The website runs on Django, so the initial color/model/engine that are loaded are already filtered with views.py to a degree, meaning they don't have options that don't have any variations regardless of the other two selections. Meaning if, for example, for color RED there are no models, regardless of the other options, color RED isn't loaded(filtered in views.py). However, if, let's say, for color RED, there are only models with the "A" engine, and no models with the "B" engine, my question is, how do I hide the "B" option from the engine drop-down menu when RED is selected? And vice-versa, if the "B" engine has no RED variation, how do I hide RED from the color drop-down menu when "B" is selected? The color listing part looks like this: <div class="select-color__items"> {% for color in colors %} <label for="{{ color|slice:"1:" }}" style="background-color: {{ color }}" class="select-color__item js-color-item js-select-filter {% if color == "#ffffff" %}select-color__item_white{% endif %}"> <input type="radio" id="{{ color|slice:"1:" }}" name="color" {% if request.GET.color … -
Django multiple user models
I want to create 2 custom user models(profiles) which will have a field with OneToOne mapping to the default Django auth User model. class StudentProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # several fields here class TeacherProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # more fields here I am able to implement it using signals if it was a single User Profile model. I have 2 forms and 2 views, one for each registration. How do I make only an object of the Profile model to be created when its respective form function is executed? -
Django/Play Framework: Clarify situation with HTTP chunking/streaming
Currently, I am new to a project that uses the Play Framework for a web application backend. For a specific REST endpoint we have to return a dynamically generated CSV file. To not hold the file in memory as a whole and to improve the TTFM (Time To First Byte) we thought about generating the file "on the fly" and returning those chunks immediately to the user. Because I have some knowledge in Django, I knew there's the StreamingHttpResponse which is exactly for the use case I described above. So I searched if there's something equivalent in the Play Framework and discovered Chunked responses. There they say it's using the "Chunked transfer encoding" mechanism provided by HTTP 1.1. That leads me to the following questions: Is both Django's StreamingHttpResponse and Play's Chunked response using the same mechanism in the background (like HTTP chunked transfer encoding) or do they use different techniques? This blog post makes me guess they're using both the same mechanism in the background. Assuming both are using the HTTP Chunked transfer encoding. What happens if my backend uses this, but HTTP 2.0 is supported and a compatible browser makes a HTTP 2.0 request? -
how to add a select option which is child of another select in django html
assume that i have 2 models A and B A is the main table and B is its sub (one to many relationship) some of contents in A have more than one subcategories in B and some have no items in B so , i want to display this contents in my html inside a select tag and the objective is when i choose an option from A i want another select options to display the sub contents of A stored in B what i know is contents=A.objects.all() and in html page {for content in contents} {{content}} but i dont know how to display the sub contents from B in an another option which changes the sub contents according to the first option please help me thanks in advance -
how handle high incoming data and sending throttled data to web sockets in django-channels
I am facing a problem in my django web server. We are using python3, django2, django-rest-framework3.8 and channels2.x Scenario is we are receiving DATA from a UDP connection at very fast rate (~100 messages per second). The data revived is in proto format (you can say we are receiving byte data). some data gets starved in this process as Rate of production >>> rate of consumption we are implementing throttling but still at 100 concurrent users data starves again. Can anyone help us in this scenario. If anyone has any new architecture idea please share. This is surely an interesting problem. This is about stock market feed PS :- I cannot post any code as it is my companies. but i can help any time you need clarification on any point. -
How to fix unexpected Django redirect
I've got an app called api in my Django project. It has one view, and thus one URL. When I call this endpoint when the development server is running locally, I get an unexpected redirect to the login page, which is part of a different project app called app. Note: I am NOT using the Django Rest Framework. I am running a Django 2.1 development server on 127.0.0.1:8000 with python manage.py runserver. I've attempted accessing the endpoint from different environments (Python requests, curl, Postman), and all have produced the same outcome. I have also tried shifting around the URL configs but to no avail. I am unaware of any other methods that may produce a different outcome. # api/views.py # this is a dummy view i have been using. the same result is produced # whether or not i use this dummy. def action(request, apitoken): return JsonResponse({'test': 'dummy'} # api/urls.py urlpatterns = [ path('test/<str:apitoken>', views.dummy, name='dummy'), ] # server logs at call "GET /api/test/testtoken?endpoint=testendpoint HTTP/1.1" 302 0 "GET /login/ HTTP/1.1" 200 4626 The endpoint should produce a JSON response of "{'test': 'dummy'}". It should not execute a redirection to the login view. To my knowledge, without the login_required decorator (or … -
Error while using django multiselectfield
I'm using django multiselectfield package and I'm encoutering a problem ValueError: not enough values to unpack (expected 2, got 1) What I know is that I have a problem in the MultiSelectFieldattribute choicesbut I can't figure out how to solve it. models.py class Meal(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.PROTECT) category = models.ForeignKey(MealCategory, on_delete=models.PROTECT) name = models.CharField(max_length=500) short_description = models.CharField(max_length=500) image = models.ImageField(upload_to='meal_images/', blank=False) price = models.IntegerField(default=0) #extras = models.OneToOneField('foodtaskerapp.Extra',related_name='is_extra' ,blank=True, null=True) extras = MultiSelectField(choices ='foodtaskerapp.Extra().get_extras()') def __str__(self): return self.name class Extra(models.Model): extra_n = models.CharField(max_length=200) meal = models.ForeignKey(Meal, on_delete = models.CASCADE, null=True, blank=True) extra_price = models.IntegerField(default=0) def __str__(self): return self.extra_n def get_extras(self): return self.extra_n -
Get a module not found when spinning up dev sever after adding new app to Django
I have created one app in Django successfully and linked it to the appropriate URLS and views but when I try to setup a second app, the dev server kicks back a "ModuleNotFoundError: No module named 'about'" error...not sure how to fix this. I have double checked the code many times to ensure the second app is written the same as the first app but it seems to be the same and the dev server still wont spin up. from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.about, name="About"), ] import django.shortcuts def about(request): return django.shortcuts.render(request, "about.html") urlpatterns = ( url(r'^admin/', admin.site.urls), url(r'^index/', include('index.urls')), url(r'^about/', include('about.urls')), -
Django CreateView not creating on submit of form
In my views.py: class DatasetRequestCreateView(CreateView): model = DatasetRequest form_class = DatasetRequestForm template_name = 'engine/datasetrequest_create.html' def get_success_url(self): return reverse("datasetrequest_detail", kwargs={ 'pk': str(self.kwargs['pk']), 'slug': str(self.kwargs['slug'])}) def form_valid(self, form): f = form.save(commit=False) f.creator = self.request.user f.save() # dsr = f.save() # dsr.votes.up(self.request.user.pk) return super(DatasetRequestCreateView, self).form_valid(form) def form_invalid(self, form): return self.render_to_response( self.get_context_data(form=form)) Page in question: http://datafix.io/dataset-request/create Log in with username "test" and password "djangohelp" or create your own account. To recreate the error, enter a title, description, and (int) reward and try to submit the form. It will basically just refresh the page without having created the form. DatasetRequestCreateView worked fine before I integrated django-wysiwyg with tinymce into the form. Not sure what is wrong. Docs are on their readme: https://github.com/pydanny-archive/django-wysiwyg Thank you in advance -
Remember me functionality(login page) in django
I am new to django, i tried to implement remember password functionality in my login page, i all-most browsed all the contents in internet, but i didn't get what exactly the functionality work in back-end. please help me guys. -
How can I use `email` in "django-rest-framework-simplejwt" instead of `username` to generate token?
In django-rest-framework-simplejwt plugin username and password are used by default. But I wanted to use email instead of username. So, I did like below: In serializer: class MyTokenObtainSerializer(Serializer): username_field = User.EMAIL_FIELD def __init__(self, *args, **kwargs): super(MyTokenObtainSerializer, self).__init__(*args, **kwargs) self.fields[self.username_field] = CharField() self.fields['password'] = PasswordField() def validate(self, attrs): # self.user = authenticate(**{ # self.username_field: attrs[self.username_field], # 'password': attrs['password'], # }) self.user = User.objects.filter(email=attrs[self.username_field]).first() print(self.user) if not self.user: raise ValidationError('The user is not valid.') if self.user: if not self.user.check_password(attrs['password']): raise ValidationError('Incorrect credentials.') print(self.user) # Prior to Django 1.10, inactive users could be authenticated with the # default `ModelBackend`. As of Django 1.10, the `ModelBackend` # prevents inactive users from authenticating. App designers can still # allow inactive users to authenticate by opting for the new # `AllowAllUsersModelBackend`. However, we explicitly prevent inactive # users from authenticating to enforce a reasonable policy and provide # sensible backwards compatibility with older Django versions. if self.user is None or not self.user.is_active: raise ValidationError('No active account found with the given credentials') return {} @classmethod def get_token(cls, user): raise NotImplemented( 'Must implement `get_token` method for `MyTokenObtainSerializer` subclasses') class MyTokenObtainPairSerializer(MyTokenObtainSerializer): @classmethod def get_token(cls, user): return RefreshToken.for_user(user) def validate(self, attrs): data = super(MyTokenObtainPairSerializer, self).validate(attrs) refresh = self.get_token(self.user) data['refresh'] = … -
Module Relationships, django
What i want to do, are to create two new models class ProduktGruppe_short(models.Model): a = models.IntegerField() b = models.IntegerField() class ProduktGruppe_long(models.Model): c = models.IntegerField() d = models.IntegerField() If I select long, in the Produkt Module. The module, will have an relationship to the ProduktGruppe_long module. If i select Short, it will haven an connection to the ProduktGruppe_short module. class MerkeNavn(models.Model): label = models.TextField(max_length=200, ) class Meta: abstract = True ordering = ['label'] class ProduktGruppe(models.Model): GROUP= ( ('1', 'Shoe'), ('2', 'Pants'), ) DIM= ( ('1', 'Long'), ('2', 'Short'), ) dim = models.CharField(max_length=4, choices=DIM, ) group = models.CharField(max_length=4, choices=GROUP, ) class Meta: abstract = True class Produkt(MerkeNavn, ProduktGruppe): class Meta: unique_together = ("label", "group", "dim") I need it to work well together whit Rest, since i will set up an API. I know the aproach is most likely wrong, but its the easiest way i could explain what i want to do. All help is apriciated ;) -
Error while using django-multiselectfield
While using multiselectfield package into my django app and while running makemigrations I had the following error : Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/pc/Desktop/code 2 copy/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/pc/Desktop/code 2 copy/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/Users/pc/Desktop/code 2 copy/venv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/pc/Desktop/code 2 copy/venv/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/pc/Desktop/code 2 copy/venv/lib/python3.5/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Users/pc/Desktop/code 2 copy/venv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked ImportError: No module named 'multiselectfield' I have followed all the instructions on doc and still don't know where is the problem.