Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where to put bin, include and lib directories from virtual environment into development repository?
I have a Django project which I've been running on a local virtual environment, here's how the root directory looks (draft1 is my app). I'm now ready to push this project to a repo so I can start to develop it on a public server - so my question is - where do the bin, include and lib directories go? How do they translate from local development to when using a public server? -
'WSGIRequest' object has no attribute 'some_attribute'
I am trying to render html to pdf and include it as a django action, however, for some odd reason, I seem to keep getting the issue that the object has no attribute 'some_attribute'. My view looks like this: class CreatePdf(ContextMixin, View): def get_context_data(self, obj, request): cxt = {'some_attribute': obj.some_attribute, 'today': date.today()} return cxt def create_pdf(self, some_template, some_dict={}): template = get_template(some_template) html = template.render(some_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue()) return None And the action, which had the purpose to call everything and do all the magic, looks like this: def get_pdf(self, obj, request): pdf_view = views.CreatePdf() pdf = pdf_view.create_pdf('templates/some_template.html', pdf_view.get_context_data(obj,request)) return HttpResponse(pdf) I thought, that using get_context_data will get the fields of the selected object in the admin field, however, it seems to through me the same error. -
How to override Model.objects.all() to a subset of the same globally
The Scenario I'm developing a web application that will store multiple Organizations and each organization has it's own users. For me an organization is a domain and the domains can't see each others at database level. Instead of creating N databases/views to simplify the management and speed up the performances I store the data of all organizations onto the same database. The Goal What I want to implement is a simple way to retrieve the data from my database that are already filtered by domain. Since each domain belongs to an User (or vice versa) the first option that come in my mind is to use a queryset defined in this way: def MyCustomViewSet(viewsets.ModelViewSet) queryset = Model.objects.all(domain__iexact=request.user.domain) I can't use this solution because it forces the developer to filter all queries manually all around the web application. If for some reason someone forget to properly filter queryset, the users of an organization can see the data of other organizations (and vice versa) - It's error-prone. Using thread locals Since I can find the user inside the request another solution would be to expose the request through a middleware and automatically filter by domain using the domain of the user that β¦ -
Edit form that has ForeignKey to other model
I have a form that a user need to fill up, the model of that form as ForeignKey to another model (Question) When I create a new form, it works as I expect. When I try to do edit an existing record I am able to get the relevant data in the template but when I click on submit It fails with no error β when I debug it its failes on form is not valid and that the question is None. # form class AnswerForm(forms.ModelForm): question = forms.ModelChoiceField( label=_(u'question'), widget=forms.HiddenInput(), queryset=Question.objects.all()) description = forms.CharField( label=_(u'description'), widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '4'}), max_length=2000, required = False) link = forms.URLField( label=_(u'link'), max_length=1000, required = False) price = forms.DecimalField( label=_(u'price'), widget=forms.TextInput(attrs={'class': 'form-control'}), #max_length=100, required = False) currency = forms.ModelChoiceField( label=_(u'currency'), required=False, queryset=Currency_converter.objects.all()) class Meta: model = Answer exclude = ('user','link_domain_name',) fields = ['link','price', 'currency','description'] def clean(self): cleaned_data = super(AnswerForm, self).clean() if cleaned_data.get('link')=='' and cleaned_data.get('price')==None and cleaned_data.get('description')=='' : raise forms.ValidationError(_("You must fill at least one field!")) if cleaned_data.get('link')=='' and cleaned_data.get('price')!=None : raise forms.ValidationError(_("Add link to the price you found!")) if cleaned_data.get('price')!=None and cleaned_data.get('currency')==None : raise forms.ValidationError(_("set currency for the price you set!")) return cleaned_data #view def answer(request,question_id ,answer_id): path_to_pic = filepath_link_as_pictures() question = get_object_or_404(Question, pk=question_id) β¦ -
PyCharm + Django ImportError: cannot import from models in python console
I'm building Django website (Django 1.11.2 and Python 3.5.2), and I faced with the problem File "<input>", line 1, in <module> ImportError: cannot import name 'Test' When executing a command from events.models import Test Code of events.models # coding=utf-8 from __future__ import unicode_literals from http.client import HTTPSConnection from datetime import timedelta from django.conf import settings from django.contrib.auth import get_user_model import json from django.utils.safestring import mark_safe from django.db import models from django.urls import reverse from django.utils.timezone import now from django_cron import CronJobBase, Schedule from django.db.models import Max class EventClass(models.Model): game_class = models.CharField(max_length=100) game_name = models.CharField(max_length=100) tournament_name = models.CharField(max_length=100) tournament_round = models.CharField(max_length=100) tournament_type = models.CharField(max_length=100) class Event(models.Model): game_class = models.CharField(max_length=100) ........................................ ........................................ class Test(models.Model): test = models.CharField(max_length=100) How can I import without any error? -
Why is django 2 available under python 2?
According to Django 2.0 release notes Django 2.0 onwards will only support python 3, making the 1.11.X the last release series to support python 2. See quote from the release notes page: Django 2.0 supports Python 3.4, 3.5, and 3.6. We highly recommend and only officially support the latest release of each series. The Django 1.11.x series is the last to support Python 2.7. However when running pip2 install Django, django version 2 is being installed (which then fails because it assumes functionality not available in python 2): (venv-crap) mbp15:server nir$ pip2 install django Collecting django Downloading Django-2.0.tar.gz (8.0MB) 100% |ββββββββββββββββββββββββββββββββ| 8.0MB 177kB/s Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/PATH/django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/PATH/django/ I know I can manually specify requirement version below 2, making pip install a version valid for python 2, however that will complicate the installation process if I want to support both python2 and β¦ -
ForeignKey-Style InLines for Django Admin Scalability Issue
I have a Django 1.7 app the focuses on relationships, so: models.py class Thing1(Model): .... class Thing2(Model): .... class Relationship: relatedThing1 = ForeignKey(Thing1...) relatedThing2 = ForeignKey(Thing2...) .... #lots and lots of fields I want to be able to create and edit multiple Relationship from either the Thing1 admin form or the Thing2 admin form (a classic "One-To-Many"). Django makes this super easy with InLines. But if Relationship has 50 fields, and a Thing1 object has 100 relationships associated with it, the form tries to load 5000+ fields and tries to save all of those for every minor edit, leading to long page-loads and crashes. In reality, all I want is the same simple ChoiceField with "add or edit popout" widget you get with a traditional ForeignKey, but I have not been able to figure out how to do this (and have not found a solution in the forums or Django docs, though that may be to not searching on the right keyword). Please let me know, even if it's just that I've missed something incredibly simple and basic or if I'm asking the impossible and that this is one of the downsides of Django not directly supporting "One-to-many" relationships. -
How to pass RawQuerySet result as a JSONResponse in DJango?
I have two models like this: class McqQuestion(models.Model): mcq_question_id = models.IntegerField() test_id = models.ForeignKey('exam.Test') mcq_right_answer = models.IntegerField() class UserMcqAnswer(models.Model): user = models.ForeignKey('exam.UserInfo') test_id = models.ForeignKey('exam.Test') mcq_question_id=models.ForeignKey('exam.McqQuestion') user_answer = models.IntegerField() I need to match the user_answer and mcq_right_answer. Able to do that by executing the below raw query. rightAns=UserMcqAnswer.objects.raw('SELECT B.id, COUNT(A.mcq_question_id) AS RightAns\ FROM exam_mcqquestion AS A\ LEFT JOIN exam_usermcqanswer AS B\ ON A.mcq_question_id=B.mcq_question_id_id\ WHERE B.test_id_id=%s AND B.user_id=%s AND\ A.mcq_right_answer=B.user_answer',[test_id,user_id]) 1) But the problem is that couldn't able to pass the result as JSONResponse because it says TypeError: Object of type 'RawQuerySet' is not JSON serializable 2) Is there any alternative to this raw query by using the objects and filtered querysets? -
In Django Rest Framework how to update FK in serializer
I'm trying to add a vote functionality to the code found in tutorial of Django Rest Framework. On top of Snippet model, I added a Vote model: class Vote(models.Model): created = models.DateTimeField(auto_now_add=True) voter = models.ForeignKey(User, on_delete=models.CASCADE) snippet = models.ForeignKey(Snippet, related_name='votes', on_delete=models.CASCADE) class Meta: ordering = ('created',) After posting and validating a user vote to a snippet, I now want to update the number of votes received by the snippet (I added to the Snippet model a number_of_votes field). I'm doing it in the create method of my VoteSerializer like that: class VoteSerializer(serializers.HyperlinkedModelSerializer): voter = serializers.ReadOnlyField(source='voter.username',validators=[UniqueValidator(queryset=VoteUp.objects.all(), message=already_voted)]) snippet = serializers.PrimaryKeyRelatedField(queryset=Snippet.objects.all()) def validate(self, data): # ... my validation function def create(self, validated_data): obj = Vote.objects.create(**validated_data) obj.snippet.number_of_votes += 1 obj.snippet.save() return obj It works well but I'm not sure if it's the good way or not to do it. Is there a better way? -
How to recover deleted files that were deleted during merging
I was trying to delete all the migration files on the master branch. Git prompted: error: Merging is not possible because you have unmerged files. hint: Fix them up in the work tree, and then use 'git add/rm <file>' hint: as appropriate to mark resolution and make a commit. fatal: Exiting because of an unresolved conflict. since I did not need the migration files, I typed: git rm . -r Git prompted: error: the following files have changes staged in the index: /middleware.py project_management/models.py sales/migrations/0001_initial.py (use --cached to keep the file, or -f to force removal) Thinking that the conflicts are just due to those migration files, I typed: git rm . -r -f Now, git has removed ALL my files, including models, templates, views, static files, etc. rm '.gitignore' rm 'accounts/__init__.py' rm 'accounts/__pycache__/__init__.cpython-36.pyc' rm 'accounts/__pycache__/backends.cpython-36.pyc' rm 'accounts/admin.py' rm 'accounts/apps.py' rm 'accounts/backends.py' rm 'accounts/forms/__init__.py' rm 'accounts/forms/authenticate.py' rm 'accounts/forms/register.py' rm 'accounts/migrations/0001_initial.py' rm 'accounts/migrations/__init__.py' rm 'accounts/models.py' rm 'accounts/templates/login.html' rm 'accounts/templates/signup.html' rm 'accounts/tests.py' rm 'accounts/urls.py' rm 'accounts/views.py' Now, when I do git status It tells me this: On branch master All conflicts fixed but you are still merging. (use "git commit" to conclude merge) Changes to be committed: deleted: .gitignore deleted: accounts/__init__.py deleted: β¦ -
Moving from Django 1.3 to Django 1.11 object_list
I'm trying to update some python files from Django 1.3 to Django 1.11. In the views.py file I have a method with the following line return object_list(request, queryset=results['flips'], extra_context=context, **kwargs) I've read that object_list is now deprecated and instead of that I have to use ListView from django.views.generic.list and use Class View. I've tried with this: Django 1.3 views.py def flow(request, **kwargs): agent = 'default' lang = request.LANGUAGE_CODE.lower() cache_key = '%s%s%s' % (request.build_absolute_uri(), request.user.id, lang) results = cache.get(cache_key) if results is None: results = {} flips = pushitem.visibles.visibles().by_lang(lang=lang) sort = request.GET.get('sort', '') if sort == 'popular': flips = flips.order_by('-votes_total') else: flips = flips.order_by('-timestamp') scope = request.GET.get('scope', '') if scope: today = datetime.now() if scope == 'day': flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month, timestamp__day=today.day) if scope == 'month': flips = flips.filter(timestamp__year=today.year, timestamp__month=today.month) if scope == 'year': flips = flips.filter(timestamp__year=today.year) #Todo use UserProfile instead of User for people and add a searchfield to UserProfile (faster) query = request.GET.get('q', '') if query: people = User.objects.filter(Q(username__contains=query)) people |= User.objects.filter(Q(first_name__contains=query)) people |= User.objects.filter(Q(last_name__contains=query)) flips = flips.filter(Q(searchfield__contains=query)) topics = Tag.objects.filter(Q(name__contains=unidecode(query.lower()))) results['people'] = people results['topics'] = topics results['flips'] = flips cache.set(cache_key, results) context = { 'title': _('Flipter.com, Ask everything!'), 'description': _('The world\'s largest community of opinions, made with awesome β¦ -
Python If statement in view using queryset
I'm attempting to use the following if statement which will display an empty set if the reportaccess is equal to All Reports using the following. if reportaccess == 'All Reports': bhreportgrouplist = None cereportgrouplist = None finreportgrouplist = None careportgrouplist = None pireportgrouplist = None screportgrouplist = None dssreportgrouplist = None psgreportgrouplist = None othreportgrouplist = None else: bhreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 200) cereportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 500) finreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 600) careportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 800) pireportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1100) screportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1200) dssreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1300) psgreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1400) othreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 99999) When the view goes through it is always displaying the Else, but when I view the print of reportaccess it displays as : <QuerySet ['All Reports']> Why is my if condition not being met? How can I make it met -
Jinja2 templating options not working in test, but are fine when running server
I receive the following error... ERRORS: ?: (templates.E001) You have 'APP_DIRS': True in your TEMPLATES but also specify 'loaders' in OPTIONS. Either remove APP_DIRS or remove the 'loaders' option. ...when attempting to run any test suite, with Django 1.11 and its standard test runner. manage.py runserver, however, works just fine. I tracked the error back to the jinja2 templates. My django TEMPLATES setting looks like: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(BASE_DIR, 'jinja2')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'environment': 'mysite.jinja2.environment', }, }, { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, 'templates')], "APP_DIRS": True, 'OPTIONS': { 'debug': DEBUG, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'mysite.context_processors.app_rendering_ctx', ], }, }, ] You'll see there's no loaders key in either of the OPTIONS dicts, so the error is seriously confusing. Stripping out, it's nothing to do with the context processors or environments. It's related to the jinja2 templating... Removing the APP_DIRS key from the first entry lets the tests run: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(BASE_DIR, 'jinja2')], 'OPTIONS': { #stuff }, }, { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, 'templates')], "APP_DIRS": True, 'OPTIONS': { #stuff }, }, ] But now I can't find the jinja2 templates β¦ -
Django Return Two Separate __str__ for a Model Form
I have a Task model that includes tasks and a foreign key to entities: class Task(models.Model): task = models.CharField(max_length=500) entity = models.ForeignKey(Entity) I have a model that is related to one foreign key in Task: class Entity(models.Model): entity = models.CharField(max_length=50) type = models.CharField(max_length=50) def __str__(self): return self.entity Task is placed into a Model Form: class TaskForm(ModelForm): class Meta: model = Task fields = [ 'task', 'entity' ] The Model Form is displayed in the template like this: {{ form.task }} {{ form.instance.entity }} How would I include the equivalent of {{ form.instance.type }}? This would involve somehow including two __str__ representations in the same model form. I have seen label_from_instance used in overriding the model form, but this looks like it's only possible with ModelChoiceFields. In addition, it would render the field as a widget rather than text (like form.instance). -
Django admin TabularLine with custom intermediate fornkey
I have 3 model like this example: class A(models.Model): .... class B(models.Model): a = models.ForeignKey(A, ...) .... class C(models.Model): b = models.ForeignKey(B, ...) .... with this configuration, I would to have in my admin page for model A, a TabularLine related to the list of model C objects. Is possible this? -
PIP cannot install Django inside VIrtualenv
(myenv) wanjila@wanjila:~/Desktop/Python-Area/projects/Djangular$ pip freeze djangorestframework==3.7.3 pkg-resources==0.0.0 (myenv) wanjila@wanjila:~/Desktop/Python-Area/projects/Djangular$ pip install django Collecting django Using cached Django-2.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "/tmp/pip-build-qAnv7G/django/setup.py", line 32, in version = import('django').get_version() File "django/init.py", line 1, in from django.utils.version import get_version File "django/utils/version.py", line 61, in @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ------------------------------------ I keep getting that error whenever i try to pip install django while inside my virtualenv. How can i fix this. -
Hosting django project with mongodb
i m developing a website using above mentioned python framework and m planning to use above mentioned database. But many hosting services show only MySQL databases can be made. I need some source to refer entire website deployment process and also how exactly can i plan my deployment. Thanks in advance. -
django generated files in ec2 instance
I deployed a django application in elastic beanstalk -amazon-. Actually by following this link. The application creates and updates a file and now I would like to download it. I connected via ssh with the username ec2-user without problem, but my home directory appears to be completely empty. What I found weird is that if I run readlink -f filename the file appears to be at my home directory which, as I mentioned, is completely empty. If I understood the answer given here it shouldn't be the case. Thanks in advance for your help -
Django NoneType Error
i got this Error: Internal Server Error: / Traceback (most recent call last): File "/home/cena/AjiiMajii/.venv/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/cena/AjiiMajii/.venv/local/lib/python2.7/site-packages/django/utils/deprecation.py", line 142, in __call__ response = self.process_response(request, response) File "/home/cena/AjiiMajii/.venv/local/lib/python2.7/site-packages/django/middleware/clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'NoneType' object has no attribute 'get' [04/Dec/2017 20:08:25] "GET / HTTP/1.1" 500 65880 my middleware is : MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'cms.Middleware.Visits', ] </pre> and my custom middleware 'cms.Middleware.Visits' class Visits(MiddlewareMixin): def __init__(self,get_response): self.get_response = get_response def __call__(self, request): print '*'*22 print self.get_client_ip(request) print '*'*22 def get_client_ip(self,request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip def RedisConnection(self): Connection=redis.Redis(host='localhost',port='6379') self.Connection=Connection return self.Connection def IpCheker(self): # just set and count of visit[s] for ever ip print '%'*30 print self.get_client_ip() print '%'*30 self.RedisConnection() if self.Connection.get(self.CliReq): HashPattern=self.HashSetter(self.CliReq) UserId=self.Connection.get(self.CliReq) UserPattern="User:Id:{}".format(UserId) print UserPattern self.Connection.hincrby(UserPattern,'vcount') else: IDnum=self.IdGenerator(self.CliReq) self.Connection.set(self.CliReq,IDnum) HashPattern=self.HashSetter(self.CliReq) Location=self.GetLoc(self.CliReq) self.Connection.hset(HashPattern,'ip',self.CliReq) self.Connection.hset(HashPattern,'vcount',1) self.Connection.hset(HashPattern,'loc',Location) def HashSetter(self,ip): id=self.IdGenerator(ip) IdStyle='User:Id:{}'.format(id) return IdStyle def IdGenerator(self,ip): Count=self.Connection.keys('User:Id:*') id= len(Count) + 1 return id def GetLoc(self,ip): #GetLocation oF ip's print 'f' * 80 ApiLoc='http://www.freegeoip.net/json/' ABSLOC=requests.get('http://www.freegeoip.net/json/{}'.format(ip)) LocInfo=json.loads(ABSLOC.content) return LocInfo['country_name'] </pre> i cant resolve or debug this, why this happen? -
How can I save a key+value from external API in django models?
My idea is that I want to create sort of save/like button in my app. In my services.py and views.py I call and display the API data and the API result looks like that [ {'rating':4, 'name': 'Whatever name there is', 'id': 'whatever ID there is', } ] is there a way to save an ID part to my models and how can I implement this? considering that each time I use api, the API result might change. -
if statement in Django template issue
I am trying to compare value inside template of django. if statement is not working here is my code Model class: class Run(models.Model): run_id = models.AutoField(primary_key=True) run_name = models.CharField(unique=True, max_length=30) pms_id = models.ForeignKey('ProcessManagementSystem', db_column = 'pms_id') def __unicode__(self): return self.run_name class ProcessManagementSystem(models.Model): pms_id = models.AutoField(primary_key=True) pms_name = models.CharField(unique=True, max_length=30) def __unicode__(self): return self.pms_name My template {% for run in all_runs %} {{run.pms_id}} {% if run.pms_id == "PMSName1" %} {{run.pms_id}} {% endif %} {% endfor %} the interesting thing is when I am printing {{run.pms_id}} , it is not showing the ID, It is showing pms_name (maybe because of return self.pms_name) So during compare, I am trying to compare with name i.e. "PMSName1" instead of id But still no luck. Any suggestion how to compare? Thanks -
URL issue using multiple ids pk1 and pk2
My url is not working I am getting an error : TemplateSyntaxError at /website/project/172/ Could not parse the remainder: '=' from '=' Here is my url link : <span class="fa fa-id-card-o" aria-hidden="true"><a href="{% url 'website:EmployeDetails' pk1 = project.id pk2 = member.id %}"> Show Results</a> I guess it is coming from the pk1 = project.id pk2 = member.id but I dont know how to fomulate ir urs pattern: url(r'^project/(?P<pk>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'), url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.EmployeeDetailView.as_view(), name='EmployeDetails'), url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/api/chart/data/$',views.EmployeeChartData.as_view(), name='employeechartdata'), url(r'^project/(?P<pk>[0-9]+)/api/chart/data/$', views.ChartData.as_view(), name='chartdata'), views.py: class EmployeeDetailView(generic.DetailView, LoginRequiredMixin): #import pdb; pdb.set_trace() model = MyUser template_name = 'Employee_Details.html' def get_object(self, queryset=None): return get_object_or_404(MyUser, pk=self.kwargs['pk2'], members__project=self.kwargs['pk1']) def get_context_data(self, **kwargs): context = super(EmployeeDetailView, self).get_context_data(**kwargs) employee_name = MyUser.objects.get(id=self.kwargs['pk2']) team_list = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all() team_list_pop = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all().exclude(id=self.kwargs['pk2']) context={ 'employee_name' : employee_name, 'team_list' : team_list, 'team_list_pop' : team_list_pop } return context -
Issues in running my Python code
I was trying to run a python project located here which is for ad detection inside a video. I installed the required dependencies on my Ubuntu 16.04 (by running the dependencies.sh). I changed the comdet.py main part to account for my input file: def test_recognize(): #input_file_path = '../test/test.mp4' input_file_path = '../test/nadal-news.mp4' ad_det = ComDet() ad_det.recognize_ads_file(input_file_path) if __name__ == '__main__': #test_generate() test_recognize() After a few dependencies and import problems that I fixed, I update the mySQL password in comdet.py as below. Plus, I have to manually create a database called devaju in mysql command line. config.setdefault('database', { "host": "127.0.0.1", "user": "root", "passwd": "root", "db": "dejavu" }) The program runs by python2.7 comdet.py, but nothing happens. No prints, nothing. Do I run it correctly? Can someone help me running and get proper output? I assume it detect the time periods of ads inside the video. But I don't get anything. -
Python: 'module' object has no attribute 'logout_view'
I'm currently trying to implement the ability to log out into my django site and I'm getting the following error when attempting to use the command python manage.py runserver while in the virtual environment: (ll_env) C:\Users\me\Desktop\learning_log>python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x0000000006693BA8> Traceback (most recent call last): File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "c:\users\me\python27\Lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\me\Desktop\learning_log\learning_log\urls.py", line 22, in <module> url(r'^users/', include('users.urls', namespace='users')), File "C:\Users\me\Desktop\learning_log\ll_env\lib\site-packages\django\conf\urls\__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "c:\users\me\python27\Lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\me\Desktop\learning_log\users\urls.py", line 13, in <module> β¦ -
How to start two Django applications at the same server?
I am going to use both Saleor and Wagtail in the same project. Saleor will take care of all shop related functionalities and Wagtail will be the CMS for everything else (it is a lot of content). What I need as advice is to how can I run both applications from the same server? E.g. wagtail will serve urls like www.example.com/about-us etc. and Saleor will serve www.example.com/shop I understand that this will happen in urls.py but, what confuses me is when I run ./manage.py runserver at the Saleor end how is this going to start the wagtail server. So basically how can I start both apps with one single management command and share the resource? (it is still a localhost project) I will be thankful if somebody can show me some web resources about the topic if my approach is correct or can point in a better direction.