Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Override django model save function that extends AbstractBaseUser
Im using restframework for user signup i need generate random password before save, i override save method in model but this never run and throw message password field is required. ¿How i can override this? Thanks. # ViewSet. class AgentViewSet(viewsets.ModelViewSet): queryset = Agents.objects.all() serializer_class = AgentSerializer permission_classes = (permissions.AllowAny,) http_method_names = ['post'] # Model. class Agents(AbstractBaseUser): oldkey = models.CharField(max_length=32, blank=True, null=True) is_main_user = models.IntegerField(blank=True, null=True) name = models.CharField(max_length=45, blank=True, null=True) lastname = models.CharField(max_length=45, blank=True, null=True) email1 = models.CharField( max_length=100, blank=True, null=True, unique=True ) email2 = models.CharField(max_length=100, blank=True, null=True) city = models.CharField(max_length=200, blank=True, null=True) country = models.ForeignKey( 'bdetail.Countries', models.DO_NOTHING, db_column='country', blank=True, null=True ) username = models.CharField(max_length=30, blank=True, null=True) image = models.CharField(max_length=80, blank=True, null=True) num_access = models.IntegerField(blank=True, null=True) phone1 = models.CharField(max_length=20, blank=True, null=True) phone2 = models.CharField(max_length=20, blank=True, null=True) phone3 = models.CharField(max_length=20, blank=True, null=True) whatsapp = models.CharField(max_length=20, blank=True, null=True) permissions = models.CharField( max_length=10, blank=True, null=True, default='limited') fb_profile_id = models.CharField(max_length=30, blank=True, null=True) fb_access_token = models.TextField(blank=True, null=True) clients = models.ForeignKey( 'Clients', models.DO_NOTHING, blank=True, null=True ) last_login_time = models.IntegerField(blank=True, null=True) about = models.TextField('Acerca de mi', blank=True) USERNAME_FIELD = 'email1' REQUIRED_FIELDS = ['name'] objects = MyUserManager() class Meta: db_table = 'agents' def get_full_name(self): return self.name, ' ', self.lastname def get_short_name(self): return self.name def has_perm(self, perm, obj=None): return … -
Arch Nginx Uwsgi no app loaded
I am trying to get django working but uwsgi is having problems loading anything. Most likely do to my ignorance. I would love some help troulble shooting. I have been looking at similar posts on the stack exchange but none of them have helped, they are all pretty specific. In /etc/uwsgi/ I have a .ini file for config and a .py file that I want uwsgi to host on port 2929. At /etc/uwsgi/test.ini: [uwsgi] socket=127.0.0.1:2929 plugin=python wsgi-file=/etc/uwsgi/test.py master=True At /etc/uwsgi/test.py: def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [b"Hello World"] At /etc/nginx/sites/test.conf, which is enabled and loaded into nginx: upstream test_uwsgi{ server 127.0.0.1:2929; } server{ listen 80; server_name test.example.com; location / { include uwsgi_params; uwsgi_pass test_uwsgi; } } Note: I am using Arch Linux. I restart nginx, then start test.ini using uwsgi: systemctl restart nginx systemctl start uwsgi@test Both succeed to run/activate without error. When I check the log/journal for the service uwsgi@test.service: Sep 30 11:29:23 Nexus systemd[1]: Starting uWSGI service unit... Sep 30 11:29:23 Nexus uwsgi[576]: [uWSGI] getting INI configuration from /etc/uwsgi/test.ini Sep 30 11:29:23 Nexus uwsgi[576]: *** Starting uWSGI 2.0.13.1 (64bit) on [Fri Sep 30 11:29:23 2016] *** Sep 30 11:29:23 Nexus uwsgi[576]: compiled with version: 6.1.1 20160501 on … -
Django: Submit Multiple of Same Forms with One Button
I want to improve my page by having one Submit button at the bottom of multiple forms to submit the data to SQL. At the moment, each form has its own submit button and when click on one, it submits all of them at once. I went through different posts and none talked about multiple forms that were all the same. I have one form that consists of Value and Name. I populate a table with this form depending on how many different Name fields there are. In the View, I populate the form as a list containing different instances for each Name. Then in the Template I loop through each item in the form and display it on a row. VIEW for enumeration in enumerationidlist: enumerationdata=Enumeration.objects.get(enumerationid=enumeration) if request.method == 'POST': form = form + [[EditEnumerationForm(request.POST, instance=enumerationdata, read=read, prefix=i),enumerationdata.enumerationid]] if form[i][0].is_valid(): form[i][0].save(commit=True) else: print(form[i][0].errors) else: form = form + [[EditEnumerationForm(instance=enumerationdata, read=read, prefix=i), enumerationdata.enumerationid]] initialList.append(enumerationdata) i = i + 1 Template <tbody> {% csrf_token %} {% for form in forms %} <tr> <td> {% crispy form.0 %} </td> </tr> {% endfor %} </tbody> How can I have just one Submit button displayed to the user that can submit (all at once) … -
Django view going into infinite loop without a response
I have a Django view. When I execute that view, It is never stopping. I would like to stop this script, when a json file is created in the last. What is causing the problem? How can I make it a finite loop? def GetSerialNum(request): if request.method == 'GET': import socket import time import string import re import urllib2 from xml.etree import ElementTree as ET from xml.dom.minidom import parse import os import csv import json msg = \ 'M-SEARCH * HTTP/1.1\r\n' \ 'HOST:239.255.255.250:1900\r\n' \ 'MX:2\r\n' \ 'MAN:ssdp:discover\r\n' \ 'ST:urn:schemas-upnp-org:device:ManageableDevice:2\r\n' # Set up UDP socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) s.settimeout(1000) s.sendto(msg, ('239.255.255.250', 1900) ) try: os.remove('serialnumbers.txt') except OSError: pass def logToFile(logTxt): logFile = open("serialnumbers.txt", "a+") logFile.write(logTxt+"\n") # print logTxt def getCurrentTimeStamp(): return strftime("%Y-%m-%d %H:%M:%S") try: while True: data, addr = s.recvfrom(65507) mylist=data.split('\r') url = re.findall('http?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', data) print url[0] response = urllib2.urlopen(url[0]) the_page = response.read() # print the_page tree = ET.XML(the_page) with open("temp.xml", "w") as f: f.write(ET.tostring(tree)) document = parse('temp.xml') actors = document.getElementsByTagName("ns0:serialNumber") for act in actors: for node in act.childNodes: if node.nodeType == node.TEXT_NODE: r = "{}".format(node.data) print r logToFile(str(r)) f = open("compare.txt", "r") reader = csv.reader(f) data = open("temp1.csv", "wb") w = csv.writer(data) for row in reader: my_row = … -
Django ManyToMany Teams
I am working on my first application in Django and I don't really know for sure what's the best way to implement the following: Users can be a member of different teams as stated in the following code: class Team(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_lenght=200) administrator = models.OneToOneField(User) members = models.ManyToManyField(User) The user has to be able to switch between teams in the app. This means that one time, the user sees the workspace for team A, and another time, the user sees the workspace for team B. The user is a member of both teams. The URL for both workspaces had to be the same. What's the best way to go about this? -
Post data by URL in many to many field django rest framework
I'm trying to POST with django REST framework, the field is ManyToMany, I kind of have the idea of how to do it but not how to send the data. The model: class ModelC(models.Model): km=models.FloatField() aM=models.OneToOneField(Challenge,on_delete=models.CASCADE, primary_key=True) user=models.ManyToManyField(User,related_name='users') def __str__(self): return '%s, %f'%(self.aM, self.km) This is my serializer: class ModelCSerializerCreate(serializers.ModelSerializer): aM=serializers.StringRelatedField() user=UserSerializer(read_only=True, many=True) user_id=serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), write_only=True, many=True) class Meta: model=ModelC fields=('aM','user','user_id','km', 'date') def create(self,validated_data): users=validated_data.pop('user_id') modelC=ModelC.objects.create(**validated_data) for user in users: modelC.user.add(user) return modelC views.py def post(self,request,format=None): serializer=ModelCSerializerCreate(data=request.data) if serializer.is_valid(): aM=self.get_AM(pk=int(self.request.data['am'])) serializer.save(am=aM) return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) But when I try to POST this: http://127.0.0.1:8000/modelC/ km=5 aM=3 user_id=1 I get this error: {'user_id': ['Expected a list of items but got type "str".']} How do I need to send the data? or is something bad with my code? Thank you -
How to make Q lookups in django look for multiple values
Currently I have a very simple search option which goes through my pages and looks up through several fields for requested query. If I input a single word in it it works just fine, however if I input multiple words in search query, I get nothing, even if a single page contains all attributes. For example if I search for test admin, I will not get empty query, even though there's a page with title test, with content test and author admin. Is there a way to expand the search to look up each word in search query individually? # Fetch all pages and sort them alphabetically queryset = Page.objects.all().filter(archived=False).order_by("title") # Get search query if applicable query = request.GET.get("q") if query: queryset = queryset.filter( Q(title__icontains=query) | Q(content__icontains=query) | Q(user__username__icontains=query) | Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) ).distinct() -
Use Django ORM Postgresql regex when the regex is in the database and the value is a string
I understand how to do Postgresql regular expression searches through the Django ORM when I am passing the regular expression. What is the equivalent when the regular expression is in the database table, and I am passing the string? For example, in Django you can do the Postgresql query: INSERT INTO StringValues (val) VALUES ('abc'); SELECT * FROM StringValues WHERE val ~* '^[a-z]{3}$'; With: StringValues.objects.get(val__regex=r'^[a-z]{3}$') How would can you do the following query in Django? INSERT INTO StringValues (val) VALUES ('^[a-z]{3}$'); SELECT * FROM StringValues WHERE 'abc' ~* val; I.E. the regular expression is in the table and I want the row that matches my string. -
Django ManyToMany field related to itself
I have a Django model Groups that I'm trying to relate back to itself, in a ManyToMany field called related_groups. The model changes and the makemigrations script created a new table called group_related_groups (Group was a previously implemented model, with new fields added for relationships). The new model looks like this: class Group(models.Model): """ Model definition of a Group. Groups are a collection of users (i.e. Contacts) that share access to a collection of objects (e.g. Shipments). """ group_id = models.AutoField(primary_key=True) group_name = models.CharField(max_length=100) owner_id = models.ForeignKey('Owner', related_name='groups') category = models.CharField(max_length=30) related_groups = models.ManyToManyField('self', blank='true') What I'm wanting to achieve is the related groups column holds the PKs of associated groups. For example, multiple groups of Students could belong to a single group of Counselors, where the Group model is the establishing factor for all Users. Like: | id | group_name | owner_id | category | ------------------------------------------ | 1 | students1 | 10 | student | | 2 | counselors | 10 | counselor | | 3 | students2 | 10 | student | .... | 7 | students3 | 10 | student | and on the group_related_groups table: | id | from_group_id | to_group_id | ------------------------------------ | 1 | … -
My Django application is not displaying content from the db
{% extends 'photos/base.html' %} {% block galleries_active %}active{% endblock %} {% block body%} <div class="gallery-container" container-fluid> <!--- Galleries---> <div class="row"> <div class="col-sm-12"> <h3>Text's Gallery</h3> </div> {% if gallery %} {% for gallery in galleries %} <div class="col-sm-4 col-lg-2"> <div class="thumbnail"> <a href="{% url 'photos:details' gallery.id %}"> <img src="{{gallery.Gallery_logo}}" class="img-responsive" height="240" width="240"> </a> <div class="caption"> <h2>{{gallery.Title}}</h2> <h4>{{gallery.Category}}</h4> <!-- View Details--> <a href="{% url 'photos:detail' gallery.id %}" class="btn btn-primary btn-sm" role="button">View Details</a> <!-- Delete Album--> <form action="{% url 'photos:delete_gallery' gallery.id %}" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="gallery_id" value="{{gallery.id}}"> <button type="submit" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-trash"></span> </button> </form> <!-- Favorite --> <a href="#" class="btn btn-default btn-sm btn-favorite" role="button"> <span class="glyphicon glyphicon-star"></span> </a> </div> </div> </div> {% cycle '' '' '' '' '' '<div class="clearfix visible-lg"></div>' %} {% endfor %} {% else %} <div class="col-sm-12"> <br> <a href="#"> <button type="button" class="btn btn-success"> <span class="glyphicon glyphicon-plus"></span>&nbsp; Add a Gallery </button> </a> </div> {% endif %} </div> </div> </div> {% endblock %} That is my index file below is my views.py file from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from .models import Gallery class IndexView(generic.ListView): template_name = 'photos/index.html' context_object_name = 'all_galleries' def get_queryset(self): return Gallery.objects.all() … -
how can reactjs access session data(username) from django
i am using django with reactjs, and now i have maintained session and want to access session data by reactjs to cutomise UI. what all can i do for this? //my models.py snippet class Users(models.Model): gender = models.CharField(max_length=200) username = models.CharField(max_length=50) password = models.CharField(max_length=50) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() address = models.CharField(max_length=50) city = models.CharField(max_length=60) state = models.CharField(max_length=30) country = models.CharField(max_length=50) bg = models.CharField(max_length=200) badges = models.BigIntegerField(null=True) dob = models.DateField() contact = models.BigIntegerField(null=True) age = models.BigIntegerField(default=0) status = models.BigIntegerField(null=True) //my views.py snippet def login(request): print(request.POST.get('username')) username=str(request.POST.get('username')) password=str(request.POST.get('password')) if(Users.objects.filter(password=password, username=username).exists()): request.session['username'] = username name=request.session['username'] return render(request, 'loggedin.html', {"username" : name}) else: return HttpResponse("incorrect data") -
Django Bootstrap Data Toggle Radio Buttons Not working
I have a form - part of which is creating radio buttons to select from a group of choices called "tool_loc". The Javascript and bootstrap CSS are being loaded properly (per Chrome anyway). Here is the snippet for the template: {{form.tool_loc.errors}} <label for="{{form.tool_loc.id_for_label}}">Tool Location:</label> <div class="btn-group" data-toggle="buttons"> {% for field in form.tool_loc %} <label class="btn btn-primary"> {{field.choice_label}} {{field.tag}} </label> {% endfor %} </div> The end HTML result is here: https://jsfiddle.net/6o84xLx2/2/ Issue Once a button is clicked it doesn't stay highlighted (as it does here: http://v4-alpha.getbootstrap.com/components/buttons/#checkbox-and-radio-buttons) Not sure what I'm doing wrong! -
Bjoern wsgi mime type of served statics are wrong
Trying to use Bjoern in here with Django framework, and there's a problem I see in Firefox console: The stylesheet http://localhost/en/assets/css/user-area.css was not loaded because its MIME type, "text/html", is not "text/css". en The stylesheet http://localhost/en/assets/css/mikesCustom.css was not loaded because its MIME type, "text/html", is not "text/css". en The stylesheet http://localhost/en/node_modules/primeui/primeui-ng-all.min.css was not loaded because its MIME type, "text/html", is not "text/css". en The stylesheet http://localhost/en/node_modules/primeui/themes/omega/theme.css was not loaded because its MIME type, "text/html", is not "text/css". en The stylesheet http://localhost/en/assets/css/global.css was not loaded because its MIME type, "text/html", is not "text/css". en The stylesheet http://localhost/en/assets/css/bootstrap-datetimepicker.min.css was not loaded because its MIME type, "text/html", is not "text/css". en The stylesheet http://localhost/en/assets/css/tabs.css was not loaded because its MIME type, "text/html", is not "text/css". File itself indeed contains HTML source of index.html. Nginx doesn't complain that file is not found. Here's wsgi.py: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "spiral.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() import bjoern bjoern.run(application, "0.0.0.0", 8000) Decided to use bjoern because it's written in C, and benchmarks are insane in compare with other wsgi tools. Also I'm pretty much sure that nginx has nothing to do with it, because going to localhost:8000 i've got exactly the same problem. -
Django rest framework serialize a dictionary
Hi everyone I am using Django rest framework, and I want to serialize a dictionary object that I obtain when I consult a database def retrieve(self, request, project_name=None): try: opc = {'name_proj' : project_name } alldata = connect_database(opc) except KeyError: return Response(status=status.HTTP_404_NOT_FOUND) except ValueError: return Response(status=status.HTTP_400_BAD_REQUEST) serializer = serializers.cpuProjectsSerializer(instance=alldata, many=True) return Response(serializer.data) when I call to connect_database(opc) function, I consult the database and return all the rows. after that a create, a dictionary obj that I return in alldata, so I call to my serializers method with a dictionary. my dictionary object is like that {names:[], {jobs_running:[[], [],[] ]}, {jobs_pending:[[],[],[]] }} My problem is that I don't know how to create a serializer file. I try this, return a name like string, jobs_running and jobs_pendding like a dictionary class cpuProjectsSerializer(serializers.Serializer): project = serializers.CharField(max_length=256) jobs_running = serializers.DictField() jobs_pending = serializers.DictField() def create(self, validated_data): """ Create and return a new `cpuProjects` instance, given the validated data. """ return cpuProjects.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `cpuProjects` instance, given the validated data. """ instance.project = validated_data.get('names', instance.project) instance.save() return instance but I receive this error The serializer field might be named incorrectly and not match any attribute or key … -
Django image caching with S3
So my app stored users profile photos on S3 and I'm running into an interesting problem. On one particular page we load and display the profile picture ~20 times, and on that page we are using a custom template tag which asks for the users profile_photo.url. My app is configured to use django_storages, and when calling .url my app creates a temp url for the image. When inspecting the page I notice that sometimes the page will make tons of different requests for the same image. The difference between the requests being the key and expiry. Somewhere my app is deciding to not reuse the same temporary URL and I'm not sure what is causing that. So I've got 2 questions: How do I fix the temporary url problem? I think it's related to the use of a templatetag that is used ~10 times on the page users|user_info_as_json How would I implement caching into my app so that images are not always directly served from S3 temp urls. -
Common loggers for all views in django
Here is my loggers configuration of settings.py on my Django sever. 'loggers': { 'tutorial.view_test': { 'handlers': ['logfile','console','mail_admins'], 'level': 'DEBUG', 'propagate': True, }, } I am able to log the details using the above loggers configurations for view "tutorial.view_test". But if i want to log for all my view in my project with a common loggers. How can i do that. -
Django logging issue
I have below logging dict in settings.py. project name is "refer" LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s - [ %(levelname)s ] - %(module)s %(name)s : %(message)s' }, }, 'handlers': { 'default': { 'level': 'DEBUG', #'filters': ['require_debug_true'], 'class': 'logging.handlers.RotatingFileHandler', 'filename' : 'logs/refer.log', 'maxBytes' :1024*1024*10, 'backupCount' : 5, 'formatter': 'standard' }, 'basic': { 'level': 'INFO', #'filters': ['require_debug_true'], 'class': 'logging.handlers.RotatingFileHandler', 'filename' : 'logs/inforefer.log', 'maxBytes' :1024*1024*10, 'backupCount' : 5, 'formatter': 'standard' } }, 'loggers': { 'debug': { 'handlers': ['default'], 'level': 'DEBUG', 'propogate': True #'filters': ['special'] }, 'refer': { 'handlers': ['basic'], 'level': 'INFO', 'propogate': True #'filters': ['special'] }, } } and below is the way i am trying to get logs but nothing is getting printed only file was created import logging logme = logging.getLogger(__name__) logme.info("test") logme.debug("test") -
When saving ManyToMany Field value in django ,error occures invalid literal for int() with base 10
I am trying to save ManyToMany filed value in django model objects.But when i ma saving an error comes invalid literal for int() with base 10. My code is def saveDetail(request): userExp = str(request.GET.get('user')) tags = request.POST.getlist('tags') comment = request.POST.get('comment') exp = customer.objects.get(user = userExp) exp.tags = tags exp.save() and the error is ValueError: invalid literal for int() with base 10: 'tag2 -
csrf exempt on dispatch method not working
I had added csrf exempt on dispatch method on CBV but still I get 403 forbidden error, Forbidden (403) CSRF verification failed. Request aborted. class Upload(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(Upload, self).dispatch(request, *args, **kwargs) def get(self, request): user_id = utils.check_session_variable(request) if user_id is None: return utils.page_redirects_login(request) else: return utils.page_redirects(request,request.session['userid'], active_tab='ams') def post(self, request): print 'post request' user_id = utils.check_session_variable(request) -
Django Sites framework - can I do these things?
I have a general idea of what the Sites framework is, but after much researching, I can't confirm if what I'm trying to achieve is possible. Here's what I want to achieve (simplified). These would be three separate sites - and separate Django projects. Is this possible? Site/Project 1: Customers.ourdomain.com This site manages everything about our customers. There would be a model called Contact which stores all the information about customers (name, address, email, etc.) Have views that a for viewing the Contact model objects, editing their details, etc Site/Project 2: WorkOrders.ourdomain.com This site would manage all things pertaining to Work Orders there would be a WorkOrder model, to create/edit/manage work orders for doing installs and service, etc. In order to create work orders for our customers, the WorkOrder model would need to know about the Customer model from the other site. The work order site doesn't need to edit the customer's data - just needs to have read access of all the customers Site/Project 3: Accounting.ourdomain.com Accounting site for handling all things accounting, such as invoices, accounts receivable, revenue, etc. There would be a bunch of accounting related models, like Invoice, Payment, etc. The Accounting site would need to … -
Python argparse does not parse images with wildcard
I use this library https://github.com/cmusatyalab/openface for image comparison. I have downloaded Docker container with preinstalled environment. I start the container and I'm accessing this file: https://github.com/cmusatyalab/openface/blob/master/demos/compare.py with this command: ./demos/compare.py images/examples/{lennon*,clapton*} (check http://cmusatyalab.github.io/openface/demo-2-comparison/ if you want) It works fine when I execute the command directly from Docker terminal. Parsed arguments look like this: Namespace(dlibFacePredictor='/root/openface/demos/../models/dlib/shape_predictor_68_face_landmarks.dat', imgDim=96, imgs=['images/examples/lennon-1.jpg', 'images/examples/lennon-2.jpg', 'images/examples/clapton-1.jpg', 'images/examples/clapton-2.jpg'], networkModel='/root/openface/demos/../models/openface/nn4.small2.v1.t7', verbose=False) The problem is when I execute the same command from PHP file (I start simple PHP web server to access this script from host machine). PHP code: echo shell_exec('./demos/compare.py images/examples/{lennon*,clapton*}') Parsed arguments look now like this: Namespace(dlibFacePredictor='/root/openface/demos/../models/dlib/shape_predictor_68_face_landmarks.dat', imgDim=96, imgs=['images/examples/{lennon*,clapton*}'], networkModel='/root/openface/demos/../models/openface/nn4.small2.v1.t7', verbose=False) BOTTOMLINE: When script is executed directly, imgs argument is parsed correctly imgs=['images/examples/lennon-1.jpg', 'images/examples/lennon-2.jpg', 'images/examples/clapton-1.jpg', 'images/examples/clapton-2.jpg'] When script is executed from PHP script, imgs argument is not correctly parsed: imgs=['images/examples/{lennon*,clapton*}'] Code: import time start = time.time() import argparse import cv2 import itertools import os import numpy as np np.set_printoptions(precision=2) import openface fileDir = os.path.dirname(os.path.realpath(__file__)) modelDir = os.path.join(fileDir, '..', 'models') dlibModelDir = os.path.join(modelDir, 'dlib') openfaceModelDir = os.path.join(modelDir, 'openface') parser = argparse.ArgumentParser() parser.add_argument('imgs', type=str, nargs='+', help="Input images.") parser.add_argument('--dlibFacePredictor', type=str, help="Path to dlib's face predictor.", default=os.path.join(dlibModelDir, "shape_predictor_68_face_landmarks.dat")) parser.add_argument('--networkModel', type=str, help="Path to Torch network model.", default=os.path.join(openfaceModelDir, 'nn4.small2.v1.t7')) parser.add_argument('--imgDim', type=int, help="Default image dimension.", default=96) … -
Specifying Readonly access for Django.db connection object
I have a series of integration-level tests that are being run as a management command in my Django project. These tests are verifying the integrity of a large amount of weather data ingested from external sources into my database. Because I have such a large amount of data, I really have to test against my production database for the tests to be meaningful. What I'm trying to figure out is how I can define a read-only database connection that is specific to that command or connection object. I should also add that these tests can't go through the ORM, so I need to execute raw SQL. The structure of my test looks like this class Command(BaseCommand): help = 'Runs Integration Tests and Query Tests against Prod Database' def handle(self,*args, **options): suite = unittest.TestLoader().loadTestsFromTestCase(TestWeatherModel) ret = unittest.TextTestRunner().run(suite) if(len(ret.failures) != 0): sys.exit(1) else: sys.exit(0) class TestWeatherModel(unittest.TestCase): def testCollectWeatherDataHist(self): wm = WeatherManager() wm.CollectWeatherData() self.assertTrue(wm.weatherData is not None) And the WeatherManager.CollectWeatherData() method would look like this: def CollecWeatherData(self): cur = connection.cursor() cur.execute(<Raw SQL Query>) wm.WeatherData = cur.fetchall() cur.close() I want to somehow idiot-proof this, so that someone else (or me) can't come along later and accidentally write a test that would modify the production … -
Custom rendering of foreing field in form in django template
In my modelform i have a foreign key, i cannot figure out how to change the appearance of this field in template. I can change the text by changing __unicode__ of the model, but how make it bold for example? in models.py i try the following but form render in with and all other tags as if they just text: def __unicode__(self): u'<b>Name</b>: {}\n<b>Loyal</b>: {}'.format(self.name, self.loyal) my template.html: <form method="post"> {% csrf_token %} {{ form.client|safe}} <br> <input type="submit" value="Save changes" class="btn btn-s btn-success"> </form> doesnt work. Here the picture -
Reserve redirect does not work but inserts data into db
from django.db import models from django.core.urlresolvers import reverse class Gallery(models.Model): Title = models.CharField(max_length=250) Category = models.CharField(max_length=250) Gallery_logo = models.CharField(max_length=1000) def get_absolute_url(self): return reverse('photos:detail', kwargs={'pk', self.pk}) def __str__(self): return self.Title + '_' + self.Gallery_logo class Picture (models.Model): Gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE) Title = models.CharField(max_length=250) Artist = models.CharField(max_length=250) Price = models.CharField(max_length=20) interested = models.BooleanField(default=False) def __str__(self): return self.Title Am getting this error below TypeError at /photos/gallery/add/ _reverse_with_prefix() argument after ** must be a mapping, not set Request Method: POST Request URL: http://127.0.0.1:8000/photos/gallery/add/ Django Version: 1.10.1 Exception Type: TypeError Exception Value: _reverse_with_prefix() argument after ** must be a mapping, not set Exception Location: C:\Users\JK\AppData\Local\Programs\Python\Python35\lib\site-packages\django-1.10.1-py3.5.egg\django\urls\base.py in reverse, line 91 Python Executable: C:\Users\JK\AppData\Local\Programs\Python\Python35\python.exe Python Version: 3.5.2 Python Path: ['C:\Users\JK\PycharmProjects\catalog', 'C:\Users\JK\AppData\Local\Programs\Python\Python35\lib\site-packages\django-1.10.1-py3.5.egg', 'C:\Users\JK\PycharmProjects\catalog', 'C:\Users\JK\AppData\Local\Programs\Python\Python35\python35.zip', 'C:\Users\JK\AppData\Local\Programs\Python\Python35\DLLs', 'C:\Users\JK\AppData\Local\Programs\Python\Python35\lib', 'C:\Users\JK\AppData\Local\Programs\Python\Python35', 'C:\Users\JK\AppData\Local\Programs\Python\Python35\lib\site-packages'] Server time: Fri, 30 Sep 2016 17:15:55 +0300 Again am just a newbie -
Is there a common way of getting the uploaded file across multiple Python frameworks?
Is there a common way of getting the uploaded files in Python just like $_FILES is in PHP? In Django there is request.FILES['fieldid'], in Pyramid request.POST['fieldid'], while in Flask request.files['fieldid']. And all these return a different type of object. However, is there a generic way of getting that in all 3 frameworks? Thanks!