Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Added Many2Many now getting "ValueError: XXX needs to have a value for field "id" before this many-to-many relationship can be used"
I've read a bunch of similar sounding questions of SO, but somehow none of them have helped me solve my particular case. I added a ManyToManyField to represent "Likes" to my Photo model: class Photo(TimestampModerated): owner = models.ForeignKey('auth.User', related_name='photos', on_delete=models.CASCADE) uuid = models.UUIDField(default=uuid4, editable=False) slug = models.SlugField(max_length=80, editable=False) title = models.CharField(max_length=80, blank=False, null=False) description = models.TextField(verbose_name='description of entity', blank=True, null=True) photo = models.ImageField(upload_to=user_directory_path, height_field="height", width_field="width", blank=True) height = models.IntegerField(blank=True) width = models.IntegerField(blank=True) tags = TaggableManager(blank=True) hash = models.CharField(max_length=64, unique=True, null=True) size = models.BigIntegerField('size of file in bytes', blank=True, null=True) likes = models.ManyToManyField('auth.User', blank=True, null=True) class Meta: verbose_name_plural = "photos" def __str__(self): return self.title def delete(self, using=None, keep_parents=False): default_storage.delete("{}".format(self.photo)) super().delete() def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Photo, self).save(*args, **kwargs) Here is the view (at least the part that should matter for creating): class PhotoViewSet(viewsets.ModelViewSet): queryset = Photo.objects.all() serializer_class = PhotoSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsOwnerOrReadOnly, permissions.AllowAny,) parser_classes = (MultiPartParser, FormParser) def perform_create(self, serializer): serializer.save(owner=self.request.user, likes=[]) And here is the serializer: class PhotoSerializer(serializers.ModelSerializer, TaggitSerializer): owner = serializers.CharField(source='owner.username', read_only=True) tags = TagListSerializerField() photo = Base64ImageField( max_length=None, use_url=True, ) class Meta: model = Photo fields = ('photo', 'height', 'width', 'owner', 'slug', 'uuid', 'title', 'id', 'created', 'updated', 'moderation_code', 'tags', 'hash', 'description', 'size', 'likes') … -
-bash: acme.sh: command not found
I am trying to use LetsEncrypt, "a free, automated, and open certificate authority (CA), run for the public’s benefit", for my Django application. I am using Webfaction, and used this users tutorial to set up and run an ACME (Automated Certificate Management Environment) shell script. Everything goes smoothly until I add a new app to the root of my application for generating an ssl certificate. When I enter this command Le_HTTPPort=77777 acme.sh --test --issue -d domain.com -d www.domain.com --standalone with the domains, and port switched out, I get this error. -bash: acme.sh: command not found Admittedly, I'm not super linux savvy, getting by on what I need to develop web applications, so I'm not sure if I'm simply running the command from the wrong area, or if there is some other issue at hand. Do I need to run this command in my project, or since its listening to the port that my application is running on, could I even just run the command in a brand new terminal ? -
Is it expensive to send GET request on changing Text
Is it expensive to send GET request on changing Text? I'm sending GET request to check if username is obtained or not. I followed exactly how Instagram implemented on Register part. Basically it checks username everytime they type something in InputField. So if I recommend 'my_username' at the initial point and user changes to 'hi_user', I'm sending about 18 GET requests. Instagram is rich but I'm just a college student, so I just want to know if I can afford it. :P My GET request is very lite url: ${ROOT_URL}/profile/unamecheck/?un=${username} body: username response: {valid: true} Am I too much worrying? About my app: Django for Backend and React Native for Frontend. I'm planning to deploy my app on AWS EC2 and S3 -
NameError: name 'Area' is not defined
I made area data model in models.py. #coding:utf-8 from django.db import models class User(models.Model): name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) area = models.ForeignKey(Area) class Area(models.Model): name = models.CharField(max_length=20, verbose_name='area') class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='city') area = models.ForeignKey(Area) class City(models.Model): name = models.CharField(max_length=20, verbose_name='region') prefecture = models.ForeignKey(Prefecture) class Price(models.Model): name = models.CharField(max_length=20, verbose_name='price') PRICE_RANGE = ( ('a', 'under500'), ('b', '500-1000'), ('c', 'upper1000'), ) price_range = models.CharField(max_length=1, choices=PRICE_RANGE) city = models.ForeignKey(City) When I run migration command,NameError: name 'Area' is not defined area = models.ForeignKey(Area) error happens.However,I defined Area,so I really cannot understand why this error happens.How should I fix this? -
Django REST framework JWT 403 forbidden
I've gone through the installation steps in the django-rest-framework-jwt docs and I am unable to run the curl $ curl -X POST -d "username=admin&password=abc123" http://localhost:8000/api-token-auth/. I CANNOT get back the token! Instead I got back CSRF cookie error: <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> </head> <body> <div id="summary"> <h1>Forbidden <span>(403)</span></h1> <p>CSRF verification failed. Request aborted.</p> <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for &#39;same-origin&#39; requests.</p> </div> <div id="info"> <h2>Help</h2> <p>Reason given for failure:</p> <pre>CSRF cookie not set.</pre> <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when <a href="https://docs.djangoproject.com/en/1.8/ref/csrf/">Django's CSRF mechanism</a> has not been used correctly. For POST forms, you need to ensure:</p> <ul> <li>Your browser is accepting cookies.</li> <li>The view function passes a <code>request</code> to the template's <a href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a> method.</li> <li>In the template, there is a <code>{% csrf_token %}</code> template tag inside each POST form that targets an internal URL.</li> … -
Wagtail CMS: Is it possible to add a `PageChooserPanel` to the `content_object` field in `EditView` for `ModelAdmin`?
Wagtail CMS: Is it possible to add a PageChooserPanel to the content_object field in EditView for ModelAdmin? The model is a Comment from django-contrib-comments (Django "excontrib" Comments). -
Using class mixin causes Pycharm to say "unexpected argument" for null=True
Pycharm shows "unexpected argument" when I use CIEmailField(null=True), but not when I use CIEmailFieldOld(null=True). null is still a valid argument as far as I can tell, so why is Pycharm giving me this warning? from django.db.models import * class CIText: def db_type(self, connection): return 'citext' class CIEmailField(CIText, EmailField): pass class CIEmailFieldOld(EmailField): def db_type(self, connection): return 'citext' -
Display column when value not equal to null
I've tried to google how to solve this problem. But most of it was not related to this. This program is to get input from user, which is in checkbox format, it will read all the content in text file and display it in table format on website. QUESTION Any possible command that the column only will be display if the column has value?? Note : If you guys understand and saw this problem before please post the link here. views.py tokens = request.GET.getlist('token') # ... with open(path) as input_data: for line in input_data: if 'visual' in tokens and line.startswith('2_visualid_'): prev_key = line.lstrip('2_visualid_').rstrip() data.update({prevkey: []}) if 'time' in tokens: if search_string in line and prev_key in data: data[prev_key].append(next(input_data).lstrip('2_mrslt_').rstrip()) html table <div class="input-group" align="center" style=" left:10px; top:-110px; width:99%"> <table class="table table-bordered"> <thead class="success" > <tr> <th class="success"> <b>Visual ID</b> </th> <th class="success"> <b>Time Delay Index Time</b> </th> </tr> {% for key, values in output.items %} <tr class="warning"> <td rowspan={{ values|length|add:1 }}><b>{{ key }}</b></td> {% for value in values %} <tr class="warning"> <td ><b>{{value}}{{key1}}</b></td> </tr> {% endfor %} </tr> {% endfor %} </thead> </table> </div> -
AttributeError: module 'django.db.models' has no attribute 'ForignKey'
I made area data model in models.py. class User(models.Model): name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) area = models.ForignKey(Area) class Area(models.Model): name = models.CharField(max_length=20, verbose_name='area') class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='city') area = models.ForignKey(Area) class City(models.Model): name = models.CharField(max_length=20, verbose_name='region') prefecture = models.ForignKey(Prefecture) class Price(models.Model): name = models.CharField(max_length=20, verbose_name='price') PRICE_RANGE = ( ('a', 'under500'), ('b', '500-1000'), ('c', 'upper1000'), ) price_range = models.CharField(max_length=1, choices=PRICE_RANGE) city = models.ForignKey(City) I wanna use Area&Prefecture&City&Price models in User area = models.ForignKey(Area).However,when I run migrate command this code,AttributeError: module 'django.db.models' has no attribute 'ForignKey' error happens.Why does this error happen?Am I wrong to use ForignKey?How should I write it? -
How to count object and include the result in template
I need to push number of items to template for have adaptive website in fonction of number of items. in the models.py i add get_context models.py class LivreDesc(Page): note = models.CharField(max_length=25,null=True,blank=True,) resume = RichTextField(blank=True, verbose_name="Résumé") couverture = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Couverture du livre") parent_page_type = ['HomePage'] subpage_types = [] content_panels = Page.content_panels + [ FieldPanel('note'), FieldPanel('resume', classname="full"), ImageChooserPanel('couverture'), ] def get_context(self, request): context = super(LivreDesc, self).get_context(request) context['nb_livres'] = LivreDesc.objects.all().count() return context in template of HomePage i add this but I don't see anything {{ nb_livres }} -
Object 'user' has no atribute 'create' - Django
I have a question about an error that I am getting. I have a query that I am trying to send based on the Synapse Api for my project. I am currently trying to senda request taht creates a new user with the API. Every time I try to to send the request, I get a message that the User object doesnt have a create. Here is the error. AttributeError at /setup_profile/ type object 'User' has no attribute 'create' Request Method: POST Request URL: http://127.0.0.1:8000/setup_profile/ Django Version: 1.8.6 Exception Type: AttributeError Exception Value: type object 'User' has no attribute 'create' Exception Location: C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in createUserSynapse, line 1104 Here is the current code that I have which will create the request to create a new user. def createUserSynapse(request): args = { 'email': 'hello@synapsepay.com', 'phone_number': '555-555-5555', 'legal_name': 'Hello McHello', 'note': ':)', # optional 'supp_id': '123abc', # optional 'is_business': True, 'cip_tag': 1 } user = User.create(client, **args) print(user) Now i do know that with a normal query set, I have the object in the following format User.objects.create(client, **args) but when i do that I get an error that says two parameters are being passed and 1 is requires so I think there is … -
How to view a URL from a GET method in Django after sending and receiving data?
How does one view a URL from a GET method, especially after receiving data and using it to query from a database in order to view the result? Here are my views: def index(request): db.execute("SELECT major_division from sic") div = db.fetchall() item = request.GET.get('q') item_list = [] if item != None: item = "'%"+item+"%'" db.execute("SELECT * from sic where major_division LIKE "+item+" or major_division_title LIKE "+item+" or divisions LIKE "+item+" or divisions_title LIKE "+item+" or major_groups LIKE "+item+" or major_groups_title LIKE "+item+" or groups LIKE "+item+" or group_title LIKE "+item+" or versions LIKE "+item) item = db.fetchall() temp_list = [] for temp in item: for x in temp: temp_list.append(x) item_list.append(temp_list) temp_list=[] context = {"item_list":item_list} return render(request, "search2.html",context) And here is my urls.py: urlpatterns = [ # url(r'^sic/\?query=(.*?(?:&|$))', index), # url(r'^sic/(?P<q>\w+)/', index), url(r'^sic/$', index, name='urlname'), # url(r'^', include('sic_app.urls')), # url(r'^admin/', admin.site.urls), ] -
Access a function variable outside a function with required function parameters
I am having a hard time, accessing a variable outside a function. I am defining the variable inside the function and assigning a value to it, but I cannot access it outside. The variable I want to access outside is chatid and I want to save it to my database. Here is my code def send_messages(message, token): post_message_url = "https://api.telegram.org/bot{0}/sendMessage".format(token) result_message = {} result_message['chat_id'] = message['chat_id'] chatid = message['chat_id'] result_message['text'] = "Hey there" response_msg = json.dumps(result_message) status = requests.post(post_message_url, headers={ "Content-Type": "application/json"}, data=response_msg) When I try to save it like this I get a name error because I don't call the function u = User(userid=chatid) u.save() When I add return chatid to the end of the function and then try to save it like this u = User(userid=send_messages()) I get that I am missing two required positional arguments which are message and token, that I need in my function Eventually when I add them like this u = User(userid=send_messages(message, token)) again I get a name error because I did not define message and token. What's my way out of this to save chatid to my database? -
.filter() on Django Unioned QuerySets gives incorrect results
I have a model called Event that has both a start and stop field, both of type DateTimeField. I want to filter out the Events that have null start and stop fields. Using these two queries, I get 2 QuerySets: tempset = Event.objects.filter(site__slug='test-site', owner__email='bill@email.com') tempset2 = Event.objects.filter(site__slug='test-site', invite__slug='bill-compton') I've tried to do a union like this: tempset.union(tempset2) as well as like this: tempset = Event.objects.filter(site__slug='test-site', owner__email='bill@email.com').union(Event.objects.filter(site__slug='test-site', invite__slug='bill-compton')) but when I try to filter, using this syntax: filtered_query = tempset.filter(start__isnull=False, stop__isnull=False) and then print out the start and stop values, for thing in filtered_query: print(thing.start, thing.stop) I get this output: None None 2017-09-01 11:00:25+00:00 None 2017-09-03 11:00:00+00:00 2017-09-03 12:00:00+00:00 2017-09-06 11:00:00+00:00 2017-09-06 12:00:00+00:00 2017-09-06 11:00:54+00:00 2017-09-06 12:00:54+00:00 2017-09-06 11:00:07+00:00 2017-09-06 12:00:07+00:00 Note: If I use the | character to merge the two queryset, this filtered query works fine. I was under the understanding that .union() would allow this merging behavior however. Any thoughts? -
Django downloading a file that had been uploaded before
I'm using Django 1.10 and I have a button on my home page that you can click to download a file (PDF or MP4). I have a ajax call going to my views.py `def downloadfile(request): if request.POST: fileviewing = get_object_or_404(FileViewing, pk=request.POST.get("id")) file_name = fileviewing.file.file.name file_path = fileviewing.file.file.path file_wrapper = FileWrapper(file(file_path,'rb')) file_mimetype = mimetypes.guess_type(file_path) response = HttpResponse(file_wrapper, content_type=file_mimetype) response['X-Sendfile'] = file_path response['Content-Length'] = os.stat(file_path).st_size response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) return response` This is my function to download a file but nothing happens when it goes through the fuction. There are no errors and the function runs completely but nothing is being downloaded. -
django rest authentication return "don't include authentication information"
I am making django authentication function via rest framework. I made view.py, serizlizers.py and backends.py. And I setup settings.py to call my own authentication function. But something is wrong and I got the error message that means "detail" : "don't include authentication information". I have no idea what is wrong of my function. Please give me an advice. backends.py class RemoshinUserAuthBackend(BaseAuthentication): def authenticate(self, username=None, password=None): try: user = RemoshinUser.objects.get(username=username) if not user.check_password(password): return None except RemoshinUser.DoesNotExist: return None return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None views.py @method_decorator(csrf_exempt, name='dispatch') class UserAuthenticationView(APIView): authentication_classes = (RemoshinUserAuthBackend, BasicAuthentication) permission_classes = (IsAuthenticated,) serializer_class = RemoshinUserAuthInputSerializer def get(self, request, format=None): content = { 'user': request.user.username, 'auth': None, } return Response(content) def post(self, request): serializer = RemoshinUserAuthInputSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = authenticate(**serializer.data) if not user: raise AuthenticationFailed() return Response(serializer.data) serializers.py class RemoshinUserAuthInputSerializer(serializers.ModelSerializer): class Meta: model = RemoshinUser fields = ('username', 'password') -
If else not working (comparison operator in Django)
I am using Django 1.11 and I am trying to use the Django templating to do an if .. else .. statement in a html file. Regular if .. else .. statements work in the Django templating, the only issue I am running into is using the comparison operators (<=, <, >, >=). I have re-read the docs for Django 1.11 and it definitely seems like it is supported in this version. Code (view / database): a = 25.2 # passed from view to database HTML template {% if data.a < 30 %} <p>correct</p> {% else %} <p>incorrect</p> {% endif %} By itself data.a works fine, if I just use {{ data.a }} then it will correctly display 25.2, however if I run the above code, then the else statement is always displayed. Any suggestions? -
Override Settings for django test does not seem to work
I have to override settings in a test in Django @override_settings(XYZ_REDIRECT="http://localhost:8000") @override_settings(TOKEN_TIMEOUT=0) class CustomTestCase(TestCase): def setUp(self): self.token = self._generate_auth_token() self.client = Client() def test_token_expiry(self): feoken_count = 0 client = Client() client.post('/api/v1/auth/login/', {'token': 'AF'}) # Over HERE TOKEN_TIMEOUT is not changed self.assertEqual(ABCN.objects.count(), feoken_count) The override settings decorator, however seems not to work. In the other side of the route, I have this code. from fetchcore_server.settings import AUTH0_SERVER_URL, TOKEN_TIMEOUT .... def post(self, request, *args, **kwargs): if 'token' in request.data: FetchcoreToken.objects.filter(expiry_time__lte=timezone.now()).delete() print TOKEN_TIMEOUT # this is still original value token = request.data['token'] try: fetchcore_token = FetchcoreToken.objects.get(token=token) user = fetchcore_token.user user_id = user.id I tried using the with self.settings(TOKEN_TIMEOUT=0) but even that did not work. I am not sure how I'm using this wrong Django docs on the subject: https://docs.djangoproject.com/en/1.11/topics/testing/tools/ In case it is relevant, this is how I run the test python manage.py test api.tests.integration.v1.users.AuthUserTestCase -
removing python django folder
my situation is simple, i have created a django project by using django-admin startproject first_site in cmd, the folder is inside the python folder something went wrong and i cant runserver with that folder. and i want to delete it and start over. but it just does not let me delete the folder. i am trying to remove the whole python django project from my folder, but it asking for administration, then when i allowed it with administration it now require a permission from Desktop-QVCR3VD to make changes to this folder. i have look online on how to remove the python django project folder, not just the app not just the model, but the entire project folder. how do i accomplish this? its driving me insane -
How to get current template engine in custom template filter in Django?
How to get current or default template engine here? @register.filter def myfilter(instance): pass -
Uploading file using AJAX request
I'm trying to upload a file using AJAX. I tried to do it using formData() object as well. How can I add a file to following Ajax request? $.ajax({ url: '/api/add_new_pair/', method: "POST", type: 'POST', FILES: { 'image' : file, }, data: { 'csrfmiddlewaretoken': csrftoken, 'text': text, }, }).done(function(response){ console.log(response); } -
Key Error = client_id -- django
I have an api that i am using for a project that I am working on. I am getting a key errror for the client Id that I have to pass in order ot call the api. THe api that i am using is Synapse. If anyone knows what is cuasing the error or how I can fix this key error, it would be a lit of help... Here is the full error. KeyError at / 'client_id_SOJMCFkagKAtvTpem0ZWPRbwznQ2yc5h0dN6YiBl' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.8.6 Exception Type: KeyError Exception Value: 'client_id_SOJMCFkagKAtvTpem0ZWPRbwznQ2yc5h0dN6YiBl' Exception Location: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\lib\os.py in __getitem__, line 669 Python Executable: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\OmarJandali\\Desktop\\opentab\\opentab', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages'] here is the code: import os from synapse_pay_rest import Client args = { 'client_id': os.environ['client_id_SOJMCFkagKAtvTpem0ZWPRbwznQ2yc5h0dN6YiBl'], 'client_secret': os.environ['client_secret_muUbizcGBq2oXKQTMEphg0S4tOyH5xLYNsPkC3IF'], 'fingerprint': '599378e9a63ec2002d7dd48b', 'ip_address': '127.0.0.1', 'development_mode':True, 'logging':False } client = Client(**args) -
Django Tables2 Filter
I am trying to display a table with filter using Django tableas 2 and crispy forms. I have the following files: filter.py import django_filters from .models import Poste class PosteFilter(django_filters.FilterSet): id = django_filters.CharFilter(lookup_expr='icontains') status = django_filters.CharFilter(lookup_expr='icontains') address = django_filters.CharFilter(name='address', lookup_expr='icontains') atualizado_em = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Poste fields = {'id', 'status', 'address', 'atualizado_em',} forms.py from django import forms from .models import Poste from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, ButtonHolder, Submit class PosteListFormHelper(FormHelper): model = Poste form_tag = False form_style = 'inline' layout = Layout( 'id', 'status', 'address', 'atualizado_em', Submit('submit', 'Filtrar'), ) table.py import django_tables2 as tables from .models import Poste class PosteTable(tables.Table): class Meta: model = Poste # add class="paleblue" to <table> tag attrs = {'class': 'paleblue'} fields = ('id', 'status', 'address', 'atualizado_em') per_page: 25 As a result, I get this: What I want is: exclude the word "contains" in the lablel have the filter for inline I tried many ways to do that without success. Any help will be welcome. -
Can't iterate through Users list with django tags
I'm creating a friends list feature for a website, right now I'm just testing it. So I'm trying to display all Users with a little button beside their name that would send a friend request to them. But when I do it nothing appears on the page HTML: <h1>My profile</h1> {% for each_user in all_users %} <a href="{% url 'change_friends' operation='add' pk=each_user.pk %}"> Click </a> <h3>{{ each_user.first_name }}<h3> {% endfor %} views.py def profile_test(request): #going to use this view to display the profile page, and test alterations to it form = ImageUploadForm(request.POST, request.FILES) user = User.objects.get(id=request.user.id) all_users = User.objects.all() if request.method == "POST": user.userprofile.img = request.FILES.get('uploaded_image') user.userprofile.save() return HttpResponseRedirect(reverse("profile_test")) else: print 'invalid' form = ImageUploadForm() return render(request, 'profile_test.html', {form:'form', user: 'user', all_users:'all_users'}) def change_friends(request, operation, pk): #this view will manage a user's friends other_user = User.objects.get(pk=pk) #a list of primary keys if operation == 'add': Friend.objects.add_friend( request.user, other_user, message='Hi, I would like to add you') elif operation == 'remove': Friend.objects.remove_friend(request.user, other_user) return redirect('profile_test') -
Anyconfig in Django, connection to MySQL
I just created a Django app with mysql as a database. My codes are not clean but it is working right now. Just trying to learn more and fix some redundant codes. Per my code review, I was told that I should not declare my connection in my functions but placed them into an anyconfig. I have been reading some docs but I am not understanding it. Can someone please help me out? My code goes like this: Models.py class SomeobjectManager(models.Manager): def get_user_information(self, query): configs = {'host': '127.0.0.1','port': 8000,'user': 'myuser','password': 'somepassword','database': 'somedatabase'} cnx = mysql.connector.Connect(**configs) cursor = cnx.cursor() err = [] try: cursor.execute(mycont['query']) result = cursor.fetchall() # should return an array cnx.close() except: print "FAILED validation" err.append("Cannot populate anything from your Query. Please try again.") return err else: print "PASSED Validation" return result in my views.py, if I call this function, I either get an array of error (so I can display an error message) or the array of data from my database. So I guess my question is, what is the best practice to (1) establish a connection, (2) execute a query and (3) close the connection to mysql without having to write all the configs in every functions? …