Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to associate “owner” with default User model?
I’m trying to teach myself Django and the Django Rest Framework, but I'm having a hard time understanding how object ownership is defined. I want to apply the custom “IsOwnerOrReadOnly” permissions given in the DRF documentation with the default User model. My goal: Users will be able to PUT/PATCH/DELETE the information in their own account, but won't be able to change any other users’ information. My user serializer: class UserSerializer(serializers.ModelSerializer): rides = serializers.PrimaryKeyRelatedField(many = True, queryset = Ride.objects.all()) class Meta: model = User fields = [ 'pk', 'username', 'first_name', 'last_name', 'email', 'password', 'rides' ] write_only_fields = ['password'] read_only_fields = ['pk', 'username'] The IsOwnerOrReadOnly code: class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user The problem is with the line return obj.owner == request.user. It always returns AttributeError: 'User' object has no attribute 'owner’. Why is the "owner" of a user not the user itself? How can I say “owner = this object” so that my permissions classes work? Follow-up question: I would like to eventually extend the default User model to add more fields. Would my permissions still work if I made a new User model by inheriting from AbstractBaseUser? (I just … -
Getting error while playing video in django web app
I am creating a video streaming website like youtube in django and I am getting the following error while playing videos and when forword the running video. [enter image description here][1] -
How to run django app in heroku with DEBUG=False
I know this may be asked before, but I have tried a lot to get it right but it just won't. I have tried setting DEBUG=False and then setting ALLOWED_HOSTS = ['*'] as many posts here o SO and on medium suggested. please help me get this to work or link to a recent answer that got it right. I have django_herokuu installed already. Below is my settings.py file. When I run it like that I get a 500 error DEBUG = False ALLOWED_HOSTS = ['*'] -
How i can open my django adminstration page again?
I created a django project in my linux terminal and i reached the step that django adminstration page after that i closed the page. Now, i don't know that how i will open that adminstration page again and to make something on my project? -
Where to creat forms an models
Is it a best way to create only one file of forms and one files of models in the folder of the project django? Create for each application one forms.py and one models.py is too long. -
Django how update page after receiving POST request?
I'm new with Django. I would like to update the page in the browser each time a POST request is received by the app. By the moment, I send POST request with POSTMAN. At the end, it is another webserver which will send data through POST request. I don't find any solution to do this. This the code in my view : @csrf_exempt def prem(request): if request.method == 'GET': print("GET") context = {'contenu': request.GET.get("request_received", "nothing") } elif request.method == 'POST': print("POST") datar = request.GET.get('request_received','rien') context = { 'request_received' : datar } return render(request, 'polls/seco.html', context) Code in my template : {% if request_received %} {% csrf_token %} <p>Message received from POST request : {{ request_received }}</p> {% endif %} Someone could help me ? -
Django login user=username never true
I am having problems with my Django login. The below if statement (if user is not None:) always resolves as false, so it moves onto the else. I'm not sure why and I would appreciate any help Thanks VIEWS.PY def index(request): return render(request, 'home.html', {}) def login_user(request): if request.method == 'POST': user = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=user, password=password) if user is not None: login(request, user) messages.success(request, ('You are logged in')) return redirect('index') else: messages.success(request, ('Login failed')) return redirect('login') else: return render(request, 'login.html', {}) And here is the login form: <form name="form1", id="form1" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" id="user" aria-describedby="emailHelp" placeholder="Enter email"> </div> <div class="form-group"> <input type="password" class="form-control" id="password" placeholder="Password"> </div> <button type="submit" class="btn btn-danger">Login</button> </form> -
How to parse request in view.py in Django API?
I want to pass two parameters to the end-point of my Django API. This is the first Django API that I am doing. Currently I hardcoded the input parameters in data = {'param1':[0.4],'param2':[0.9]}. Then I want to be able to call this end-point as follows http://localhost:8000&lat=50&param2=30 How should I update this code of view.py in order to obtained the desired functionality? from django.http import HttpResponse import pandas as pd import json # used to export a trained model from sklearn.externals import joblib def index(request): decision_tree = joblib.load('proj/model/decision_tree.pkl') # now I manually pass data, but I want to get it from request data = {'param1':[0.4],'param2':[0.9]} test_X = pd.DataFrame(data) y_pred = decision_tree.predict(test_X) response_data = {} response_data['prediction'] = y_pred response_json = json.dumps(response_data) return HttpResponse(response_json) -
Issues opening static files using djnago in BeaverDam
I am trying to use the video annotation tool BeaverDam to annotate a static video offline. https://github.com/antingshen/BeaverDam I have a video file 0.mp4 in the directory '/home/arl/BeaverDam/annotator/static/videos' I then included the STATICFILES_DIRS in the setup file: https://github.com/antingshen/BeaverDam/blob/master/beaverdam/settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "annotator/static/") STATICFILES_DIRS = ("/home/arl/BeaverDam/annotator/static/videos", ) I have not been able to view the static folder in the URL. Tried options like localhost:5000/annotator/static/ localhost:5000/annotator/static/videos Any help will be highly appreciated -
How to send password reset email from Django using django-rest-auth and Mailgun
I'm setting up user authentication in Django with Django rest auth. Most things are working well but I can't get the password reset emails to send, either in the dummy backend or with Mailgun. I have an account with Mailgun and am trying to use the sandbox to send mails. # api/urls.py from django.urls import include, path urlpatterns = [ path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('users/', include('users.urls')), ] I'm requesting a password reset for a registered user via the browsable API form: http://127.0.0.1:8000/api/v1/rest-auth/password/reset/ I enter an email address in the form and press 'POST'. The page displays this: POST /api/v1/rest-auth/password/reset/ HTTP 200 OK Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Password reset e-mail has been sent." } However the email is not sent! The mailgun logs show no activity - no email has been sent. When I look on the Network tab in the browser, I don't see a post request. Here's my setup using Mailgun: EMAIL_HOST = 'smtp.mailgun.org' EMAIL_PORT = 587 EMAIL_HOST_USER = 'postmaster@sandboxxxxx.mailgun.org' EMAIL_HOST_PASSWORD = 'xxxx' EMAIL_USE_TLS = True (I've put my real sandbox and password in the actual file) First, with this in settings.py: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' I expect the email text to be logged to … -
Django - Update foreign keys to BigAutoField using makemigrations
I had a model with this code: class Author(models.Model): id = models.AutoField(primary_key=True) name= models.CharField(max_length=100) And I have this other model that uses the model above: class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.PROTECT) But, because a integration with other database that I had to do, the id of the Author became a very big integer. So, I had to change the id of Author from models.AutoField() to models.BigAutoField(). Almost everything went Ok. But the field "author" in "Book" continues to be a normal Integer field. And now I'm having problems when I try to insert new Books from an Author because some author's ID's are too big. I found a solution, but it's impracticable in my current database because in other Models I have the same situation of this one. I tried to run django's makemigrations and migrate but even after the fields changes he doens't update the table structure. Please, Is there anything that I can do? -
ModelForm - Access fields in clean()
Giving the the following Model and a ModelForm, how would i get 'Title' in clean()? https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#overriding-modelform-clean-method "A model form instance attached to a model object will contain an instance attribute that gives its methods access to that specific model instance." But 'self.instance.Title' returns "None", even if the field has a value. class Book(models.Model): Author = models.CharField() Title = models.CharField() class Author_Form(forms.ModelForm): Author = forms.CharField() class Meta: model = Book fields = ['Author',] def clean(self): Title = self.instance.Title Author = self.cleaned_data.get("Author") -
Django can't populate table rows on loop every x seconds with jquery post
I want to repopulate my table every few seconds to see what clients are doing on our servers. I'm new to Django but I've managed to stand this project up on a remote server through SSL. I need to request this information and then send back the list for table. I've gotten 404 forbidden errors, errors related to not being able to find the function, ect. Currently, I have the information being fetched but its refreshing the entire page rather than the table rows. This is obviously because I was using: **setInterval(function() { document.getElementById('jobs').submit() }, 5000);** Which I'm trying to avoid Views.py (part of it) class ActiveServerJobsView(LoginRequiredMixin,generic.ListView): template_name = 'project_name/active_server_jobs.html' context_object_name = 'current_job_list' def post(self, request): if request.method == "POST": db_default = connections['default'] default_cursor = db_default.cursor() default_cursor.execute("select server_name from table_name where server_is_database = True") host_list = default_cursor.fetchall() current_job_list = get_current_jobs(host_list) args = {'current_job_list': current_job_list} return render(request,'project_name/active_server_jobs.html',args) def get_queryset(self): db_default = connections['default'] default_cursor = db_default.cursor() default_cursor.execute("select junk, and, stuff from table_name where server_is_database = True") host_list = default_cursor.fetchall() return get_current_jobs(host_list) def get_current_jobs(host_list): current_jobs = [] for host in host_list: host_name = host[0] host_db = connections[host_name + "/example"] host_cursor = host_db.cursor() #get file jobs host_cursor.execute("select junk, and, stuff") host_file_list = host_cursor.fetchall() for … -
How to POST a form with Django and not reload the page
I'm working on an app where the user will submit a value and I want to hide the div containing the form on submit and display a div containing the results. The goal is to have them submit the form and display a different hidden div. What am I doing wrong with either the Django code or Javascript? views.py from django.shortcuts import render from .models import VintageMac from .forms import VintageMacForm def home(request): if request.method == "POST": form = VintageMacForm(request.POST) if form.is_valid(): form.save() form = VintageMacForm() else: form = VintageMacForm() return render(request, 'hmwypapp/index.html', {'form': form}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ] models.py from django.conf import settings from django.db import models from django.utils import timezone from django import forms class VintageMac(models.Model): price = models.IntegerField() def publish(self): self.save() def __str__(self): return '%s' % (self.price) forms.py from django import forms from .models import VintageMac class VintageMacForm(forms.ModelForm): class Meta: model = VintageMac fields = ('price',) HTML <div id="submission1"> <p class="card-text">Some quick example text to build on the card title.</p> <div class="bottom"> <div class="row"> <form action="/create_post/" class="w-100" method="POST" id="form1"> <div class="col-12"> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor … -
Django admin custom queryset for a custom action
I am a bit lost on how to perform a specific queryset in django admin. Below are my models. class People(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=35) phone_number = models.CharField(null=True, blank=True, max_length=15) def __str__(self): return self.first_name class Meta: verbose_name_plural = 'People' class Group_and_message(models.Model): name = models.CharField(max_length=30, null=True) people = models.ManyToManyField(Person) message_body = models.TextField(max_length=140) updated = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return self.name In Admin, I have created a custom action. def send_message(modeladmin, request,queryset): pass My question is to be able, when selecting a "group_and_message" object in the admin dashboard via the checkbox, be able to retrieve "id" and "phone_number" of the selected object so i can use it to perform "send_message" custom action. Below is the equivalent of basic of a few queryset steps that showcase what i am trying to achieve(just for illustration purpose) g = Group_and_message.objects.last() #self instead of last is what i want; g1 = g.people.all() g2 = g1.values_list("id","phone_number"); g3 = dict(g2) The result gives me the "id" and "phone number". Any help would be much appreciated. -
How to add an image to a jinja html page
I'm just learning the basics of django and jinja. I've extended my header file and now I want to add an image to the page, but I don't know the jinja syntax for doing that. Please assist. {% extends "media/header.html" %} {% block content %} This is where I would like to insert my image. {% endblock %} -
TinyMCE HTMLField not works with extra defined language
I have this in models.py: from django.db import models from tinymce import models as tinymce_models class Article(models.Model): title = models.CharField(max_length=50) content = tinymce_models.HTMLField(verbose_name=_('Content')) Also, I determined english, russian and uzbek languages in settings.py using EXTRA_LANG_INFO. TinyMCE configurations in settings.py: TINYMCE_DEFAULT_CONFIG = { 'theme': "advanced", 'relative_urls': False, # default value 'width': '100%', 'height': 300, 'plugins': "table,spellchecker,paste,searchreplace" } TinyMCE works good for already defined languages in package (for english and russian in my case), works fine in admin (https://imgur.com/a/AgaH2de) But its not displays text field in admin for extra added language (https://imgur.com/a/k3LQl7y) How to fix this problem? Thanks. -
Find average after annotation subtract without aggregate Django-rest-framework
I have a lot of querys that want to return in a single request, I have a query with an aggregate and when we concat the queryset with this function and try to serialize the function returns an error: ['All items in the ConversasAPIViewSet querylist attribute should contain a queryset key'] Is there any kind of solution for this problem? APIViewSet: class ConversasAPIViewSet(ObjectMultipleModelAPIViewSet): kpiDTO = KpiDTO(6) json = Conversas.objects.values('nome' ).annotate(deltaTime = (Max('data') - Min('data')) ).aggregate(tempoMedioTotal=Avg('deltaTime')) qtdUsuariosMes, qtdMensagensMes, fraseIntentEntity, tempoMedioTotal = kpiDTO.retornaDTO() querylist = [ {'queryset': qtdMensagensMes, 'serializer_class': QuantidadeMensagensMesSerializer, 'label': 'qtdMensagensMes'}, {'queryset': qtdUsuariosMes, 'serializer_class': QuantidadeUsuariosMesSerializer,'label': 'qtdUsuariosMes' }, {'queryset': fraseIntentEntity, 'serializer_class': EntidadeIntencaoSerializer, 'label': 'fraseIntentEntity'}, {'queryset': json , 'serializer_class': TempoMedioSerializer, 'label': 'tempoMedio'} ] Serializer: class TempoMedioSerializer(serializers.Serializer): tempoMedioTotal = serializers.CharField() -
How to create online SQL compiler using Django [on hold]
I'm trying to create an online compiler of SQL where one can practice SQL queries. I'm using Django for this purpose can some tell me what should be the flow of the wbsite . I need some clear idea of what to use and how to use(in implementation) Thanks in advance -
How can Import a csv file into a Django project?
I can't import a csv file into my Django project. I have a code that is already working that basically takes a csv file and output spendings on different categories (using pandas). I'm learning Django right now and I'm trying to include that code into my project. But everytime I try to run in it says 'No module named StatementOCTRev'. I'm not sure if it's a directory thing or a pandasXdjango thing. I tried different approaches but none of them work. That led to an ugly code. So I apologize. Anyway here is my view.py: from django.shortcuts import render, get_object_or_404 from .models import Post from .budget import Categorize, Spending import numpy as np import pandas as pd import csv import mysite.StatementOCTRev from import_export import resources #import # Create your views here. def home(request): posts = Post.objects return render(request, 'mysite/home.html', {'posts':posts}) def post(request,post_id): ################################ coffeelist = ["WING", "COSTA", "CAFFEINE", "PASSO", "LA FELICE", "GULLUOGLU", "CARIBOU", "ARK COFFEE"] restlist = ["TALABAT", "SOLO", "MELENZANE", "PIZZA", "HARDEES", "HARDEE'S", "MCDONALDS", "GULF ROYAL", "SARAY", "Carriage"] gaslist = ["KNPC", "OULA", "ALFA"] read = pd.read_csv('StatementOCTRev.csv', encoding="ISO-8859-1") # Read CSV # create a new dataframe df = pd.DataFrame(columns=["Date", "Reference", "Debit", "Credit", "Balance"]) df['Date'] = read.iloc[:, 0] df['Reference'] = read.iloc[:, 1] … -
How to fix "config for 'compressor' " error in Django
I'm following the Django-SHOP tutorial https://django-shop.readthedocs.io/en/latest/tutorial/intro.html#tutorial-populate-database-fixtures. After successfully declaration of demo implementation I tried running my app. I got the traceback: [2018-12-28 18:21:07,071 exception] ERROR: Internal Server Error: / Traceback (most recent call last): File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 109, in get_exception_response response = callback(request, **dict(param_dict, exception=exception)) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/views/defaults.py", line 45, in page_not_found body = template.render(context, request) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/backends/django.py", line 66, in render return self.template.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 207, in render return self._render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/var/www/vhosts/Tutorial/shoptutorial/local/lib/python2.7/site-packages/django/template/base.py", … -
Django - Store the language of user in database
I am able to change the language of the user with built-in function of django path('i18n/', include('django.conf.urls.i18n')), In order to send email to user translated in his language, I want to know the activated language of the user. How can I save the language of the in db? Is there another way to know the language? This is the session: from django.utils import translation request.session[translation.LANGUAGE_SESSION_KEY] -
How can I not display 'Id:' when I render my form? (same as 'ParentClass ptr:')
I have made a form (Formset actually) with modelformset_factory. I display it with <form method="post" action=""> {% csrf_token %} {{ player_formset.management_form }} {% for player_form in player_formset %} {% for field in player_form %} {{ field.label_tag }} {{ field }} {% endfor %} <br> {% endfor %} <input type="submit" value="Aggiungi"> </form> When it render automatically adds a field with the write 'Human ptr:' (because my model, Player, is a subclass of Human... if I use directly Human he shows me 'Id:', the title is just to generalize the problem). How can I delete this write? I tried: 1) to use in html file the tag {% forloop.last %} but actually the last field is 'Delete:' checkbox (if I use can_delete=False it works, but I need it) 2) change label in PlayerForm(ModelForm) Meta, but seem not working for this field. It's strange that instead works widgets = {'human_ptr': Input(attrs={})} but it affects the {{ field }} not the {{ field.label_tag }} If can be useful I add all the parts of the involved code: forms.py from skeleton.models import Player from django.forms import ModelForm from django.forms.widgets import Input class PlayerForm(ModelForm): class Meta: model = Player fields = ['first_name', 'last_name', 'jersey_number'] labels = … -
In a Postgresql database where a seller has many products and products have many sellers, where should price(s) get stored?
Using django and python, I am building a web app that tracks prices. The user is a manufacturer and will want reports. Each of their products has a recommended price. Each product could have more than one seller, and each seller could have more than one product. My question is, where do I store the prices, especially the seller's price? Right now I have my database schema so the product table stores the recommended price and the seller's price, and that means one single product is repeated a lot of times. Is there a better way to do this? -
Django url template tags adding absolute filepath
I am having a problem where my {% url %} django template tag is adding the filepath to the web address in production. This is not replicated on my local development machine. With urls.py setup such that: url("^about_us/$", views.about_us, name="about_us"), In production, I am getting the link www.mysite.com/home/username/myapp/about_us instead of www.mysite.com/about_us I have looked at this similar issue and it does not help with my specific application: Django url tag adds filepath My django project is hosted on A2 (shared) hosting using apache, wsgi, and passenger. My .htaccess file look the following: # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/user/myapp" PassengerBaseURI "/" PassengerPython "/home/user/virtualenv/myapp/2.7/bin/python2.7" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END My passenger_wsgi.py file looks like the following: import myapp.wsgi SCRIPT_NAME = '/home/user/myapp' #SCRIPT_NAME = '/' class PassengerPathInfoFix(object): """ Sets PATH_INFO from REQUEST_URI because Passenger doesn't provide it. """ def __init__(self, app): self.app = app def __call__(self, environ, start_response): from urlparse import unquote environ['SCRIPT_NAME'] = SCRIPT_NAME request_uri = unquote(environ['REQUEST_URI']) script_name = unquote(environ.get('SCRIPT_NAME', '')) offset = request_uri.startswith(script_name) and len(environ['SCRIPT_NAME']) or 0 environ['PATH_INFO'] = request_uri[offset:].split('?', 1)[0] return self.app(environ, start_response) application = myapp.wsgi.application application = PassengerPathInfoFix(application) I feel like something is off in one of these files. How can I …