Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter a table based on other two tables Django OMR
I have a table with fields email and department_name, another table named Department with a dept_name and a user table. Department table have a manytomany relation to user table. I need to filter first table with departments having user with email columns. Is there anyway to do this in a single query. My query may look like TempUser.objects.filter(email__in=Department.objects.filter(dept_name="department name from first table").users.value_list('email', flat=True) -
Function's url staying after a new render
I have just started learning Django after completing the tutorial on their website and I am trying to get my Django website's form to render a template with a dictionary describing the "login_error" variable after a login attempt has failed. This works fine but the URL still contains the view functions name and I don't want this. Redirecting the page to itself works fine but then I cannot define the "login_error" variable. The URL to start the views login function: path('login_user', views.login_user, name='login_user'), If the login fails I am re-rendering the page like so: return render(request, 'sign_in/sign-in.html', { 'login_error': "We couldn't find an account with that email and/or password." }) Here is what I am using to navigate to this function: <form class="sign_in" method="post" action="{% url 'sign-in:login_user' %}"> Here are some images to help explain what's happening: I submit a bad login: This is the part of the URL stays after the render: Any advice, links or resources to direct me in the way of a solution would be highly appreciated as I have been searching for hours now and still can't find anything related to this issue, thanks! -
django: trying to organize clean_data functions, and validators. Where does each thing go?
I am trying to find the way to organize code snippets the right way but I am getting mixed up with all this: I have the models.py where I have declared (show part of the fields) this class Posts(models.Model): image = models.ImageField(upload_to=user_directory_path, null=True, blank = True) Then I want to sanitize that field just in case someone wants to be funny in the form page. So I went to forms.py and created a custom method to clean it class PostsForm(ModelForm): class Meta: model = Posts fields = ['image' , 'otherfields'] def clean_image(self): image = self.cleaned_data['image'] Ok that cleans it, but I need more, like making sure they dont upload a file too large. So I thought I could create a directory in templates/validators and create a file like validators.py where I write my validation functions and then I can import that function. So. validators.py from django.core.exceptions import ValidationError def file_size(value): limit = 2 * 100 * 100 if value.size > limit: raise ValidationError('File too large. Should be less than 200 Kbs') so when I am in the forms.py I wanted to import that file validators.py like this from myaapp.validators import file_size but it tells me that it doesn't know what … -
Django Migration is not apply new migrations
I tried to make new migrations but show me error. I am using django1.9 and python 2.7 .Is any solution for this so i can create new migration.How can I do the migration? django.db.utils.IntegrityError: could not create unique index "appointments_userappointments_advance_c37857a7_uniq" DETAIL: Key (advance, status)=(5000, 3) is duplicated. Here is my model: class UserAppointments(models.Model): """ Represent an Appointment entity """ STATUS = ( ("1", 'Scheduled'), ("2", 'Active'), ("3", 'Completed'), ("4", 'Cancelled') ) customer = models.ForeignKey(Customer, null=True, blank=True) staff_user = models.ForeignKey(StaffUser, null=True, blank=True, related_name='staff_user') service = models.ForeignKey(Service, null=True, blank=True) advance = models.IntegerField(default=0, null=True, blank=True) date_time = models.DateTimeField(auto_now_add=True) creation_date = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(StaffUser, null=True, blank=True, related_name='created_by') update_date = models.DateTimeField(auto_now=True, null=True, blank=True) updated_by = models.ForeignKey(StaffUser, null=True, blank=True, related_name='updated_by') status = models.CharField(max_length=1, default=1, choices=STATUS) class Meta: verbose_name_plural = 'Appointments' ordering = ['date_time'] def __unicode__(self): return self.date_time.strftime("%Y-%m-%d %H:%M:%S") and my migration file: from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('appointments', '0009_auto_20180114_1838'), ] operations = [ migrations.AlterModelOptions( name='userappointments', options={'ordering': ['advance'], 'verbose_name_plural': 'Appointments'}, ), migrations.AlterUniqueTogether( name='userappointments', unique_together=set([('advance', 'status')]), ), ] -
Django ManyToManyField Storing None objects
I am trying to create an audit app in which a model contains all the questions, answers in form of choices and comments class AuditQuestion(models.Model): NOT_INITIATED = 'NI' IN_PROCESS = 'IP' COMPELETED = 'C' STATUS = ( (NOT_INITIATED, 'Not Initiated'), (IN_PROCESS, 'In Process'), (COMPELETED, 'Completed'), ) type_of_room = models.ForeignKey(TypeOfRoom, null=True, blank=True) question = models.CharField(max_length=512) status = models.CharField(max_length=2, choices=STATUS, default=NOT_INITIATED) comments = models.TextField(null=True, blank=True) def __str__(self): return self.question Another model contains project status which contains details of the project such as location, project_name, user and floor no of the building class ProjectStatus(models.Model): floor_no = models.IntegerField(null=True) project_details = models.ForeignKey(ProjectDetails, null=True) question = models.ManyToManyField(AuditQuestion, null=True) def __str__(self): return str(self.floor_no) The logic goes like this... a new project is created using ProjectDetails model, and a project status is generated for every floor of the building. and each floor is to be audited against the questions present in AuditQuestion model and status and comments are to be registered. I used ManyToMany relation so that project status model can have multiple questions and their status and comments. But, when i try to save question it doesn't happen my view.py function is below: @login_required def save_question(request): project_status_id = request.POST.get('project_status_id') question_id = request.POST.get('question_id') status = request.POST.get('status') comments = … -
Request CSRF + Access-Control-Allow-Headers
Im developing an application with two core. Client Side with ReactJs and a Server Side made with Django. The Client will makes a lot of GET/POST request to the server. To prevent CSRF problem, every Ajax Request has CSRF-TOKEN. beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", window.csrftoken); } [...] } This is a piece of the Django/Python view view example of the server: response = HttpResponse(json.dumps(software_settings), content_type="application/json" ) response['Access-Control-Allow-Origin'] = "*"; response['Access-Control-Allow-Headers'] = "X-Requested-With, X-Prototype-Version, X-CSRF-Token"; response['Access-Control-Allow-Methods'] = "POST, GET, OPTIONS"; I have two big problems: FIRST: On online solutions, window.csrftoken variables is usually taken from cookie. I sincerely don't know how to create it. Im using unversal-cookie to read and write cookie with React, but I missing the correct data flow between the two applications. The default values is "null" so the first call has null as CRFT Token; SECOND: I have a problem with response. As see above, I've tried to put a lot of configurations entry fro Access-Control. This is a piece of request headers: Access-Control-Request-Headers:x-csrftoken Access-Control-Request-Method:POST Connection:keep-alive Host:localhost:8000 Origin:http://localhost:3000 This is the error I get: Failed to load http://localhost:8000/get_software_settings/: Request header field X-CSRFToken is not allowed by Access-Control-Allow-Headers in preflight response. I … -
standalone applications should use blank.html as redirect_uri to access messages
I use django 1.11 and django-allauth for autentification. I'm all set up and everything works. Then I tried to write a message on the social network vkontakte. I take token connected vk-account from allauth access_token = SocialToken.objects.filter(account__user=request.user, account__provider='vk') then i install api-library for vk. pip install vk Then I tried to write in vk. access_token = SocialToken.objects.filter(account__user=request.user, account__provider='vk') session = vk.Session(access_token=access_token) api = vk.API(session, scope=['offline', 'messages']) api.wall.post(message='Hello, World!') I got an scope error about insufficient rights. I added in scopthe necessary rights. class VKProvider(OAuth2Provider): id = 'vk' name = 'VK' account_class = VKAccount def get_default_scope(self): scope = ['groups', 'notify ', 'friends', 'photos', 'audio', 'video', 'pages', '+256', 'status', 'notes', 'wall', 'ads', 'wall', 'offline', 'ads', 'docs', 'notifications', 'stats', 'email', 'market', 'messages',] if app_settings.QUERY_EMAIL: scope.append('email') return scope def extract_uid(self, data): return str(data['uid']) def extract_common_fields(self, data): return dict(email=data.get('email'), last_name=data.get('last_name'), username=data.get('screen_name'), first_name=data.get('first_name')) Но после этого я получил еще одну ошибку. {"error":"invalid_scope","error_description":"standalone applications should use blank.html as redirect_uri to access messages"} I sometimes don't understand what's going on? Could you help me to understand? -
How to get user queryset who commented to certain post in Python, Django?
I would like to get a user queryset who commented in certain post. Assume that there is a post(id=3), and there 8 people commented on it. I want to notify something to 8 people, so I want to get 8 people's queryset(user objects). How can I do it? I have model User, Post, and Comment. For example, User.objects.get(comment__Post.objects.filter(id='3')) like this way. (of course, the upper doesn't work) Help me! -
AttributeError when I import model from another app
I don't know why but I got an error: AttributeError: module 'downloads.models' has no attribute 'AbstractDownload' in this place: class Download(models_downloads.AbstractDownload): In download app I have already AbstractDownload class Here is my model from products products/models.py from downloads import models as models_downloads class Download(models_downloads.AbstractDownload): product = models.ForeignKey('products.Product', related_name='downloads') file = FilerFileField(related_name="file_products_download") Here is downloads models downloads/models.py class AbstractDownload(models.Model): title = models.CharField(max_length=500) subtitle = models.CharField(max_length=1000, blank=True) file = FilerFileField(related_name="file_abstract_download") order = models.PositiveIntegerField(default=0) class Meta: abstract = True def __str__(self): return self.title -
There is a django AUTHORIZATION module?
I have already a django project, which does the users authentication. Now I nedd an authorization module (for clients and groups to certain resources). I would an existing django module or api. thanks -
How to insert data on a table using a form?
I want to POST a message to the Message table in my db, wich contains the following fields: id; body; normaluser; chat.html: <form method="post" id="msg"> <div class="form-group"> <label for="comment">Message:</label> <textarea class="form-control" rows="5" id="comment"></textarea> </div> {% csrf_token %} {{ form.as_p }} <button type="submit">Enter</button> </form> views.py @login_required def msg(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() body = form.cleaned_data.get('body') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) Message(request, user) else: form = 'msg' args = {'form': form} return render(request, 'accounts/chat.html', args) I am basing my view from the def I use to make a new user. But I'm not understanding how to change it to accept a message, wich also receives the info of the user authenticated at the time he sends the message. -
Django Python: How to convert datetime.time(2, 3) to String format H:M:S
In my Django models I have a models.TimeField to store time. When doing model.objects.filter().values() my TimeField gets return as datetime.time(2,3) for example. I want to return it as a string. In this case since the time is AM my string should look like 2:03:00 AM or if PM then 2:03:00 PM. It could also be formatted as a 24-hour format. How do I do that? -
What is the proper regular expression for uid in base64 and token in Python?
In Django 2.0, I deal with uid and token for user email confirmation. 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': PasswordResetTokenGenerator().make_token(user), My urlpatterns is like below, however pattern is not found urlpatterns = [ re_path(r'^confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/' '(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', confirm_user_email, name='confirm-user-email'), ] the error message is like this, Reverse for 'confirm-user-email' with keyword arguments '{'uidb64': b'Mw', 'token': '4t9-a61218655569c14203b8'}' not found. 1 pattern(s) tried: ['member\/confirm/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] -
Dictionary Errors with Django Intermediate Model
I have three tables. Table A, B, and C. I have a form where the user can select choices from each table. I need to save the relationship between Tables A & C and the relationship between Tables B & C. The relationships between Tables B&C are saving fine(AssignmentManager). However, the relationships between Tables A & C are not. They are linked through an intermediary model. I'm trying to follow the documentation examples, but I don't know if I'm interpreting them right. https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany I keep getting one error after another. The latest one is a multi key dictionary error. The intermediary manager for Tables A and C is the FunctionAssignmentManager. Models.py class AssignmentManager(models.Manager): def relationship (self, Role_id, Assignment_title): select = Assignment.objects.get (id= Assignement_title) roles = Role.objects.get(id=Role_id) select.role.add(roles) select.save class FunctionAssignmentManager(models.Manager): def functionA (self,postData): newrel = FunctionAssignment.objects.create( function = ['function'], assignment = ['assignment'] ) newrel.save() class Function(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to="images") objects = FunctionManager() class Role(models.Model): level = models.CharField(max_length=255) function = models.ForeignKey(Function, related_name="roles") objects = RoleManager() class Assignment(models.Model): function = models.ManyToManyField(Function, through='assignments') role = models.ManyToManyField(Role, related_name='assignments') title = models.CharField(max_length=255) definition = models.TextField() objects = AssignmentManager() class FunctionAssignment(models.Model): function = models.ForeignKey(Function, on_delete=models.CASCADE) assignment = models.ForeignKey(Role, on_delete=models.CASCADE) review= models.TextField() objects = … -
Generic detail view ProfileView must be called with either an object pk or a slug
I'm new to Django 2.0 and i'm getting this error when visiting my profile page view. It's working with urls like path('users/<int:id>') but i wanted to urls be like path('<username>'). Not sure what exactly is the problem. I hope you can help. #views.py class ProfileView(views.LoginRequiredMixin, generic.DetailView): model = models.User template_name = 'accounts/profile.html' #urls.py urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('signup', SignUpView.as_view(), name='signup'), path('login', LoginView.as_view(), name='login'), path('logout', logout_view, name='logout'), path('<username>', ProfileView.as_view(), name='profile') ] #base.html <ul class="dropdown-menu"> <li><a href="{% url 'accounts:profile' user.username %}">View Profile</a></li> <li><a href="#">Edit Profile</a></li> </ul> -
porting an app built using Tornado framework to Django framework
I have an app that was developed using Tornado framework and Angularjs. the app is basically a game with two type of users a moderator and players. the moderator and players exchange data in "real time" and a graph is updated based on their input. I am a decent coder but new to web development and this is just an in case question. Since the app has some issues, and since I will have to learn a framework anyway, I would rather learn Django. I was wondering if there is a resource out there that makes the conversion easier? What I am looking for is advice on how to tackle this in a way where I don't have to go through the documentation of both frameworks before I can do anything useful. Ideally, I'd like to incrementally learn more about both frameworks as I make meaningful edits to the app. -
Django ignores test database settings
I have an app deployed on pythonanywhere which runs fine. Problem is that when I want to run test django, my test database settings is completely ignored. Each time I run test I get the following message.though. Creating test database for alias 'default'... Got an error creating the test database: (1044, "Access denied for user 'funnshopp'@'%' to database 'test_funnshopp$funn'") Database name for the app is funnshopp$funn. It can be seen that django somehow always tries to create the test database by appending test_ to the database name. Never minding what I have in DATABASES settings Below is my full settings file ( Test runs fine on my PC and I am using Django 2.0, though I started the project with Django 1.11) """ Django settings for funnshopp project. Generated by 'django-admin startproject' using Django 1.11.7. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os from django.urls import reverse_lazy from django.core.exceptions import ImproperlyConfigured # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def get_env_variable(var_name): """Get the environment variable or return exception""" try: return os.environ[var_name] except KeyError: error_msg = "Set the {} environment variable".format(var_name) raise … -
I don`t know what means None in django user
class MemberStaffManager(BaseUserManager): def create_user(self, staff_id, company, position, name, password=None): user = self.model( staff_id=staff_id, company=company, name=name, position=position, ) user.set_password(password) user.save(using=self._db) return user Now I'm studying Django custom user but I don't know what means password=None maybe not mean password = null because user.set_password(password) is send password-value please help me. -
ModuleNotFoundError at /polls/register/
I am creating a registration form in django. My project name is FirstProj containing mysite and mysite containing polls. My forms.py is this from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email= forms.EmailField(required = True) class Meta: model = User fields = { 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' } def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = cleaned_data['first_name'] user.last_name = cleaned_data['last_name'] user.email = cleaned_data['email'] if commit: user.save() return user My views.py is this from mysite.polls.forms import RegistrationForm from django.shortcuts import render,redirect def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/polls') else: form = RegistrationForm() args = {'form': form} return render(request, 'polls/reg_form.html', args) However my cleaned_data() can't be read and i am getting the following erro. No module named 'mysite.polls' -
How to insert multiple Django blocks into one template?
I am trying to use more different views in one template via different blocks or include method but I have got stuck. My aim is to implement my different views into one template. I tried to more solution but these haven't worked for me. I show these solution: My views: def dashboard_data(request): # Here I collect data from my PostgreSQL database I push these into #Objects and I send it to my test_a.html via render like below. return render(request, 'my_project/test_a.html', send_data) def chart_data(request): #In these view my final goal is to collect data from database and create #charts but for the simplicity I just use a list (a=[1,2,3,4]) and I #push it to the test_b.html and I render it. render(request, 'my_project/test_b.html', send_data)) My templates: 1, base.html <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>My project</title>{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Include CSS files --> {% load static %} <!-- Include CSS files --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap-table.css' %}"> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <link rel="stylesheet" href="{% static 'css/font-awesome.min.css' %}"> </head> <body> {% block sidebar %} {% endblock %} {% block content%} … -
Django create form wizard from model form
My requirement is to create a form wizard using model form. For example, I have a number of dynamic models, one model has 10 fields and another model have 15 fields. the model form should be split into multiple forms automatically based on fields it contains. I have tried using django-form-tools, but in django-form-tools we need to predefine the form classes in form_list attribute. Is there any other alternative to achieve this without manually doing this -
django project multiple user use the same project
I am new to django and web programming. Right now, I have created a django project for configuration form generation. It allows the user to input the values and generate a configuration form once the user got the URL. Project name: portal, App name: home, input_data.txt: a text file stored the values for the corresponding parameter and it will be read for further processing It works fine for myself, but multiple users use it at the same time. It doesn't work. what can I do in order to allow multiple users use it at the sam time? -
Django webpack loader - KeyError 'DEFAULT' while rendering template
I am trying to get django-webpack-loader to run with webpack but I get an error when I try to render the {% render_bundle 'main' %} tag in my view. I have checked and webpack is successfully generating bundles into my bundles folder, but django-webpack-loader can't seem to render it into the template. I am using default settings for webpack-loader. Does anyone understand this error message and what is causing it? Template error: In template /djangoreact/djangoproject/djangoapp/templates/djangoapp/base.html, error at line 11 DEFAULT 1 : {% load render_bundle from webpack_loader %} 2 : <!DOCTYPE html> 3 : <html> 4 : <head> 5 : <meta charset="UTF-8"> 6 : <title>Example</title> 7 : </head> 8 : <body> 9 : <h1>Django-webpack</h1> 10 : <div id="react"></div> 11 : {% render_bundle 'main' %} 12 : </body> 13 : </html> Traceback: File "/djangoreact/djangoproject/djangoapp/views.py" in index 7. return render(request, template_name ) File "/.virtualenvs/djangoreact/lib/python3.6/site-packages/webpack_loader/config.py" in load_config 33. return user_config[name] Webpack configuration in Django. WEBPACK_LOADER = { 'DEAULT':{ 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } -
Chart JS - Data graph is out of chart
I m new to chart.js, and yet so far i was unable to find answer for this issue. When i add option to chart scaleBeginAtZero: true, some of the top values is out of Y axis boundaries, and in some cases it shows nice view. Maybe it is something to do with the steps of Y axis ? Note in example how Y axis max value 2560 and data in the graph is 2700. Example -
Communication between two django applications
I have one django application that has a model Patient which has all the information about the patient and it's blood sample . I wish to have another application that have some fields of the Patient model and i want both the applications to communicate using some sort of web services so the changes made in the first application are reflected in the second . I'm a novice in django , please share any resources anyone has . If my question is not clear enough, please let me know with a comment. Thank you