Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framwork: DELETE without pk
I user Django Rest Framwork. I want to make a api for delete an object like this DELETE .../items/ to delete request.user's item. (Each user can create at most one item only, and only owner can delete his item.) I use mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet for list view and create. I have tried @action(methods=['delete'], detail=False, url_path='') def leave(self, request, *args, **kwargs): ... but url pattern will go: .../items/leave/$ How can I config the router or path for this? Thanks -
botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
I'm using django-dbbackup to back up my postgresql database to my s3 bucket. It's connected to my S3 bucket via the following settings: draft1.settings.py DBBACKUP_STORAGE = 'draft1.aws.utils.BackupRootS3BotoStorage' DBBACKUP_S3_BUCKET = AWS_STORAGE_BUCKET_NAME DBBACKUP_S3_ACCESS_KEY = AWS_ACCESS_KEY_ID DBBACKUP_S3_SECRET_KEY = AWS_SECRET_ACCESS_KEY draft1.aws.utils BackupRootS3BotoStorage = lambda: S3Boto3Storage(location='backup') Bucket policy { "Version": "2012-10-17", "Statement": [ { "Sid": "Allow All", "Effect": "Allow", "Principal": "*", "Action": [ "s3:GetObject", "s3:PutObject" ], "Resource": "arn:aws:s3:::****-bucket/*" }, { "Sid": "Deny All Actions On All But Media and Static Unless Defined User", "Effect": "Deny", "NotPrincipal": { "AWS": "arn:aws:iam::********:root" }, "Action": "s3:*", "NotResource": [ "arn:aws:s3:::****-bucket/media/*", "arn:aws:s3:::****-bucket/static/*", "arn:aws:s3:::****-bucket/media_thumbnail/*" ] } ] } As you can see I'm trying to back it up to the backup folder. Full error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/zorgan/postr/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/zorgan/postr/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/zorgan/postr/env/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/zorgan/postr/env/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/zorgan/postr/env/lib/python3.5/site-packages/dbbackup/utils.py", line 116, in wrapper func(*args, **kwargs) File "/home/zorgan/postr/env/lib/python3.5/site-packages/dbbackup/management/commands/dbbackup.py", line 61, in handle self._save_new_backup(database) File "/home/zorgan/postr/env/lib/python3.5/site-packages/dbbackup/management/commands/dbbackup.py", line 88, in _save_new_backup self.write_to_storage(outputfile, filename) File "/home/zorgan/postr/env/lib/python3.5/site-packages/dbbackup/management/commands/_base.py", line 88, in write_to_storage self.storage.write_file(file, path) File "/home/zorgan/postr/env/lib/python3.5/site-packages/dbbackup/storage.py", line 82, in write_file self.storage.save(name=filename, content=filehandle) File "/home/zorgan/postr/env/lib/python3.5/site-packages/django/core/files/storage.py", line 54, in … -
How to serve React app AND Django blog from Nginx?
I'm using nginx to serve a Django blog from http://dendro.com.au/blog and a React app from http://dendro.com.au. I'm also using nginx to redirect all http to https. The problem is some weird behaviour... If I navigate to the blog with a clear cache, it shows the blog. If I then navigate to the index page it shows the react app. All good so far. But then, if I return to http://dendro.com.au/blog it continues to show the react app, not the blog! I think the problem involves caching, but I'm not sure where. I am not using react-router, so the urls so I'm not sure how the urls could get redirected on the client side. Here is my nginx config: server { listen 80; server_name dendro.com.au www.dendro.com.au; return 301 https://$server_name$request_uri; } server { listen 443 ssl; server_name dendro.com.au www.dendro.com.au; root /production_build; location /static/ { root /var/www/dendro; } location /blog { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://dendro; } location /cms { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://dendro; } location / { try_files $uri /index.html; } } -
Django ModelForm center labels on the top of already centered inputs
Hi I am trying to display labels above already centered inputs, how would I go about this? I am not quite sure how to for loop through the labels and then align them above. I am new to Django and not sure how to use the for loop template tags properly in the HTML, thanks for your time :). from django.db import models from django.forms import ModelForm from django.forms import modelformset_factory # Create your models here. # Model Sign up starts here. class ModelRegister(models.Model): name = models.CharField(max_length=356) lastname = models.CharField(max_length=356) email = models.EmailField(max_length=356) password = models.CharField(max_length=356) password_conf = models.CharField(max_length=356) phone_number = models.CharField(max_length=356) # ModelForm Sign up starts here. class RegisterForm(ModelForm): class Meta: model = ModelRegister fields = ['name', 'lastname', 'email', 'password', 'password_conf', 'phone_number',] labels = { 'name' : 'Name', 'lastname' : 'Last Name', 'email' : 'Email', 'password' : 'Password', 'password_conf' : 'Confirm', 'phone_number' : 'Phone Number', } class Media: css = { '__all__' : 'Register_style_sheet.css' } -
django: google ouath redirects to login page requires username and password
I am trying to implement google login in django. I am using the sample code from https://github.com/google/google-api-python-client/tree/master/samples/django_sample My googleauth app's models.py from django.contrib import admin from django.contrib.auth.models import User from django.db import models from oauth2client.contrib.django_util.models import CredentialsField class CredentialsModel(models.Model): id = models.ForeignKey(User, primary_key=True, on_delete=models.CASCADE) credential = CredentialsField() class CredentialsAdmin(admin.ModelAdmin): pass my apps's views from django.shortcuts import render import os import logging import httplib2 from googleapiclient.discovery import build from django.contrib.auth.decorators import login_required from django.http import HttpResponseBadRequest from django.http import HttpResponseRedirect from django.shortcuts import render from .models import CredentialsModel from project import settings from oauth2client.contrib import xsrfutil from oauth2client.client import flow_from_clientsecrets from oauth2client.contrib.django_util.storage import DjangoORMStorage # CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this # application, including client_id and client_secret, which are found # on the API Access tab on the Google APIs # Console <http://code.google.com/apis/console> FLOW = flow_from_clientsecrets( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scope='https://www.googleapis.com/auth/plus.me', redirect_uri='http://localhost:8000/oauth2callback') @login_required def index(request): storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("plus", "v1", http=http) activities = service.activities() activitylist = activities.list(collection='public', userId='me').execute() logging.info(activitylist) return render(request, 'plus/welcome.html', { 'activitylist': activitylist, }) … -
How to enable frontend editing in Django CMS?
How exactly do I enable front end editing in Django CMS 3.5.2? I added this to the top of my template: {% load cms_tags menu_tags sekizai_tags static %} and I added {% placeholder "content" %} to the body. This works in the sense that I can use it in the structure toolbar but it doesn't show up as an editable field when I hover the mouse over it. I don't want to use {% render_model ... %} as I'm not creating a new model. I know how to use Django but its not helping me much here as DjangoCMS doesn't make it obvious what variables are passed into the template. Please, How do I go about this? -
static files not loading only on django admin page
This is on a production server with DEBUG = False. My static files will load on the home page but not the admin page. It gives me a error 404 in the browser console. This only happens on the admin page. I've checked to make sure that the .css files are in the specified directory's and they are along with the code inside them. NOTE: The same server and file structure was working earlier. I've tried almost everything I can think of any help would be greatly appreciated! -
analysis django input form
i m a new to django i first created a project so i can translat the form input and display it in my app (the translation algorithm is all set ) the form view template are all set i imported multiple py files that contains the translation code to views.py in "views.py" i have this : from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import PhraseForm import re import string import sys import argparse from . import normalize from .stemming import ArabicStemmer from . import stem_const def get_phrase(request): form = PhraseForm(request.POST) als = ArabicStemmer(); text = u"" var = u"" ana = u"" # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required texte = form.cleaned_data['ma_phrase'] words = normalize.normalize_searchtext(text) words = words.split() for word in words: als.light_stem(word) ana = als.traduction(word) var = ana +' ' envoi = True return render(request , 'webapp/head.html', locals()) envoi is passed to the front end the issue is with 'var' any clue please help -
Django persist ModelMultipleChoiceField selections
I have a ModelMultipleChoiceField that allows a user to select one or more of a set of my "community" model (akin to a user joining a subreddit). When the user reopens the page to select communities, there are no checkboxes on the fields that the user has selected before. I would like to make it so that previously selected communities stay with check boxes, and therefore when the user hits submit their previous choices won't be forgotten if they don't reselect the previous choices. Here is my form: class CustomChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return obj.name class CommunitySelectForm(forms.ModelForm): community_preferences = CustomChoiceField(queryset=Community.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model= UserQAProfile fields = ['community_preferences'] And here is my template: <div class="col-sm-8 input"> <form method="post" enctype='multipart/form-data'> {% csrf_token %} {{ form.as_p }} <input class="btn btn-submit pull-left" type="submit" value="Choose Communities" /> </form> </div> The UserQAProfile model has a ManyToMany field to store the preferences: community_preferences = models.ManyToManyField(Community) -
Django fake registrations on the app. Is this hacker activity?
We are two people working on a startup based in India. The MVP is not yet complete. So, there is no way for others to know about the website being built and its address. But the past two days I have observed fake registrations on the webApp: The other person says he have no Idea. Is this hacker activity? If it is,then what am I supposed to do? I don't like to use CAPTCHA. Moreover, I feel this as hacker activity because the registrants have not yet confirmed their email address neither did they login since. Please help. -
Django MultipleChoiceField not showing saved choices
This is what my form looks like. class DecisionMadeForm(forms.ModelForm): option = forms.MultipleChoiceField(required=False, label = "Which option(s) did you choose? (Please check ALL that apply)") class Meta: model = Decision_Made fields = ('option', ) def init(self, *args, **kwargs): dec_id = kwargs.pop("dec_id") choicelist = kwargs.pop("choicelist") super(DecisionMadeForm, self).init(*args, **kwargs) instance = getattr(self, 'instance', None) query = Solution_Options.objects.filter(dec_id = dec_id, archived = 'N').values_list('option', flat=True).distinct() query_choices = [(id, id) for id in query] self.fields['sol_option']=forms.MultipleChoiceField(choices=query_choices, required=False, widget=forms.CheckboxSelectMultiple,label="Which choice did you make?") if self.instance: self.fields['sol_option'].initial = choicelist In my views.py def decision_made(request): try: dec_made = Decision_Made.objects.get(dec_id = dec_id) except ObjectDoesNotExist: REDIRECT TO DIFFERENT PAGE if request.method == 'POST': decmadeform = DecisionMadeForm(request.POST, instance=dec_made, dec_id=dec_id, optionlist = dec_made.option) if decmadeform.is_valid(): id = decmadeform.save(commit=False) ... else: decmadeform = DecisionMadeForm(instance=dec_made, dec_id = dec_id, optionlist = dec_made.option) All the choices are stored successfully in the database. But no matter what I do I cannot display it on the screen. I have tried all the suggestions given in stack overflow and nothing has worked. Any help would be much appreciated! -
Django ModelForm update don't work
Hi I have problem with ModelForms. When I'm trying update object form two classes using transaction nothing happening. My form class: class TeamForm(forms.ModelForm): employers = forms.ModelMultipleChoiceField(queryset=Employer.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Team fields = '__all__' My model classes: class Team(models.Model): name = models.CharField(default='Team', max_length=100, unique=True) def __str__(self): return self.name class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) team = models.ForeignKey(Team, on_delete=models.SET_NULL, null=True) team_leader = models.BooleanField(default=False) project_menager = models.BooleanField(default=False) # project_id = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True) hourly_rate = models.IntegerField(default=0) working_time = models.FloatField(default=0.0) def __str__(self): return self.user.first_name + ' ' + self.user.last_name and finally my view: def TeamUpdateView(request, pk): if request.method == 'POST': team_form = TeamForm(request.POST) if team_form.is_valid(): with transaction.atomic(): team = Team.objects.filter(pk=pk).update(name=str(team_form['name'].value())) for e in team_form['employers'].value(): Employer.objects.filter(pk=e).update(team=team) print(team_form.errors) return redirect('resources:ResourcesListView') else: team = get_object_or_404(Team, pk=pk) team_form = TeamForm(initial={'name': team.name}) # milestone_form = MilestoneForm() context = {'team_form': team_form, 'form_pk': pk} # , 'milestone return render(request, 'resources/resources_edit_modal.html', context) When i print form error i can see somethings like this: <ul class="errorlist"><li>name<ul class="errorlist"><li>Team with this Name already exists.</li></ul></li></ul> -
whitenoise not adding random string
I just put up another copy of my Django app in production. The only intended difference between my "old" app and the "new" one is that the old app runs in "traditional" Heroku, and the new app runs in "Dockerized" Heroku. The weirdest thing is happening. I use Whitenoise to serve my static assets. On the older app, links to my static assets look like this in the generated pages: <link href="/static/assets/css/bootstrap.min.9f236e18d5bf.css" rel="stylesheet"> But on my new app, that little string (9f236e18d5bf) is missing. it looks like: <link href="/static/assets/css/bootstrap.min.css" rel="stylesheet"> As a result, I don't have any stylesheets on my new site. Is there an additional step that I have to take in the Dockerized version to get this to work? Or am I missing some combination of STATIC* settings values that are needed. My temporary workaround was to add python manage.py collectstatic --noinput to Dockerfile.web, and then set: STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' Which works, but I'm wondering if I'm going to get a scaling issue on Monday. -
Redirect with additional context django
I have this view where i needed two models Book and UserFav so I used context for that: class BookDetailView(LoginRequiredMixin, generic.DetailView): model = Book template_name = 'book_detail.html' def get_context_data(self, **kwargs): context = super(BookDetailView, self).get_context_data(**kwargs) context.update({ 'fav_list': UserFav.objects.filter(user=self.request.user) }) return context and another view function def favorite(request, pk): book = get_object_or_404(Book, pk=pk) fav, created = UserFav.objects.get_or_create(user=request.user) fav.favorites.add(book) return render(request, 'book_detail.html', {'book': book}) form for the favourite function <form action="{% url 'favorite' book.id %}" method="post" style="display: inline;"> {% csrf_token %} <button type="submit" class="btn btn-danger btn-xs"> <span class="glyphicon glyphicon-remove"></span>&nbsp; add this book to favourite </button> my url url(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'), url(r'^book/(?P<pk>\d+)/f/$', views.favorite, name='favorite'), now the problem is that when i get redirected to book_detail.html I am not getting the fav_list which is needed for the template How do I redirect properly or use some other way to define views? -
Django REST API Generics displaying improperly
Currently using a REST API and the generic views CreateUpdateDestroy, and my admin display GUI looks like this : All the sources online that I've followed, tutorials etc get a generic view which looks much nicer. Here is my views.py: from rest_framework import generics from models import Results from serializers import ResulutsSerializer class ResultsList(generics.ListAPIView): queryset = Results.objects.all() serializer_class = ResultsSerializer class ResultsDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Results.objects.all() serializer_class = ResultsSerializer and urls.py: from django.urls import path from main import views urlpatterns = [ path('results/', views.ResultsList.as_view()), path('<int:pk>/', views.ResultsDetails.as_view()) ] what am I doing wrong? -
Elasticsearch with django-haystack run update index automatically
I am developing a open blogging website, for its search functionality I am using Elastic search with django-haystack but the problem is after every blog post I need to run the command - python manage.py update_index, how to make update_index automatically ? and could you please tell me if site has millions of posts then, Is this a good idea or it will crash my site because I need to refresh index every time, I am newbie please tell me the correct way for heavy search. What search technologies does instagram and other social websites uses. -
django NoReverseMatch Exception
I'm getting this error while using hyperlink in django. ** error** django.urls.exceptions.NoReverseMatch: 'mywebapp' is not a registered namespace mywebapp/template/about.html .. <body> <a href="{% url 'mywebapp:home' %}">Click here</a> Hello World!!!<p>Today is {{today}}</p> mywebapp/template/home.html .. <h4>Homepage.</h4> settings.py .. INSTALLED_APPS = [ .. 'mywebapp'#new .. ] -
Vue.js + vue.router + history mode + Django = Error
When im using publicPath: '/static/' in my webpack config, my vue app runs fine on a Django Webserver (both dev and production). however now im trying to use history mode, i have to change the publicPath to "/" otherwise the url always gets a "/static/" inbetween the domain and actual target. The Vue dev server still runs fine, however both production and development Django server give me these errors in the browser console: Uncaught SyntaxError: Unexpected token < Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://127.0.0.1:8000/6.01a214ce.css". i tried several different solutions like: publicPath: './' assetsPublicPath: '/static/' inside base html (gave me an error on compilation) Does anybody have an idea how i can resolve this issue ? -
ValueError at /accounts/signup/
this is my signup view -> def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) print('hello') if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) account = Account(user=user) account.save() login(request, user) return redirect('/gallery/index') else: form = UserCreationForm() return render(request, 'accounts/signup.html', {'form': form}) this is my accounts model -> class Account(models.Model): user = models.OneToOneField(User, related_name="profile",on_delete=models.CASCADE) following=models.ManyToManyField(User,related_name="followers",null=True,blank=True) this is the error I am getting - The view accounts.views.signup didn't return an HttpResponse object. It returned None instead. I am getting this error whenever I submit the form. I am using the django admin signup form by default -
django clone repo is not working
I clone a Django project from github. But when I ran the python manage.py runserver it showed the following errors. How to fix them? python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/human-inside/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/human-inside/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 303, in execute settings.INSTALLED_APPS File "/home/human-inside/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/home/human-inside/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/home/human-inside/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/human-inside/Desktop/web_project/parsifal/settings.py", line 18, in <module> default = config('DATABASE_URL')) File "/usr/local/lib/python2.7/dist-packages/decouple.py", line 198, in __call__ return self.config(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/decouple.py", line 77, in __call__ return self.get(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/decouple.py", line 64, in get raise UndefinedValueError('%s option not found and default value was not defined.' % option) decouple.UndefinedValueError: DATABASE_URL option not found and default value was not defined. -
Python 3.7, Failed building wheel for MySql-Python
I am new to python and I am trying django framework that involves some MySql and ran into this error when try to do pip install mysqlclient and down the lines of cmd messages I got this. ---------------------------------------- Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command c:\users\ronanl~1\envs\py1\scripts\python.exe -u -c "import setuptools, tokenize;file='C:\Users\RONANL~1\AppData\Local\Temp\pip-install-pkbqy3t3\mysqlclient\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\RONANL~1\AppData\Local\Temp\pip-record-moxwf7lu\install-record.txt --single-version-externally-managed --compile --install-headers c:\users\ronanl~1\envs\py1\include\site\python3.7\mysqlclient: running install running build running build_py creating build creating build\lib.win32-3.7 copying _mysql_exceptions.py -> build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building '_mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,3,13,'final',0) -D__version__=1.3.13 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include" "-Ic:\users\ronan lina\appdata\local\programs\python\python37-32\include" "-Ic:\users\ronan lina\appdata\local\programs\python\python37-32\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.14.26428\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft … -
Allow New Consumer To See Existing Data in Django Channels Layer
Im using Django Channels (and loving it) but new consumers to the layer only see data from the time they join into the future. Is there a way for new consumers to see previous data belonging to the layer? -
how can i call MySQL stored procedure from django?
I am a beginner to Django. I tried to call the stored procedure from django with the cursor but failed. with connection.cursor() as cursor: cursor.callproc('check_schedule', [new_sch.bus_id, new_sch.depart_time, new_sch.arrive_time, 0]) if cursor.return_value == 1: result_set = cursor.fetchall() cursor.close() -
Can't log in super users created on the django admin backend
I'm trying to create superusers on the django admin backend, but somehow I can't get them to log in. Here's my user class, class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, max_length=255) mobile = PhoneNumberField(null=True) username = models.CharField(null=False, unique=True, max_length=255) full_name = models.CharField(max_length=255, blank=True, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() Here's the UserManager function to create super user, def create_superuser(self, email, username, password=None): user = self.create_user( email, username=username, password=password, is_staff=True, is_superuser=True, is_active=True, ) user.save(self._db) return user Here's the relevant backend settings. OAUTH2_PROVIDER = { # this is the list of available scopes 'ACCESS_TOKEN_EXPIRE_SECONDS': 60 * 60 * 24, 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}, 'OAUTH2_BACKEND_CLASS': 'oauth2_provider.oauth2_backends.JSONOAuthLibCore', } AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) # REST Framework REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } I'm checking the is_staff and is_superuser to true on the creation form, still nothing. The created super user can't log in on the admin backend. What am I doing wrong here. -
How to add another field in connection with a ManyToManyField?
class Team(models.Model): college = models.CharField(max_length=20) image = models.FileField(upload_to='documents/',null=True) def __str__(self): return self.college class Athletics(Match): time = ? player = models.ManyToManyField(Player, related_name='player') game_level = models.CharField(max_length=256, null=True, choices=LEVEL_CHOICES) # like semi-final, final etc game_specific = models.CharField(max_length=256,null=True, choices=EVENT_CHOICES) #like Men's Shot Put or Men's Triple Jump etc def __str__(self): return str(self.game_level) I am making an Athletics Sports Model for an sports tournament. I have an existing Player Model where i have listed playes names and their teams. Now as you can see i have added player field as ManyToManyField to choose for say 4-5 players match. Now i need finishing time for each player for judging who qualifies for the next round, can it be possible to do this in this model only? Or i have to add another model? Help me!