Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retrieve data from manytomany table in python django based on its ID
Suppose there are two tables 1. mysql table name : user, Django model name: User 1. mysql table video : user, Django model name: Video User model contain one field as videos = models.ManyToManyField(Video, blank=True, null=True, related_name='video') Now i have a new mysql table name: user_videos +-------------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------------+---------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | user_id | int(11) | NO | MUL | NULL | | | video_id | int(11) | NO | MUL | NULL | | +-------------------+---------+------+-----+---------+----------------+ now i need to retrieve data my django like this mysql query (select * from user_videos order by id desc;) user.videos.all() is giving me order by video.id not user_videos.id Any good approach to do this by using models in python django without using a raw query. -
NoReverseMatch at /series/ Reverse for '{'serial_slug': '', 'season_slug': 'Season_1', 'series_slug': 'Episode_1'}' i can get 'serial_slug'
i can get the #serial_slug, but he have and he is located in module! Pls help someone)) just some text, because stackoverflow ask me, add more text, but i don't know what to add! this is my url.py from django.conf.urls import include, url from .views import homeview, post_of_serial, post_of_season, post_of_serie urlpatterns = [ url(r'^$', homeview, name='homeview'), # /series/ url(r'^(?P<serial_slug>[\w-]+)/$', post_of_serial, name='post_of_serial'), # /series/Prison_Break/ url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/$', post_of_season, name='post_of_season'), # /series/Prison_Break/season_5/ url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/(?P<series_slug>[\w-]+)/$', post_of_serie, name='post_of_serie'), # /series/Prison_Break/season_5/2/ ] this is my piece of modules.py class Series(models.Model): id = models.AutoField(primary_key=True) rus_name = models.CharField(max_length=60) eng_name = models.CharField(max_length=60) is_active = models.BooleanField(default=True) season_of_this_series= models.ForeignKey(Season, default=True) serial_of_this_series= models.ForeignKey(Serial, default=True) number_of_series = models.IntegerField(default=0, blank=True, null=True) slug = models.SlugField(unique=False, blank=True) description = models.TextField(max_length=700, blank=True, default=None) rating = models.FloatField(default=0, blank=True) timestamp_rus = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) timestamp_eng = models.CharField(max_length=60) time_of_series = models.DecimalField(max_digits=10, decimal_places=2, default=0) def get_absolute_url(self): return reverse('series:post_of_serie', kwargs= {'serial_slug': self.serial_of_this_series.slug, 'season_slug': self.season_of_this_series.slug, 'series_slug': self.slug}) def __str__(self): return "%s | %s" % (self.rus_name, self.number_of_series) class Meta: ordering = ["-timestamp_rus"] verbose_name = 'Series' verbose_name_plural = 'Series' this is my views.py def homeview(request, *args, **kwargs): full_path = Series.objects.all() context = {"full_path":full_path,} return render(request, 'home.html', context) this is template {% block content %} <div class="container"> <div class="row"> <div class="col-sm-3"></div> <div class="col-sm-6"> {% for … -
change with sed changing the order of parametres
I'm trying to make a bulk change with sed in a directory, from {{ form|as_bootstrap }} to {% bootstrap_form form %}, but "form" can be any name like "process_form" or "user_form". I found a grep that list all of them: grep -r '{{ [a-z_\.]*^\|as_bootstrap }}' ./ So I'm trying with this grep/sed command but it doesn't work: grep -rl '{{ [a-z_\.]*^\|as_bootstrap }}' ./ | xargs sed -Ei s@'{{ \([a-z_\.]*\)^\|as_bootstrap }}'@'{% bootstrap_form \1 %}'@g Can you point me to the error in the sed regexp ?? -
AttributeError: 'function' object has no attribute 'html'
I am rendering a html page in django but it's give error. in views.py def testing(request): return render_to_response(index.html) in urls.py urlpatterns = [ url(r'^testing$', views.testing, name='testing'), url(r'^calculate$', views.calculate, name='calculate'), ] other function is working fine. index.html is in template directory. I don't know why it is giving internal server error ??? please help me. -
Show in template number of new objects?
I have task but dont know how to realise it. Any help would be appreciated! In my django project I have modal "Task". Any task has a lot of comments. Here below you can see my code. I need to show number of new comments when user open the page. For example, when the user came out the page it was 4 comment to the task and then again after a certain time goes to a page and see the number of new comments left by other users. How to realise it? I am little bit comfused? models.py: class Task(models.Model): comments = models.ManyToManyField("Comment") class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created = models.DateTimeField(auto_now_add=True) html.py: (Number of new comments: ?) List of comments: {% for comment in task.comments.all %} {{ comment.author }} {{ comment.created }} {{ comment.text }} {% endfor %} -
Android application with django backend full source code?
I need a complete source code of an android application with django backend including it django source code? Since I'm new to django simple django project would be fine. -
Django error with connect mysql
At first i try to connect the mysql in .py,it is successful import pymysql db = pymysql.connect(host='localhost',user='root',passwd='admin',port=3306) cursor = db.cursor() cursor.execute("SELECT VERSION()") data = cursor.fetchone() print ("Database version : %s " % data) db.close() But when i use in the Django,is wrong DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'testdb', 'USER':'root', 'PASEWORD':'admin', 'HOST':'localhost', 'PORT':'3306', } } ----the error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb ----i add the "import pymysql"in "settings.py" the error: ImportError: Could not import settings 'HelloWorld.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named pymysql -
sqlite3.OperationalError: no such table: django_content_type
I am trying to run app not written by me app. When I write python manage.py makemigrations I got: Traceback (most recent call last): File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: django_content_type The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 115, in populate app_config.ready() File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready self.module.autodiscover() File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Users\direwolf\Documents\web\python\alexbog80-motivity-3e5c21f03b3e\app\motivity\admin.py", line 23, in <module> admin.site.register(Offer, OfferAdmin) File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\sites.py", line 110, in register system_check_errors.extend(admin_obj.check()) File "C:\Users\direwolf\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\admin\options.py", line 117, in check return self.checks_class().check(self, **kwargs) … -
NoneType err saving referral url
When a user registers in my application, I'm trying to save the referral url from their session cache to their user profile. However, it doesn't successfully get and pass the url: File "/Users/venv/app/app/users/views.py", line 215, in register user.user_web_info(request.session._session_cache) File "/Users/venv/app/app/users/models.py", line 79, in user_web_info parsed_uri = urlparse(self.referrer) File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py", line 143, in urlparse tuple = urlsplit(url, scheme, allow_fragments) File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urlparse.py", line 182, in urlsplit i = url.find(':') AttributeError: 'NoneType' object has no attribute 'find' views.py def register(request): user_form = UserForm() if request.user.is_authenticated(): messages.warning(request, 'You are already registered and logged in.') return render(request, 'public/register.html', {'form': user_form}) if request.method == "POST": user_form = UserForm(request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.user_web_info(request.session._session_cache) user.save() user = authenticate(username=request.POST['username'], password=request.POST['password']) user.update_user_info(request.META) send_mail( settings.REGISTER_EMAIL_SUBJECT, settings.REGISTER_EMAIL_MESSAGE.format(user.username), settings.REGISTER_EMAIL_FROM, [user.email]) login(request, user) return redirect('home') return render(request, 'public/register.html', {'form': user_form}) models.py class CustomUser(AbstractUser): # user model def user_web_info(self, request_session_cache): self.referrer = request_session_cache.get('REFERER') parsed_uri = urlparse(self.referrer) self.referring_domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri) self.landing_page = request_session_cache.get('landing_page') query_dict = parse_qs(urlparse(self.landing_page).query) def __unicode__(self): return "<CustomUser:{}>".format(self.username) I've tried a few different variations of defining user_web_info, and I'm obviously missing something, but not clear why the object is None thanks -
generate iframe from django tag
I managed to create a REST api with multiple items like this { "title": "problem_demo.0", "html": "<div><iframe src=/scenario/problem_demo.0/ width=\"400\" height=\"500\"></iframe></div>", "description": "desc", "url": "/scenario/problem_demo.0/" }, And i managed to extract some data and render them in my template like this views.py if embedserializer.is_valid(): embed = embedserializer.validated_data return render(request, 'workbench/dir/xblock.html', {'embed': embed}) xblock.html % block content %} <ul> <li>title : {{ embed.title}}</li> <li>description: {{ embed.description }}</li> <li>html : {{ embed.html }}</li> <li>url : {{ embed.url }}</li> </ul> {% endblock %} What i want is to be able to get an actual iframe when i add {{ embed.html }} in my template and not the value of the key "html". -
Django inline formset to edit form
I have a model like this in models.py from django.contrib.auth.models import User class Education(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) sch_name = models.CharField(max_length=50) sch_loc = models.CharField(max_length=50) sch_prog = models.CharField(max_length=50) sch_duration = models.CharField(max_length=50) sch_about = models.TextField() def __unicode__(self): return self.sch_name I want to create an inlineformset that can allow me edit this form in forms.py class EducationModelForm(forms.ModelForm): sch_about = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'About Your School'})) sch_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'School Name'})) sch_loc = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'School Location'})) sch_prog = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'School Programme'})) sch_duration = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'School Duration'})) class Meta: model = Education # exclude = ['user'] fields = ['sch_name', 'sch_loc', 'sch_prog', 'sch_duration', 'sch_about'] In my views.py def form_education_update(request, username, id=None): education = get_object_or_404(Education, id=id) EducationModelFormSet = inlineformset_factory(Education, User, form=EducationModelForm, max_num=5) edu_formset = EducationModelFormSet(request.POST or None, instance=education) if edu_formset.is_valid(): education = edu_formset.save(commit=False) education.user = request.user education.save() else: edu_formset = EducationModelFormSet(instance=education) context = { 'title': 'Form', 'edu_formset': edu_formset, 'education': education, } template = 'cv_formset.html' return render(request, template, context) Everytime I go to the url link I get this error ValueError 'auth.User' has no ForeignKey to 'cv.Education'. I just cant figure out what is wrong. In my models clearly User has a foreignkey to Education. Can someone please help me out? -
Query for retrieve data with user fk Django 1.11
I'm trying to retrieve data from user. I have my model like this: from django.contrib.auth.models import User class anotherModel(models.Model): user = models.ForeignKey(User) address = models.CharField(....) Etc... And in my view I have my query like this query = anotherModel.objects.filter(user_id=request.user) And this QuerySet is empty. I need to retrieve this data in the user profile Note: I wrote this from phone do I didn't write the full code. Just the necessary. Thanks a lot. -
Django, Perform 'iexact' lookup on EmailField
PostgreSQL DB, EmailField in model. I have a form where a user enters their email address, they are looked up and if they have a record an email is sent to complete the steps. An issue that turned up is if the user enters bob@test.com into the search but their entry in the DB is Bob@test.com they can't be found. I switched: user = User.objects.get(email=entered_email) to: user = User.objects.get(email__iexact=entered_email) However that didn't work, it seems that iexact is not supported on EmailFields. I'm trying to figure out the easiest solution, without refactoring too much. Since 99.9% of the web treats email addresses as can-insesitive I could migrate the email column using .lower() and then then do a exact match using entered_email.lower() Doing this I would then have to make sure all places the email address gets saved is convert using .lower() - thinking about it I could override the models save and then do that... but I'm not sure. But at the moment I'd be fine with case-insisite lookup on the already existing EmailField column. -
Django MultiValueField
I'm struggling with some Django, where I want to make a custom MultiValueField combined with MultiWidget. I've read misc. tutorials, but it seem I'm missing something - most of them were quite old, which I suspect could be the reason. I'm using Django 1.10. Goal: Make a custom field that provides three dropdowns for a form. So far, no requirements to the contents of the dropdowns - first I just want to see them in my form :-) I have a fields.py file, containing: from django import forms from widgets import MyCustomWidget class MyCustomField(forms.MultiValueField): widget = MyCustomWidget def __init__(self, *args, **kwargs): fields = ( forms.CharField(max_length=31), forms.CharField(max_length=31), forms.CharField(max_length=31), ) super(MyCustomField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): return "-".join(data_list) And then there's a widgets.py, containing: import re from django import forms class MyCustomWidget(forms.MultiWidget): def __init__(self, attrs=None): widgets = ( forms.widgets.Select(attrs=attrs, choices=[("1", "1")]), forms.widgets.Select(attrs=attrs, choices=[("2", "2")]), forms.widgets.Select(attrs=attrs, choices=[("3", "3")]), ) super(MyCustomWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return re.split(r"\-", value) return [None, None, None] forms.py: from django.forms import ModelForm from django import forms class MyCustomForm(forms.ModelForm): class Meta: model = MyCustomModel fields = ("name") name = forms.CharField(widget=MyCustomField) This works fine when migrating, but I try to view the form, I get this error: … -
ChartJS chart not rending in Django project
I'm working on a Django project and am trying to get ChartJS working by using the default example they have on their documentation website (http://www.chartjs.org/docs/). I'm also trying to use this video(https://www.youtube.com/watch?v=B4Vmm3yZPgc) in order to help me set up my chart. In my Django, I have an app called DisplayData which is where I'm trying to get the graph displayed. The DisplayData app is set up as follows: And my Display.html file looks as follows: {% extends "RecordEvent/nav.html" %} <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> </head> <script> {% block jquery %} var endpoint = 'display/api/chart/data/' $.ajax({ method: "GET", url: endpoint, success: function(data){ console.log(data) }, error: function(error_data){ console.log("error") console.log(error_data) } }) var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { … -
Is there an open source project to convert Django models to Bigquery tables?
Due to lack of good googling skills, I ended up writing my own classes and utilities. If there isn't I am willing to start an open source project for the same. -
What does fail_silently do in send_mail() django?
I have read the documentation of send_mail() but the purpose of fail_silently is not clear yet. -
Django tables 2 add link column to edit model
I'm using django-tables2 for a project. I want to create a new column which links to the admin page of that model so it can be edited. Can I do that? -
SimpleUploadedFile won't POST
I want to pass a dictionary to a function using Client. It looks like that: response = self.client.post( '/upload_image/', {'image': image, 'tags': ['orion', ]}) In my view, it's posting data too i have: print(request.POST) image = request.POST['image'] tags = reguest.POST['tags'] There is a MultiValueDictKeyError on request.POST['image']. print(request.POST) shows that dictionary looks like: <QueryDict: {'tags': ['orion']}> image objects is: image = SimpleUploadedFile( 'kitties.png', b'kitties_in_boxes', 'image/png') I suppose there is another way I could test uploading images functionality, but does someone know why this doesn't works? -
how to get image url from django form
i have create a simple django form where the authentication user can select one of personal images where have upload before and i want do something with that request in my views.py. but i dont know how to take the image url from that request in my view because first i using request.user in the form to take only self user images and i dont know how to continue and finaly i take that images url. the form work great show me only the self user images any idea ? here the code views.py @login_required(login_url="login/") def carlist(request): Myform = MyModelForm(user=request.user) return render(request,'about.html',{'Myform':Myform}) select django form : class MyModelForm(ModelForm): def __init__(self, *args, **kwargs): # extract "user" from kwrags (passed upon form init) if 'user' in kwargs: self.user = kwargs.pop('user') super(MyModelForm, self).__init__(*args, **kwargs) # generate the choices as (display, value). Display is the one that'll be shown to user, value is the one that'll be sent upon submitting (the "value" attribute of <option>) choices = MyModel.objects.filter(user=self.user).values_list('upload', 'id') self.fields['upload'].widget = Select(choices=choices) class Meta: model = MyModel fields = ('upload',) html : <form class="" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ Myform}} <input type="submit" name="" value="Submit"> -
Seeing and setting only one column in django admin
models.py from django.db import models from random import randint def randomnumber(): return str(randint(1,10)) class something(models.Model): name = models.CharField(max_length=20) whatever = models.CharField(max_length=20, default=randomnumber()) def __str__(self): return self.name I am trying to create a database for users in admin, where they would be able to see and add only name to it, however 'whatever' field would be added as well, when new 'name' would be added to database. How could i do that? -
Django send-mail [Errno -2] Name or service not known
hi i have problem in sending mail in Django I set my gamil following this link: https://support.google.com/mail/answer/7126229?visit_id=1-636278779262945155-948643181&rd=1#cantsignin and i tried every solution online but still get [Errno -2] i found someone said it is because the DNS problem ,can some one tell me whats wrong with my code and is there any solution ? #views.py import django from django import settings from django.core.mail import send_mail def contact(request): send_mail('subject','message',settings.EMAIL_HOST_USER,['zwt467875460@gmail.com'],fail_silently = False) return HttpResponseRedirect('/contact/thanks') def thanks(request): return HttpResponse('thanks!') #settings.py #email config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gamil.com' EMAIL_PORT = 587 EMAIL_HOST_USER='zwt467875460@gmail.com' EMAIL_HOST_PASSWORD='*********' #my gmail password EMAIL_USER_TLS = True DEFAULT_FORM_EMAIL = EMAIL_HOST_USER ACCOUNT_EMAIL_VERIFICATION = 'none' #traceback error Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/wenting/WTDjango/mysite/books/views.py", line 30, in contact send_mail('subject','message',settings.EMAIL_HOST_USER,['zwt467875460@gmail.com'],fail_silently = False) File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/mail/__init__.py", line 62, in send_mail return mail.send() File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/mail/message.py", line 342, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/mail/backends/smtp.py", line 100, in send_messages new_conn_created = self.open() File "/usr/local/lib/python2.7/dist-packages/Django-1.10.6-py2.7.egg/django/core/mail/backends/smtp.py", line 58, in open self.connection = connection_class(self.host, self.port, **connection_params) File "/usr/lib/python2.7/smtplib.py", line 256, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python2.7/smtplib.py", line 316, in … -
Connecting Django with MSSQL server
I'm trying to connect my Django app to SQL Server 2016. I've tried using django-pyodbc but it doesn't support Django 1.11. Instead I installed django-mssql 1.8. When I try to run the application I get this error. TypeError was unhandled by user code Message: 'NoneType' object is not callable At execute_from_command_line(sys.argv) in manage.py Here is my DATABASES from settings.py DATABASES = { 'default': { 'ENGINE': 'sqlserver_ado', 'NAME': 'TEST2', 'HOST': 'PCNAME\SQLEXPRESS', 'USER': '', 'PASSWORD': '', 'OPTIONS' : { 'provider': 'SQLOLEDB', 'use_mars': True, }, } } I've tried both the default and SQLOLEDB provider but always get the same error. I've also tried with and without user and password set but the error remains the same. I am able to connect to a local MySQL DB just fine. I'm running Windows 10, Visual Studio 2015, SQL Server Express 2016 -
How to pass choices from a ForeignKey/ManyToManyField to a Modelform?
I am trying to create a form out of a Modelform, but i am having trouble getting the choices i set initially in the specific Models passed on to the form. All I get are objects with no specific naming. For instance the choices for the regional_group field will contain one RegionalGroup object, but nothing else. What is the correct way to pass specific choices on to a form when the sqlite3 database is previously not populated by anything to get out of it? models.py from django.db import models class RegionalGroup(models.Model): graz = 'GRZ' sbgooe = 'SBO' wien = 'VIE' tirol = 'TRL' leoben = 'LBN' REGIONAL_GROUP_CHOICES = ( (graz, 'RG Graz'), (sbgooe, 'RG Salzburg/Oberösterreich'), (wien, 'RG Wien'), (tirol, 'RG Innsbruck'), (leoben, 'RG Leoben') ) name = models.CharField(choices=REGIONAL_GROUP_CHOICES, max_length=10) class FocusGroup(models.Model): it = 'IT' fundraising = 'FR' pr = 'PR' FOCUS_GROUP_CHOICES = ( (it, 'AG IT'), (fundraising, 'AG Fundraising'), (pr, 'AG PR') ) name = models.CharField(choices=FOCUS_GROUP_CHOICES, max_length=10) class ProjectGroup(models.Model): tailoring_togo = 'TT' fluechtlingshilfe = 'FH' vortragsreihe = 'VR' PROJECT_GROUP_CHOICES = ( (tailoring_togo, 'PG Tailoring Togo'), (fluechtlingshilfe, 'PG Flüchtlingshilfe'), (vortragsreihe, 'PG Vortragsreihe') ) name = models.CharField(choices=PROJECT_GROUP_CHOICES, max_length=10) class Member(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True, max_length=100) regional_group = … -
Django append +1 in template
I have modal that displays uploaded images from ExamFile model that is foreign-key connected to Exam model. In order for lightbox galerry to work i need to specify slide number of each examfile picture, so i need to append 1 for every picture (probably in template?) i have this script: {% for file in exam.examfile_set.all %} <div class="row"> <div class="column"> <img src="{{file.exam_file.url}}" width=60 height="60" onclick="openModal();currentSlide(//this is where i need to append +1 for every file in exam.examfile_set.all //)" class="hover-shadow cursor"> </div> {% endfor %} <div id="myModal" class="modal"> <span class="close cursor" onclick="closeModal()">&times;</span> <div class="modal-content"> {% for file in exam.examfile_set.all %} <div class="mySlides"> <div class="numbertext">1 / 4</div> <img src="{{file.exam_file.url}}" style="width:100%"> </div> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> <div class="caption-container"> <p id="caption"></p> </div> </div> </div> </div> <script> function openModal() { document.getElementById('myModal').style.display = "block"; } function closeModal() { document.getElementById('myModal').style.display = "none"; } var slideIndex = 1; showSlides(slideIndex); function plusSlides(n) { showSlides(slideIndex += n); } function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("demo"); var captionText = document.getElementById("caption"); if (n > slides.length) {slideIndex = 1} if (n < 1) {slideIndex = slides.length} for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; …