Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it ok to put html code in Django TextField?
Is it good to put html code in a Django TextField that will be used in a blog app? -
Update date in database - attend button
Hej, I have a problem with updating current date. I should click the button "attend" and update status with current date in database. For me everything looks fine but I have no clue where is the problem.. Maybe someone could find my mistake? HTML: <form method="POST" action="/donors/"> {% csrf_token %} <button type="submit" class="btn attendBtn" value="{{ item.id }}" name="attend"> attend </button> VIEW: elif 'attend' in request.GET: donor_id = None # if request.method == "GET": # donor_id = request.GET.get('id') if donor_id: donor = Donor.objects.get(id=int(donor_id)) if donor: donor.lastAttendance.add(datetime.datetime.now()) donor.save() DATABASE: database link Any help will appreciated! -
how to test a model that has a foreign key?
I'm usig python 3.5 and Django 1.10 and trying to test my app in tests.py, but an error appeared, it said:ValueError: Cannot assign "1": "NewsLetter.UserID" must be a "User" instance. so how to test a fk value here? here is the code: class NewsletterModelTest(TestCase): @classmethod def setUpTestData(cls): #Set up non-modified objects used by all test methods NewsLetter.objects.create(NewsLetterID=1, Email='test@test.com', Connected=False,UserID=1) class NewsLetter(models.Model): NewsLetterID = models.AutoField(primary_key=True) Email = models.CharField(max_length=255) Connected = models.BooleanField(default=False) UserID = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table = 'NewsLetter' -
django template select option
I have following question : I would like to have a page on which I want to use Select2 , but list of selection options should come from my database. I have a table from which I would like to select entries using something like this: SELECT DISTINCT field FROM table ORDER BY field ASC This will give a list I want to use in select. In PHP it was quite simple to use it, but in Django (which I learn) I am not sure how it can be achieved. For some reasons I do not want to use models and ORM, but would like to use direct selects to DB tables which I define by myself in view. To make this example simple, lets take it from this page : Django: Select option in template Lets assume I have DB table organizations which has two field: ID , Name I want to select 'name' using the select listed above. After I fetch those data I want them to be used in <select> <option>org1</option> <option>org2</option> ..... </select> -
how to print image by printer [Django]
I want to print only selected images by printer at server side. the language is python. framework is django. could you give me idea? best regards. -
Django uploading image using builtin user-model
I am trying to give my users ability to upload profile pictures to their account. The problem is I am using Django user model, so I don't have my own model where I can add image = models.ImageField() This is my forms.py from django import forms from django.contrib.auth import authenticate, get_user_model, class UserRegisterForm(forms.ModelForm): confirm_email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput) image = forms.ImageField(required=False) class Meta: model = User fields = ['email','confirm_email','username','password'] def clean_confirm_email(self): email = self.cleaned_data.get("email") confirm_email = self.cleaned_data.get("confirm_email") if email != confirm_email: raise forms.ValidationError("Emails do not match") email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError("Email already used") return email def clean_confirm_password(self): password = self.cleaned_data.get("password") confirm_password = self.cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError("Passwords do not match") return password in my registration page the image button is being displayed, Tho I have no idea how to save the image and link it to the user. this is my views.py from django.shortcuts import render, redirect from django.contrib.auth import (authenticate, get_user_model, login, logout) from .forms import UserLoginForm, UserRegisterForm # Create your views here. def login_view(request): login_form = UserLoginForm(request.POST or None) if login_form.is_valid(): username = login_form.cleaned_data.get("username") password = login_form.cleaned_data.get("password") user = authenticate(username=username,password=password) login(request, user) return redirect('/') context = { "login_form": login_form } … -
What is wrong with this template in Django?
from django.shortcuts import render from django.http import HttpResponse #http response sends back html/basic webpage from django.conf.urls import include from django.template import loader from .models import Album # Create your views here. '''def index(request): all_objects = Album.objects.all() html = '' for album in all_objects: url = "/music/" + str(album.id) + "/" html += '<a href = "' + url + '">' + album.album_title + '</a><br>' return HttpResponse(html) ''' def index(request): all_albums = Album.objects.all() #template = loader.get_template('music/index.html') context = {'all_albums': all_albums} return render(request, 'music/index.html', context) #return HttpResponse(template.render(context, request)) def detail(request, album_id): return HttpResponse("<h2>Details of Album with id:" + str(album_id)+ "</h2>") yields perfectly right templates. And when I add the templates for an album that does not exist. That is I have added 2 albums and synchronized with my database, and when I surf to the third template page, I should get the 404 error. And the code for this is- from django.http import Http404 from django.shortcuts import render from django.http import HttpResponse from django.template import loader from .models import Album def index(request): all_albums = Album.objects.all() #template = loader.get_template('music/index.html') context = {'all_albums': all_albums} return render(request, 'music/index.html', context) #return HttpResponse(template.render(context, request)) #render has an inbuilt http return type def detail(request, album_id): try: album = … -
Setting PyMongo at PythonAnyWhere.com
I have deployed my django project on python anywhere but i am getting ServerSelectionTimeoutError at /register/ Got opcode 1684095520 but expected 1 my client setup for pymongo in views.py client = MongoClient('localhost',80) users_current_db= client.datab Need help on this, Thanks in advance -
Django Rest Framework together with ManyToMany fields with Through
I have a Training modell and a Drill model that got a ManyToMany relationship between each other. The issue I'm having is that Django by default enforces uniqueness and it is not possible to have duplicate Drills on the same Training. To solve this, I can use the through= param when setting the ManyToMany relationship, but this causes a lot of issues with Django Rest Framework. Is there any other way of doing it? Do I have to create a through= model just to not enforce uniqueness on my M2M Relationship? The issues I'm having with DRF is that I'm also required to have a intermediary Serializer for the new Model that was created. This causes issues when I want to send Drill data because it validates it and strip all Drill data because it's expecting a TrainingDrill (The intermediary model) due to the custom serializer required. This small change really quickly require tons of extra changes. There must be a better way. -
Can't get and filter object by slug parametr, how to fix? i'm noob
for this function using ajax request We need to get the object from the database, by slug, "slug" we get from the ajax request, and it's like a string, but the get method and the filter method give an error, ostensibly there is no such record, although it exists, how to solve this problem? error exactly in get not some grammar mistake, in query set!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! query just can't accept the string as parametr def mark_and_unmark_this_episode(request): return_dict = {} data = request.POST serial_slug = data.get('serial_slug') season_slug = data.get('season_slug') series_slug = data.get('series_slug') is_delete = data.get('is_delete') serie = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug) #seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug) print(serie) user = request.user watched_serial = seriess.serial_of_this_series watched_serie = seriess minutes_of_series = seriess full traceback with method GET (series = Series.objects.get(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)) self.model._meta.object_name serials.models.DoesNotExist: Series matching query does not exist. full traceback with method filter (series = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)) AttributeError: 'QuerySet' object has no attribute this part of views.py generic content on same page like error up, there this is work, i can get and filter by slug, Since these slugs are written in the parameters of the function, and everything works there, although in fact this slug is a string, but here everything … -
ValueError: Unable to configure handler 'file_handler_test': [Errno 2] No such file or directory: 'D:\\tmp\\ocean_run.log'
i run a project in linux use the command line './runserver test' which wrote in the package,json,it starts.however i try to run this project in Windows,i wrote in the cmd :'python manage.py runserver',it shows:'ValueError: Unable to configure handler 'file_handler_test': [Errno 2] No such file or directory: 'D:\tmp\ocean_run.log''.The back end of the system is built by python and django. -
Django: IOError [Errno 2] No such file or directory while Reading JSON file path using python
I am getting No such file or directory error , while trying to read JSON file from my local django app. Please Note i tried most of the method mentioned on Stackoverflow. so think before saying duplicate... here is my code, Try 1: json_data = os.path.join(BASE_DIR, STATIC_URL, "utils/config/my_json") data = open(json_data,'r') Try 2: json_data = os.path.join(STATIC_URL, "utils/config/my_json") data = open(json_data,'r') Try 3: json_data = os.path.join(BASE_DIR, STATIC_URL, "utils/config/my_json") with open(json_data,'r') as file: print file I am getting this error, IOError at /my_url/ [Errno 2] No such file or directory: '/static/utils/config/my_json' file url after performing os.path.join() is '/static/' where is the issue in my code? how to read JSON in my case? -
How to login either through a mobile no or a email address in django?
I initially used to login using email and password but now want to change it in such a way that we can login using either mobile no or email address and password.I am not able to understand what parts to change in my code as I do not want to delete already existing user and data. forms.py from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['first_name', 'last_name', 'email', 'password'] views.py class UserFormView(View): form_class = UserForm template_name = 'main/registration_form.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # cleaned (normalized) data email = form.cleaned_data['email'] password = form.cleaned_data['password'] user.username = email user.set_password(password) user.save() # return user objects if credentials are correct user = authenticate(username=email, password=password) if user is not None: if user.is_active: login(request, user) # request.user.username display their username return redirect('main:register2') return render(request, self.template_name, {'form': form}) class LoginForm(View): form_class = UserForm template_name = 'main/login_form.html' def get(self, request): form = self.form_class(None) if error: return render(request, self.template_name, {'form': form}, {'error': error}) else: return render(request, self.template_name, {'form': form}) def post(self, request): email = request.POST.get('email', '') password = request.POST.get('password', '') … -
Django allauth override clean_username and clean_email function
Hi have created a custom user model and introduced new fields for registration say for ex: phone and created custom adapter to save the field to database, but at the time of validation. clean_username() is used to check username already exist or not i need to check phone no for that username. so checking both username and phone no at same time. how can i get the phone no inside clean_username function. the below is the clean_username function in django allauth adapter def clean_username(self, username, shallow=False): """ Validates the username. You can hook into this if you want to (dynamically) restrict what usernames can be chosen. """ if not USERNAME_REGEX.match(username): raise forms.ValidationError(_("Usernames can only contain " "letters, digits and @/./+/-/_.")) # TODO: Add regexp support to USERNAME_BLACKLIST username_blacklist_lower = [ub.lower() for ub in app_settings.USERNAME_BLACKLIST] if username.lower() in username_blacklist_lower: raise forms.ValidationError(_("Username can not be used. " "Please use other username.")) # Skipping database lookups when shallow is True, needed for unique # username generation. if not shallow: username_field = app_settings.USER_MODEL_USERNAME_FIELD #appuuid_field = app_settings.USER_MODEL_APPID_FIELD assert username_field user_model = get_user_model() try: query = {username_field + '__iexact': username} user_model.objects.get(**query) except user_model.DoesNotExist: return username raise forms.ValidationError( _("This username is already taken. Please choose another.")) return … -
AttributeError at /print/8 'int' object has no attribute 'decode'
I'm trying to print the item in python-django by "ReportLab PDF" and i have an error like this: AttributeError at /print/8 'int' object has no attribute 'decode' I have codes in 9 files models.py class Games(models.Model): title = models.CharField(max_length=50) type = models.ForeignKey("Types") date_of_production = models.DateField() producer = models.ForeignKey("Producers") availability = models.BooleanField() account = models.IntegerField() language = models.ForeignKey("Languages", default='') price = models.CharField(max_length=10) abbr = models.CharField(max_length=5) def __str__(self): return self.title class Producers(models.Model): name = models.CharField(max_length=10) date = models.DateField() def __str__(self): return self.name class Types(models.Model): type = models.CharField(max_length=10) def __str__(self): return self.type class Languages(models.Model): language = models.CharField(max_length=15) def __str__(self): return self.language Admin.py from django.contrib import admin #from main.models import Game from main.models import Games from main.models import Producers from main.models import Types from main.models import Languages # Register your models here. #admin.site.register(Game) admin.site.register(Games) admin.site.register(Producers) admin.site.register(Types) admin.site.register(Languages) forms.py from django import forms class GamesForm(forms.Form): title = forms.CharField(label= "Nazwa gry", max_length=50) type = forms.CharField(label= "Typ gry", max_length=10) date_of_production = forms.DateField(label= "Data produkcji") producer = forms.CharField(label= "Nazwa producenta", max_length= 10) availability = forms.BooleanField(label= "Czy jest dostępne?") account = forms.IntegerField(label= "Ilość dostępnych sztuk") language = forms.CharField(label= "Języki", max_length=50) price = forms.CharField(label= "Cena", max_length=10) abbr = forms.CharField(label= "Skrót waluty", max_length=5) class ProducersForm(forms.Form): name = forms.CharField(label= "Nazwa producenta", max_length=10) … -
How to get table name from Django filter objects
I have diffrent tables with same columns Like class teachers(models.Model): x= models..CharField(max_length=250, blank=True, null=True); y= models..CharField(max_length=250, blank=True, null=True); class students(models.Model): x= models..CharField(max_length=250, blank=True, null=True); z= models..CharField(max_length=250, blank=True, null=True); I am using a function to process column x of both tables. So If any undesired values come in the value for x, I need to log that with the column name. Like f = students.objects.filter() def validate_x(obj): if obj.x == None: logger.error("None object found in table" + str(obj__tablename)) return False else: return True for i in f: validate_result = validate_x(i) My actual scenario is not null check. I just tried to explain it with this example. Is there any way to achieve this. I am using Django 1.6 -
Organize a similar form
Django==1.11.2 I'd like to organize another form similar to the form below. This form is used to save FrameDate model. But I need another form which will be used to search for frames. That is it will not be used to save a model. At search page necessary are: from_date and through date. The similarity of the form for the search page and this FrameDateForm is mainly validators and auxiliary methods. The difference is: Frame must be excluded completely in case of the search form. I tried inheritance but failed. In other words, i tried something like this: class SearchDateForm(FrameDateForm): class Meta(FrameDateForm.Meta): exclude = ["frame",] Well, this doesn't work. Could you give me a kick here: how to cope with this problem. This is a form: class FrameDateForm(forms.ModelForm): def ceil_day(self, day, month, year): pass def handle_from_through_date(self, prefix): pass def is_valid(self): pass def fill_through_date(self): pass def validate_through_later_than_from(self): pass def clean(self): self.fill_through_date() self.validate_through_later_than_from() return super(FrameDateForm, self).clean() class Meta: model = FrameDate exclude = [] widgets = { 'frame': forms.HiddenInput(), 'from_date': forms.SelectDateWidget(years=YEARS), 'through_date': forms.SelectDateWidget(years=YEARS) } Model (to be on the save side): class FrameDate(models.Model): frame = models.ForeignKey(Frame, blank=False, on_delete=models.PROTECT, verbose_name=_("frame")) from_date = models.DateField(null=True, blank=False, verbose_name=_("from")) through_date = models.DateField(null=True, blank=True, verbose_name=_("through")) -
How can i reformat dates
Hey guys i receive my data from oanda and plot it via django in charts.js class ChartData(APIView): def get(request, *args, **kwargs ): data = oanda.get_history(instrument='EUR_USD', # our instrument start='2016-10-01' , # start data end=time.strftime("%Y-%m-%d"), # end date granularity='D') # minute bars # 7 df = pd.DataFrame(data['candles']) # 8 data50 = oanda.get_history(instrument='EUR_USD', # our instrument start='2016-10-01', # start data end='2017-01-01', # end date granularity='D') # minute bars # 7 df50 = pd.DataFrame(data50['candles']) # 8 data200 = oanda.get_history(instrument='EUR_USD', # our instrument start='2016-6-01', # start data end='2017-01-01', # end date granularity='D') # minute bars # 7 df200 = pd.DataFrame(data200['candles']) # 8 history = df['openBid'] date_labels = df['time'] history = df['openBid'] date_labels = df['time'] data = { "history": history, "date_labels": date_labels, } return Response(data) Now the dates are formatted as you may see in the screenshot. Hoch can i format the dates in the following format DD/MM/JJJJ? Thanks in advance Screenshot -
Access denied for user 'www-data'@'localhost' (using password: NO) django 1.11.2
I am having trouble setting up django in compute engine instance. in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': '/home/gnanavel/work/my.cnf', }, } } and the configuration file # my.cnf [client] database = apin user = apin_admin password = ************* default-character-set = utf8 while trying logging in to admin site, I am getting the following error. enter image description here set-up: google compute engine instance debian 8 mysql Ver 15.1 Distrib 10.1.24-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2 apache2 aith wsgi For some reason django ignoring my user configuration and using www-data. I have tried creating www-data as mysql user with all privileges, that didn't work either. -
How to solve the circular import error in django?
I know the error is probably due to circular import error but not having much knowledge about it I am not able to correct it. I have tried using the methods given in similar questions but couldn't resolve it.The project has two apps consult and main and I need to import their models into each other, consult/models.py from django.db import models from django.contrib.auth.models import User from main.models import Customer class Question(models.Model): name = models.ForeignKey(Customer, on_delete=models.CASCADE) type = models.CharField(max_length=100, default="SkinCare") title = models.CharField(max_length=1000) body = models.CharField(max_length=1000000) image = models.FileField(blank=True, default=None) time = models.DateTimeField() deltatime = models.IntegerField(default=0) def __str__(self): return str(self.time) class Reply(models.Model): name = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(Customer, on_delete=models.CASCADE) text = models.CharField(max_length=10000000000) like = models.IntegerField(default=0) dislike = models.IntegerField(default=0) time = models.DateTimeField() deltatime = models.IntegerField(default=0) def __str__(self): return str(self.time) main/models.py from django.contrib.auth.models import User from django.db import models from consult.models import Question, Reply class Customer(models.Model): name = models.ForeignKey(User, null=True) gender = models.CharField(max_length=100) skin_type = models.CharField(max_length=1000) hair_type = models.CharField(max_length=1000) bookmarked = models.ManyToManyField(Question) def __str__(self): return str(self.name) When I run try to migrate the appps the following error comes: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Nikhil Khandelwal\AppData\Local\Programs\Python\Python35- 32\lib\site-packages\django-1.10.4- py3.5.egg\django\core\management\__init__.py", line 367, in execute_from_ command_line utility.execute() File … -
Error importing airport names using django-airport
I have installed and configured both django-cities and django-airport. But i am getting error while importing airport data via this command - ./manage.py airports The error is - Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/itsd/venv/mnq_v2/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/itsd/venv/mnq_v2/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/itsd/venv/mnq_v2/lib/python3.5/site-packages/django/core/management/__init__.py", line 208, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/itsd/venv/mnq_v2/lib/python3.5/site-packages/django/core/management/__init__.py", line 40, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/home/itsd/venv/mnq_v2/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/itsd/venv/mnq_v2/lib/python3.5/site-packages/airports/management/commands/airports.py", line 29, in <module> class Command(BaseCommand): File "/home/itsd/venv/mnq_v2/lib/python3.5/site-packages/airports/management/commands/airports.py", line 35, in Command option_list = BaseCommand.option_list + ( AttributeError: type object 'BaseCommand' has no attribute 'option_list' How can i solve this problem ? My Django version is - 1.10.4 -
How to populate the subsequent choice fields in django?
I'm a Django beginner and I've been through the clever-select and chained-selects, but can't just seem to tinker it for my purpose. Let's say I have a model something like this, class XYZ(models.Model):   ...   attribute1 = models.CharField(max_length=100, blank=True)   attribute2 = models.CharField(max_length=100, blank=True)   attribute3 = models.CharField(max_length=100, blank=True)   attribute4 = models.CharField(max_length=100, blank=True)   attribute5 = models.CharField(max_length=100, blank=True)   ... What i am planning to do is create a template where i can house a set of dropdowns which will be linked to the above-said attributes. Initially, the first dropdown will contain the values of attribute1, retrieved from the database, and based on the selected value, attribute 2 dropdown should be populated with relevant values. -
my Django form is not validating
i am having trouble validating my django form. my form is not validating. can anyone please examine my code and point out exactly where i am doing wrong. here are my codes. models.py- from django.db import models classcommentbox (models.Model) : box=models.CharField(max_length= 50 ) forms.py- from django.forms import ModelForm from . models import commentbox class commentboxForm(ModelForm): class Meta: model=commentbox fields=['box'] views.py- from django.http import HttpResponse from . models import commentbox from . forms import commentboxForm def submit(request): if request.method=="POST": form=commentboxForm(request. POST) if form.is_valid(): return HttpResponse('valid') else: return HttpResponse('not Valid') else: return HttpResponse("error") template- <form action="{% url 'poll:submit' %}"method="POST"> {%csrf_token%} <label for"comment"> say something: </label> <textarea class="form-control" rows="3" id="comment"> </textarea> <button type="button"> submit </button> </form> -
Overriding _create classmethod
I am using django and have a custom method for creating new objects of a certain model: class DiseaseFactory(factory.django.DjangoModelFactory): class Meta: model = models.Disease def _create(cls, model_class, *args, **kwargs): obj = model_class.create_new(first_name=f"Disease{uuid.uuid4()}") return obj When I try to create an instance of DiseaseFactory using DiseaseFactory.create(), it throws me the error: TypeError: _create() missing 1 required positional argument: 'model_class' What am I doing wrong? -
How to query set as ORDER BY and GROUP BY in django?
this my query: SELECT kategoriharga,ongkoskirim,diskon,ratingproduk,ratingtoko,label FROM (SELECT * FROM pohonkeputusan where perdaerah='Kabupaten Toba Samosir' order by label) AS sub GROUP BY kategoriharga,ongkoskirim,diskon,ratingproduk,ratingtoko,label How to make to be query set in Django?