Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
utf-8' codec can't decode byte 0xb5 in position 10: invalid start byte [on hold]
I don't know this error enter image description here Error Meassage ' 'utf-8' codec can't decode byte 0xb5 in position 10: invalid start byte ' Please tell me why show me error I use Python, Django, WeasyPrint -
How to import Celery app in Django app-level task?
I follow the guide http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html but I can't find how to import celery app in app-level tasks.py, where it is used like this: @app.task() def do_my_task(): -
Dynamic models django
Let's say i have 10 tables in 1 Db and the table names differ and data is different, but the structure of the tables are the same. And then i have 1 more table that collects all the table names and the creation date of that table. Example: PrimaryTable table_name_1 table_name_2 .... table_name_10 and the structure of all tables example: class PrimaryTable(models.Model): name = models.CharField(db_column='Name', unique=True, max_length=100) date = models.CharField(db_column='Date', max_length=100) class Meta: managed = True db_table = 'Primary Table' def __str__(self): return self.name class table_name_1(models.Model): title = models.TextField(db_column='Title', blank=True, null=True) url = models.CharField(db_column='Url', unique=True, max_length=250, blank=True, null=True) description = models.TextField(db_column='Description', blank=True, null=True) created_at = models.DateTimeField(db_column='Created_at') class table_name_2(models.Model): title = models.TextField(db_column='Title', blank=True, null=True) url = models.CharField(db_column='Url', unique=True, max_length=250, blank=True, null=True) description = models.TextField(db_column='Description', blank=True, null=True) created_at = models.DateTimeField(db_column='Created_at') and so on... And i only want to make 1 class that includes all those tables that have same structure and call it when i choose the table from the PrimaryTable. I don't want to use "python manage.py inspectdb > models.py" every time i create a table. I want to have access to the new created table instantly when i create it. -
How to customise attributes of forms.Select options in Django
I am working on a custom requirement which demands to customise select option attributes. My dropdown will show the list of options, and some of those options should be shown as disabled as per certain conditions. I have tried customising the Select widget attributes by passing disabled = disabled. But that disables the whole dropdown. By looking into the code of django 1.11.5, it seems that the attributes applied on Select will be applied to its options. Can anyone please suggest how this functionality can be achieved? Thank you -
Change the text of a sidemenu item on django-admin interface
I have a couple of items (namely authentication and user_central) on the side menu of my django-admin interface which are shown in the screenshot below. I want to change their text. How can I do that? I know a litle bit about overriding the template, but which blocks to override for these two menu items? -
Getting error when running sql server query in Python
I am building a web app using Django framework of Python , DB is Sql server Azure ,using Pyodbc. I have an issue i am unable to resolve , i am getting a parameter(file_name) which is a string and when running the query with the parameter i am getting empty results in the first case and "sql = sql % tuple('?' * len(params)) TypeError: not all arguments converted during string formatting" in the 2nd case , what am i doing wrong? file_name=request.POST.get('filetodelete') with connections['default'].cursor() as c: 1st case parms=[file_name] sql='select * from banks_row_data where file_name=%s' c.execute (sql,parms) test=c.fetchall() 2nd case c.execute (sql,file_name) test=c.fetchall() -
AttributeError: module 'app.parse' has no attribute 'sheet'
I got an error: AttributeError: module 'app.parse' has no attribute 'sheet4' . In parse.py I wrote class DataRate(): data_rate ={} data_rate =defaultdict(dict) def try_to_int(arg): try: return int(arg) except: return arg book4 = xlrd.open_workbook('./data/excel1.xlsx') sheet4 = book4.sheet_by_index(0) in data_rate_savedata.py from . import parse def data_rate_save(): for row_index in range(0, sheet4.nrows): row = sheet4.row_values(row_index) row = list(map(try_to_int, row)) value = dict(zip(tag_list, row)) closing_rate_dict[value['ID']].update(value) user = User.objects.filter(corporation_id=closing_rate_dict[value['ID']]['NAME']) in main_save.py from app.parse import DataRate #parse DataRate() #save data_rate_save() When I run main_save.py, the error occurrs. I really cannot understand why this error happens because I import parse.py in data_rate_savedata.py, so I can access parse.py of 'sheet4' in data_rate_savedata.py. Should I write something in main_save.py? How can I fix this error? in models.py class User(models.Model): trunsaction_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) regist_date = models.DateTimeField(auto_now=True) user_id = models.CharField(max_length=200,null=True) name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) -
Why my django urls gets some bad garbage value
When i call http://127.0.0.1:8000 to call my homepage it automatically redirected to some bad random url like http://127.0.0.1:8000/ADwx or http://127.0.0.1:8000/GRpc urls.py url(r'^$', views.home, name='home'), views.py def home(request): if request.user.is_authenticated(): return HttpResponseRedirect('/dashboard') else: return render(request,'index/index.html') -
Django sending Email confusion
I've used one application with sending email to the user for notification. but in that application setting.py file contains some confusing terms like EMAIL_USE_TLS = True I'm not sure what this is and also EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'rquest186@gmail.com' what is the variety in this two and if host is declared here then def send_mail(title,message,reciver): try: mailS = 'smtp.gmail.com' mailP = 587 mailUsr = "idefusiontest2015@gmail.com" mailPass = "IDEF2017" # Create a text/plain message msg = MIMEMultipart('alternative') msg['Subject'] = title msg['From'] = mailUsr msg['To'] = reciver html="<html><head></head><body><p>"+message.replace("\n","<br>")+"</p></body></html>" part2 = MIMEText(html, 'html') msg.attach(part2) # Send the message via our own SMTP server, but don't include the s = smtplib.SMTP(mailS,mailP) s.ehlo() s.starttls() s.ehlo() s.login(mailUsr,mailPass) s.sendmail(mailUsr, [reciver], msg.as_string()) s.quit() except Exception as e: print(e) in this mailUsr = "idefusiontest2015@gmail.com" ???? what's this for ? I'm new to this. and it's confusing for me. thanks in adv. -
How to add multiple foreign key in Django
i am beginner in Django I have to models class Employee(models.Model): full_name = models.CharField(max_length=120,default=None) designation = models.CharField(max_length=80,default=None) class Leave(models.Model): employee = models.ForeignKey(Employee, related_name='employee') number_of_days = models.IntegerField(default=0) Now I have inline Leave Model with Employee in admin.py so that i can add as many leaves i want in employees But when i retrieve this model in views new leaves are created , all i want is one employee should show total = number of days , but it creates new leaves, not able to build any logic here i am stuck , please ask if u dint get it. -
Import error on my python Chatbot with no known parent pachage
it is my code. i could not solve it. if i comment error line, then next line gets same error -
Django import Models
i m trying to import A model from the file in the path "/usr/local/lib/python2.7/dist-packages". The file witch contain the model it's called table_class_corespondance so when i import it is:from table_class_corespondance import Users. Now in the Users class definition after i declare the field i write : class Meta: managed = False db_table = 'USERS' app_label = "banner_manager" so that Django will know that app will make referance this table. But unfortunatley this error still shows up: RuntimeError: Model class table_class_corespondance.Users doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Any idea what can i do to solve it? Sorry for my english -
Django, how to get information when confirm window'ok button is clicked
I want to know how to get event or result when confirm windows'ok button is clicked. I'm using Django. I wrote the code using xxx,, ((confirm( ,,, )" for u in myList -
Django ORM: group records by a field and then get the records with max value in each group
I have a model like this: Class Foo(model.Models): date = models.DateField() price = models.FloatField() volume = models.IntegerField() I want to get a list of all objects with the most price in each day! something like this: { 2017-01-01: {"date": 2017-01-01, "price": 1000, "volume": 210}, 2017-01-02: {"date": 2017-01-02, "price": 1032, "volumne": 242}, . . . } Can I do this with one query? The database is relatively large and performing a loop on dates is not going to work. -
Django: select_related to a table vs table's field
I have 2 models class A(models.Model): val = models.IntegerField() class B(models.Model): val2 = models.IntegerField() a = models.ForeignKey(A) class C(models.Model): b = models.ForeignKey(B) val3 = models.IntegerField() How is the query - C.objects.select_related('B').all() better than - C.objects.select_related('B__val2').all() And if not how query one can be optimised? -
Visual Studio Django app fails to build with StaticRootPath error
I'm writing my first Django app, and I have encountered a problem. When I go to build the project in visual studio, the build fails without giving any errors. The only way I can get it to show me an error at all is by changing the output to diagnostic mode, at which point it shows me this: Target "DetectStaticRootPath" in file "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\Python Tools\Microsoft.PythonTools.Django.targets" from project "C:\Users\OEM\Documents\TSM_shared\student-marketplace-v2\ecommerce test\ecommerce test.pyproj" (target "DjangoCollectStaticFiles" depends on it): Initializing task factory "RunPythonCommandFactory" from assembly "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Python\Core\Microsoft.PythonTools.BuildTasks.dll". Using "RunPythonCommand" task from the task factory "RunPythonCommandFactory". Task "RunPythonCommand" Task Parameter:Target=import test.settings as settings; print(settings.STATIC_ROOT or '') Task Parameter:TargetType=code Task Parameter:ExecuteIn=none Task Parameter:WorkingDirectory=. Task Parameter:Environment=DJANGO_SETTINGS_MODULE=test.settings Task Parameter:ConsoleToMSBuild=True Output Property: DjangoStaticRootSetting= Done executing task "RunPythonCommand" -- FAILED. Done building target "DetectStaticRootPath" in project "test.pyproj" -- FAILED. Those are the only parts of the build that fail. Below is my settings.py: INSTALLED_APPS = [ 'app', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'app/static/'),) STATIC_ROOT = os.path.join(BASE_DIR,'static/') Thank you for your time. -
ImportError: No module named 'parse'
I got an error,ImportError: No module named 'parse' . In parse.py I wrote class DataRate(): data_rate ={} data_rate =defaultdict(dict) def try_to_int(arg): try: return int(arg) except: return arg book4 = xlrd.open_workbook('./data/excel1.xlsx') sheet4 = book4.sheet_by_index(0) tag_list = sheet4.row_values(0) for row_index in range(0, sheet4.nrows): row = sheet4.row_values(row_index) row = list(map(try_to_int, row)) value = dict(zip(tag_list, row)) closing_rate_dict[value['ID']].update(value) user = User.objects.filter(corporation_id=closing_rate_dict[value['ID']]['NAME']) I wanna user DataRate class in data_rate_savedata.py,so I wrote import parse def data_rate_save(): if user2: if parse.closing_rate_dict[parse.value['ID']]['NAME'] == 'A': parse.user2.update(data_rate_under_500 = parse.closing_rate_dict[parse.value['ID']]['d500'], data_rate_under_700 = parse.closing_rate_dict[parse.value['ID']]['d700'], data_rate_upper_700 = parse.closing_rate_dict[parse.value['ID']]['u700']) I wanna use parse.py & data_rate_savedata.py in main_save.py,so I wrote from app.parse import DataRate #parse DataRate() #save data_rate_save() When I run main_save.py,I got an error ImportError: No module named 'parse',traceback says File "/Users/app/data_rate_savedata.py", line 1, in import parse is wrong.Is it IDE problem?Or am I wrong to write codes?How can I fix this error? -
ImportError: Couldn't import Django
I've already configured virtualenv in pycharm, when using the python managed. Py command E:\video course\Python\code\web_worker\MxOnline>python manage.py runserver Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? How should I fix it, I've installed django -
redirect reverse in Django
I'm working on Django 1.11 I want to redirect user from view. contents of myapp/accounts/urls.py app_name = 'accounts' urlpatterns = [ url(r'^$', views.ProfileView.as_view(), name='profile'), url(r'^profile/', views.ProfileView.as_view(), name='profile') ] and in myapp/accounts/views.py from django.contrib.auth.models import User # Create your views here. from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView, UpdateView class ProfileView(TemplateView): template_name = 'accounts/profile.html' class UpdateProfile(UpdateView): model = User fields = ['first_name', 'last_name'] template_name = 'accounts/update.html' def get_object(self): return self.request.user def get_success_url(self): messages.success(self.request, 'Profile Updated Successfully') return HttpResponseRedirect(reverse('profile')) This is giving error on redirect. NoReverseMatch at /accounts/update/ Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name. How to redirect user to profile page after updating profile details? How to redirect user to other app's view? -
Recover deleted Django migrations
On my production server I accidentally deleted my migrations directory in one of my apps. Multiple people work on the app, so at the time of making the app, what we did was push up our model changes without making any migrations locally, and than make the migrations on the production server, and migrate there. We did this because we were having migrations merge issues in the past, and thought this might be a good solution. Since there is no local copy of the migrations folder I fear its gone forever. My question is this. I can access phpPgAdmin in Webfaction, and the database has a django_migrations table. I thought one solution would be to find the latest migrations, lets say for example 0009_migration.py, and than simply rename a new migration file, 0010_migration.py for my next migration if I ever make any model changes in the future in that app. That way I can simple run migrate, and it will only be considered with the migration that it has yet to run, 0010_migration.py. But just out of curiosity, is there some command that will look at your PostgreSQL database, and create the migration files in your app migrations directory from … -
what are most frequently used real-time examples of Django custom middleware? It would be great if a code snippet is also shared
what are most frequently used real-time examples of Django custom middleware? It would be great if a code snippet is also shared. -
How to use Apache to serve Django server and React client?
I'm trying to configure Apache2 to serve Django for backend APIs (/api/), and React app for client side JS (/). I want the root path to load the React app (e.g. www.example.com/). I'm having a hard time. If I Alias/Documentroot the / to React's /build directory, then Apache stops serving Django. And conversely when I remove the Alias/Documentroot, then Django serves fine but React doesn't. How could I do this? Here's my httpd.conf file: ``` DocumentRoot /home/ubuntu/project/webapp/build/ Alias / /home/ubuntu/project/webapp/build/ <Directory /home/ubuntu/project/webapp/build> Require all granted </Directory> Alias /static /home/ubuntu/project/webapp/build/static <Directory /home/ubuntu/project/webapp/build/static> Require all granted </Directory> WSGIDaemonProcess server python-home=/home/ubuntu/python3.5/ python-path=/home/ubuntu/project/server WSGIProcessGroup server WSGIScriptAlias /admin /home/ubuntu/project/server/server/wsgi.py <Directory /home/ubuntu/project/server/server> <Files wsgi.py> Require all granted </Files> </Directory> ``` -
Would like to create a POST method for my Django API
I would like to create a POST method for my Django project while setting up the API. I have tried creating an override method for create but it gives me an integrityconstrain. I would like to make a post that stored all the field in a tidy JSON. I'm not sure if it's because of manytomanyfield that is causing the problems. Thank you in advances. Models.py class Results(models.Model): type = models.CharField(max_length=200, blank=True) question = models.CharField(max_length=200, blank=True) title = models.CharField(max_length=200, blank=True) ytid = models.CharField(max_length=200, blank=True) correct_answer = models.CharField(max_length=200, blank=True) incorrect_answers = ArrayField(models.CharField(max_length=200), blank=True) def __str__(self): return '{}, {}, {}, {}, {}, {}'.format(self.type, self.question, self.title, self.ytid, self.correct_answer, self.incorrect_answers) class Simulation(models.Model): sequence = models.PositiveIntegerField(unique=False) method = models.CharField(max_length=200) results = models.ForeignKey(Results, on_delete=models.CASCADE) class Meta: ordering = ['sequence'] def __str__(self): return '{}'.format(self.sequence) class respond_code(models.Model): respond_code = models.PositiveIntegerField(primary_key=True) simulation = models.ManyToManyField(Simulation) class Meta: ordering = ['respond_code'] def __str__(self): return '{}'.format(self.respond_code) Serializers.py class ResultsSerializer(serializers.ModelSerializer): class Meta: model = Results fields = ('type','question','title','ytid','correct_answer','incorrect_answers') class SimulationSerializer(serializers.ModelSerializer): results = ResultsSerializer(many=False) class Meta: model = Simulation fields = ('sequence','method','results') class respond_codeSerializer(serializers.ModelSerializer): simulation = SimulationSerializer(many=True) class Meta: model = respond_code fields = ('respond_code', 'simulation') def create(self, validated_data): simulations_data = validated_data.pop('simulation') simulation = Simulation.objects.create(**validated_data) for i in simulations_data: Simulation.objects.create(simulation=simulation, **i) for data in … -
Django 1.11 not discovering test cases inside tests folder
I have been doing this in earlier Django versions like 1.8, which I created a tests package inside the app and have different test cases in each files. Then I import the test cases inside __init__.py, exactly described in this SO But it seems doesn't work as expected in Django 1.11, it seems to work halfway, eg. When I run ./manage.py test app, it doesn't discover any tests. When I run ./manage.py test app.tests, it finds all the tests What am I doing wrong? -
Static Ports In Django w/ Visual Studio
Has anyone found out a way to have visual studio run a Django app on a static port rather than it changing ports every run? I have a separate program sending requests to the server but it becomes a hassle having to change the port every time I re run the server. Thanks in advance for any direction on the subject.