Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django chore weekly chart
I'm trying to develop a chore weekly chart, it seems easy in principles, but I have no idea how to create the calendar as in the below image. I need to be able to see the list of chores on the left and a weekly calendar on right, and I can navigate between weeks. If I clicked on a day cell, it will count the task as done or a start will appear. Any idea where to start to make such calendar? -
TypeError: int() argument must be a string or a number, not 'IntegerField'
I get this error whenever I try to migrate after makemigrations TypeError: int() argument must be a string or a number, not 'IntegerField' views.py from __future__ import unicode_literals from forms import * from django.shortcuts import render enter code here def home(request): return render(request, 'home.html') def upload(request): form = UploadForm return render(request, 'upload.html', {'form': form}) models.py from __future__ import unicode_literals from django.db import models class Product(models.Model): name = models.CharField(max_length=200, default='N/A') brand = models.CharField(max_length=50, default='N/A') material = models.CharField(max_length=50, default='N/A') color = models.CharField(max_length=20, default='N/A') price = models.IntegerField(default=0) discount = models.IntegerField(default=0) discountprice = models.IntegerField(default=0) photo1 = models.ImageField(default='no image') photo2 = models.ImageField(default='no image') forms.py from django import forms from models import * class UploadForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'brand', 'material', 'color', 'price', 'discount', 'discountprice', 'photo1', 'photo2'] and full error that I get Apply all migrations: admin, auth, contenttypes, products, sessions Running migrations: Applying products.0002_auto_20180617_1907...Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\Lalit\shoesite_env\lib\site-packages\django\core\management__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Lalit\shoesite_env\lib\site-packages\django\core\management__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Lalit\shoesite_env\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Lalit\shoesite_env\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\Lalit\shoesite_env\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File "C:\Users\Lalit\shoesite_env\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate state = … -
Integrating paypal's subscription to Django app (with paypal button)
I am building my first Django (2.0.5) application. So far I've set a standard django user model having plus an email attribute and a slightly custom signup form for it. I want to add a subscription to the app. After some research, I end up that a simple way to do it might be using the paypal's buttons, specifically the subscription button modification. Having followed the instructions from the paypal website, I placed the form with the test button on the template and tested the sandbox account which seems to work properly. <form class="form-control" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top"> <input type="hidden" name="cmd" value="_s-xclick"> <input type="hidden" name="hosted_button_id" value="WDWEG7ZAJD4U2"> <input type="hidden" name="on0" value="Subscription options">{% trans 'Subscription options' %}<select class="form-control" name="os0"> <option value="Basic">{% trans 'Basic' %} : €X.00 EUR - {% trans 'monthly' %}</option> <option value="Premium">{% trans 'Premium' %} : €X.00 EUR - {% trans 'yearly' %}</option></select> <input type="hidden" name="currency_code" value="EUR"> <input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"> <img alt="" border="0" src="https://www.sandbox.paypal.com/el_GR/i/scr/pixel.gif" width="1" height="1"> </form> It seems that after the test payment is successful, paypal redirects to the specified url and the process ends there. I would like to proceed somehow like getting a feedback from paypal regarding … -
How to configure pytest Django settings?
I want to experiment with pytest-django.I am following configuring django-settings-module Still,neither approach works. File "/home/mv/miniconda3/lib/python3.6/site-packages/pytest_django/plugin.py", line 120, in _handle_import_error raise ImportError(msg) ImportError: No module named 'test_settings' pytest-django could not find a Django project (no manage.py file could be found). You must explicitly add your Django project to the Python path to have it picked up. Should I edit my .bashrc? How to solve this problem? -
(custom user) createsuperuser TypeError: hasattr(): attribute name must be string
I've created a new Django project and the first thing I did was create a custom user with the help of Django docs: https://docs.djangoproject.com/en/2.0/topics/auth/customizing/ After I wrote all the code for a custom user, and after I did makemigrations and migrate for the first time in this Django project, I tried to create a superuser while my virtual env is active by writing: python manage.py createsuperuser But it gave me this error: TypeError: hasattr(): attribute name must be string I wrote all the custom user code in an app called accounts. In the settings file I added 'accounts' to the INSTALLED_APPS list, and added in the bottom this line: AUTH_USER_MODEL = 'accounts.CustomUser' Here's all my source code, starting with models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class CustomUserManager(BaseUserManager): def create_user(self, email, password): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user = self.model( email = self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password, first_name, last_name): if not first_name: raise ValueError("Staff and superusers must have a first name") if not last_name: raise ValueError("Staff and superusers must have a last name") user = self.create_user( email, … -
Django Datefield, TimeField, and DecimalField not displaying
Hi Djangonauts, I am new to Django. Please forgive any silly mistakes in code or logic My forms are not displaying the fields like they should(See Image). The price field only lets me put numbers but there is no restriction on how many numbers It even lets me add a 15 digit number The date and time_from, time_to fields just show long text-input fields. What am I doing wrong? class LessonsForm(forms.ModelForm): class Meta: model = Lessons fields = ('price', 'quantity', 'date', 'time_from', 'time_to') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].label = "How many members in one class" self.fields['price'].label = "How much do members have to pay to take lessons from you" self.fields['date'].label = "When do you plan to offer lessons" self.fields['time_from'].label = "What time do the lessons start" self.fields['time_to'].label = "What time does the lessons end" widgets = { 'price': forms.DecimalField(decimal_places=2, max_digits=5, attrs={'placeholder': 'Only Numbers'}), 'quantity': forms.IntegerField(min_value=1, max_value=25), 'date': forms.DateField(format("%b %d %Y")), 'time_from': forms.TimeField(), 'time_to': forms.TimeField() } Below is the image of how the form now looks -
Adding music Player to Django App
class Song(models.Model): album = models.ForeignKey(Album,on_delete=models.CASCADE) title = models.CharField(max_length=250) art = models.ImageField(upload_to='art_music/',default='') song = models.FileField(upload_to='songs') this is my model file and I am currently making a music player, Need the music player except HTML 5. -
Active directory account disabled.
I want add a account to AD by python ldap. by bellow code Account added to active directory maybe account status is disable: import ldap import sys def create_user_activedirectory(username , password , name ): SCRIPT = 1 ACCOUNTDISABLE = 2 HOMEDIR_REQUIRED = 8 PASSWD_NOTREQD = 32 NORMAL_ACCOUNT = 512 DONT_EXPIRE_PASSWORD = 65536 TRUSTED_FOR_DELEGATION = 524288 PASSWORD_EXPIRED = 8388608 conn=ldap.open("192.168.10.41") conn.protocol_version=ldap.VERSION3 conn.set_option(ldap.OPT_REFERRALS, 0) ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) conn.simple_bind_s("administrator@hamed.local" , "XYZ") mymodlist = { "objectClass": ["top".encode('utf-8'), "person".encode('utf-8'), "organizationalPerson".encode('utf-8'), "user".encode('utf-8')], "cn": [str(username).encode('utf-8')], #"uid": [str(username).encode('utf-8')], "userPassword": [str(password).encode('iso-8859-1')], "userPrincipalName": [str(username+"@XaaS.local").encode('iso-8859-1')], "sAMAccountName": [str(username).encode('utf-8')], "givenName": [str(name).encode('iso-8859-1')], "sn": [str(name).encode('iso-8859-1')], "displayName": [str(name).encode('iso-8859-1')], #"userAccountControl": [NORMAL_ACCOUNT], "userAccountControl": [str(NORMAL_ACCOUNT).encode('utf-8')], } dn="CN="+username+",CN=Users,DC=XaaS,DC=local" conn.add_s(dn, ldap.modlist.addModlist(mymodlist)) by "userAccountControl": [NORMAL_ACCOUNT] attribute, i get bellow error: {'info': '0000052D: SvcErr: DSID-031A12D2, problem 5003 (WILL_NOT_PERFORM), data 0\n', 'desc': 'Server is unwilling to perform'} if Delete "userAccountControl": [NORMAL_ACCOUNT] attribute, Account Disabled. -
Adding a field to django built in signup form
I am trying to create a custom sign up form in my django project but I still want to use from django.contrib.auth.forms import UserCreationForm that already has some built in fields. I have already created a form that adds the field but I don't know how to add this to model from django import forms from django.contrib.auth.forms. import UserCreation from django.contrib.auth.models import User class SignUpForm(UserCreationForm): email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput()) teamNumber = forms.CharField(max_length=4, required=True) class Meta: Model = User fields= ('username', 'email', 'teamNumber', 'password1', 'password2') I have tried using the abstractUser but that led to a mixture of errors. -
Send Email with aws workmail and django
I am using AWS workmail(not custom domain) and configured a user, I am able to send & receive mails with UI(browser). Now I want to use this workmail to send mails in my django app. below is my configuration in settings file. EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend' EMAIL_HOST = 'smtp.mail.us-east-1.awsapps.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'admin@example.awsapps.com' EMAIL_HOST_PASSWORD = 'mypwd' When user is registered using all-auth verification mail should be sent.But in my work mail I am getting that mail unable to deliver. Unfortunately, the system was unable to deliver your mail. The error given was: 2018-06-17 11:57:31 : You are not allowed to send as user or group webmaster@localhost You may need to contact your e-mail administrator to solve this problem. -
Django display search results in template
im quite new to Django and i want to display the search results in my search.html template but i missed the paths somehow... I use a context processor to display the searchbox together with a category selector globally. So the query against the database is a set of Catagorie and keyword. Not sure if i implement it the right way. No idea how to display the results in my Template. What to do with the catagoerie in the view.py ? base.py <div class="globalsearch"> <form id="searchform" action="{% url 'search' %}" method="get" accept-charset="utf-8"> <label for="{{ categorysearch_form.category.id_for_label }}">In category: </label> {{ categorysearch_form.category }} <input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search for ..."> <button class="searchbutton" type="submit"> <i class="fa fa-search"></i> </button> </form> </div> views.py class BlogSearchListView(ListView): model = Post paginate_by = 10 def get_queryset(self): qs = Post.objects.published() keywords = self.request.GET.get('q') if keywords: query = SearchQuery(keywords) title_vector = SearchVector('title', weight='A') content_vector = SearchVector('content', weight='B') tag_vector = SearchVector('tag', weight='C') vectors = title_vector + content_vector + tag_vector qs = qs.annotate(search=vectors).filter(search=query) qs = qs.annotate(rank=SearchRank(vectors, query)).order_by('-rank') return qs in the end a want to display the results the same way as i display it on my post_list.html: {% extends 'quickblog/base.html' %} {% block content %} {% for post in posts %} … -
Deconfiguration of the DJANGO_SETTINGS_MODULE variable (irreparable)
The fact is that I have a VPS in Digital Ocean with Ubuntu 18.04. I installed everything necessary starting with the typical apt update and upgrade, then pip, virtualenvwrapper, django and postgresql, started with runserver and tried in the browser the django and django-admin test page, all perfect for a few days. After a few days, I upgraded my system again with apt update and upgrade, and the django application stopped working, with the error "You must either define the variable DJANGO_SETTINGS_MODULE variable or call settings.configure () before accessing settings. " I have tried many things without finding the solution; I have reinstalled virtualenvwraper, django, virtual environments and project, but it still does not work as before. I have also tried to assign the variable manually with export DJANGO_SETTINGS_MODULE = settings and it says that the module can not be found. Any idea of what has happened to my system? I would like to try all the possibilities before deleting the droplet and reinstalling everything. -
django approve or reject for everyone field in object
I am looking for a package or hints on how to track each field and the ability to accept or reject editing i using Django 1.11 and python3 Package like: django_monitor not working django_approve not working -
Django custom login form show extra field
I've created Django custom login form, but it shows email field for 2 times and it fails to auth. here are my files : urls.py path('login/', views.login, name='login'), models.py where is the modeluser table is created : class UserModelManager(BaseUserManager): def create_user(self, email, password, pseudo): user = self.model() user.name = name user.email = self.normalize_email(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password): ''' Used for: python manage.py createsuperuser ''' user = self.model() user.name = 'admin-yeah' user.email = self.normalize_email(email=email) user.set_password(password) user.is_staff = True user.is_superuser = True user.save() return user class UserModel(AbstractBaseUser, PermissionsMixin): ## Personnal fields. email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=16) ## [...] ## Django manage fields. date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELD = ['email', 'name'] objects = UserModelManager() def __str__(self): return self.email def get_short_name(self): return self.name[:2].upper() def get_full_name(self): return self.name forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, help_text='البريد الإلكترونى الخاص بك - يجب ان يكون حقيقى (يستخدم لتسجيل الدخول) ') name = forms.CharField(required=True, help_text='إسمك الحقيقى - سيظهر كأسم البائع') password1 = forms.CharField(widget=forms.PasswordInput, help_text='كلمة المرور - حاول ان تكون سهلة التذكر بالنسبة لك') password2 = forms.CharField(widget=forms.PasswordInput, help_text='تأكيد كلمة المرور - إكتب نفس كلمة المرور السابقة مرة أخرى') class Meta: model = UserModel fields = ('email','name', … -
Form validation: "That choice is not one of the available choices."
One of my models has a foreign key field. This field is displayed, as expected, as a drop-down (Select widget). The POSTed value for that field is a string, although the related model's ID has a default type primary key (integer): Therefore, form validation fails while cleaning the data with: Select a valid choice. That choice is not one of the available choices. I have no custom form definition or validation at all. Why is the foreign key provided via select widget in form not converted to the right type? -
Django ModelForm save only if text entered matches
models.py class test1(models.Model): write = models.CharField(max_length=20) def __str__(self): return self.write forms.py class NameForm(forms.ModelForm): class Meta(): model = test1 fields = '__all__' views.py def get_name(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): if form.objects.write == 'banana': form.save(commit=True) else: return "Wrong name" return render(request,'app_one/index.html') else: form = NameForm() return render(request, 'name.html', {'form': form}) I would like to save the form only if user enters banana in the write field of NameForm. can I use if form.objects.write == 'banana': form.save(commit=True) -
DRF nested routers could not resolve URL for hyperlinked relationship
I am trying to use drf-nested-routers to create a nested url pattern like the following: /projects/{project_pk}/join_request/{pk} With my current setup, I am able to navigate to /projects successfully, and see the list of hyperlinked join_requests: [ { "url": "http://127.0.0.1:8000/projects/1/", "join_requests": [ "http://127.0.0.1:8000/projects/1/join_requests/1/", "http://127.0.0.1:8000/projects/1/join_requests/2/" ], "name": "Sample Project" } ] However, when I click through to a join_request, I get the following error: ImproperlyConfigured at /projects/1/join_requests/1/ Could not resolve URL for hyperlinked relationship using view name "projectjoinrequest-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. As a DRF beginner, after doing much research, I cannot ascertain where I am going wrong. I would appreciate if someone could post an example, or advise where I have misconfigured: In models.py, I have: class Project(models.Model): name = models.TextField() # what is the name of the project class ProjectJoinRequest(models.Model): request = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="join_requests", blank=True, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="join_requests", blank=True, null=True) class User(AbstractUser): name = models.TextField() In serializers.py: from rest_framework_nested.relations import NestedHyperlinkedRelatedField class ProjectSerializer(serializers.HyperlinkedModelSerializer): join_requests = NestedHyperlinkedRelatedField( many=True, read_only=True, view_name='projectjoinrequest-detail', parent_lookup_kwargs={'project_pk': 'project__pk'} ) class Meta: model = models.Project fields = ["join_requests", "name"] class ProjectJoinRequestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model … -
Difference between configuring database on zappa app & regular django app
Is there any difference configuring a zappa app & a regular django app? I am following this tutorial on setting up a zappa app and under "Configure the database" it links to paid tutorials - and I can't find much info via searching google. So is it any different than just changing my DATABASES in my settings, installing psycopg2 and migrating the changes? Or does zappa require something different/more? -
Q object filtering with multiple conditions failing
I am trying to apply multiple conditions to my filter. The model looks like this class modelChat(models.Model): source = models.ForeignKey(modelEmployer,related_name = 'rsource',on_delete=models.CASCADE,null=True,default=None,blank=True) job = models.ForeignKey(modelJob,on_delete=models.CASCADE,null=True,default=None,blank=True) destination = models.ForeignKey(modelEmployer,related_name = 'rdestination',on_delete=models.CASCADE,null=True,default=None,blank=True) Initially I am trying to obtain an instance of chat that involves 2 parties based on a job. At one point source can be a destination and sometimes the destination can be the source. This is what my query looks like querySet = modelChat.objects.filter( (Q(source=modelEmployerSourceInstance) | Q(destination=modelEmployerSourceInstance)) & (Q(destination=modelEmployerDestinationInstance) | Q(destination=modelEmployerDestinationInstance)) & Q(job_id=job_id) ) The job id is correct and I know there is only one item in the DB however this query alway returns back an empty item. Any suggestions why this is wrong and how I can fix it ? -
Removing case sensitivity from Email in Django login form
Before anyone marks it as duplicate, I've searched everywhere and didn't find. I've created a custom UserModel and used Email as main authenticating id instead of username. The problem that it is case sensitive, as it counts test@gmail.com,Test@gmail.com as 2 different accounts. I need to force it to deal with both as 1 account ignoring if it upper or lower case. here are my files : models.py class UserModelManager(BaseUserManager): def create_user(self, email, password, pseudo): user = self.model() user.name = name user.email = self.normalize_email(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password): ''' Used for: python manage.py createsuperuser ''' user = self.model() user.name = 'admin-yeah' user.email = self.normalize_email(email=email) user.set_password(password) user.is_staff = True user.is_superuser = True user.save() return user class UserModel(AbstractBaseUser, PermissionsMixin): ## Personnal fields. email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=16) ## [...] ## Django manage fields. date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELD = ['email', 'name'] objects = UserModelManager() def __str__(self): return self.email def get_short_name(self): return self.name[:2].upper() def get_full_name(self): return self.name signup view in views.py def signup(request): if request.method == 'POST': signup_form = SignUpForm(request.POST) if signup_form.is_valid(): signup_form.save() username = signup_form.cleaned_data.get('username') raw_password = signup_form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) return redirect('signup_confirm') else: signup_form = SignUpForm() context … -
use class attribute indivdually as Modelform in views
models.py class test1(models.Model): write = models.CharField(max_length=20,default='som') write1 = models.CharField(max_length=20,null=True) def __str__(self): return self.write + " " + self.write1 forms.py from django import forms from django.forms import ModelForm from .models import test1 class test2(forms.ModelForm): class Meta(): model = test1 fields = '__all__' views.py from django.http import HttpResponse from app_one.forms import test2 def get_name(request): a = test2.write a1 = test2.write1 html = "<html><body>It is now %s.<br>%s</body></html>" % a,a1 return HttpResponse(html) How can I use the write and write1 attributes of class test1 individually as Modelform in views -
Django: cannot import name path
My urls.py looks like this: urlpatterns = [ path('',views.index, name='index'), path('entry/(<int:pk>)' , views.details,name='details'), path('admin/', admin.site.urls), ] but when i try to run it i get error as cannot find path. Attempt 1 : I tried to use url instead but I am not sure how to use second line into url. This does not seems to work: urlpatterns = [ url(r'^$',views.index, name='index'), url(r'^entry/(?P<pk>\d+)/' , views.details,name='details'), url(r'^admin/', admin.site.urls), ] -
How to add email address in signup_form.html - Django-crispy-forms
My signup_form.html is as below, is there any way to add a email address in this form without changing views.py of back-end code?, I would like to let user fill in email adress when he is registering, {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="col-md-8 col-sm-10 col-12"> <form method="post" novalidate> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}"> {{ form|crispy }} <button type="submit" class="btn btn-success">Sign up</button> </form> </div> </div> {% endblock %} -
Anaconda installation interfering requirements.txt in django?
It is listing all packages and the list is enoromous, i am working in virtual environment. I have installed Anaconda after starting this project, is their any way to fix it? I am lisiting a few - alabaster==0.7.10 anaconda-client==1.6.5 anaconda-navigator==1.6.9 anaconda-project==0.8.0 asn1crypto==0.22.0 astroid==1.5.3 astropy==2.0.2 Babel==2.5.0 backports.shutil-get-terminal-size==1.0.0 beautifulsoup4==4.6.0 bitarray==0.8.1 sphinxcontrib-websupport==1.0.1 spyder==3.2.4 SQLAlchemy==1.1.13 statsmodels==0.8.0 sympy==1.1.1 tables==3.4.2 tblib==1.3.2 terminado==0.6 testpath==0.3.1 -
What is the best search third party in Django for search at scale?
I plan to get an search field for my web site. What is your suggestions? What is the best third party app? For example ElasticSearch is best?