Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Exceptions: Django 1.8 with MSSQL Server 2017 offline
As I'm new to Django. I have installed Django = 1.8 version. I tried with MSSQL Server 2017 which is locally installed in standalone system. Apart from settings.py file I had not modified anything. It is showing ImproperlyConfigured: Django 1.11 is not supported even though i had used Django 1.8 version. Settings.py DATABASES = { 'default': { 'ENGINE': 'django_pyodbc', 'HOST': '127.0.0.1', 'NAME': 'demo2016', 'USER': '', 'PASSWORD': '', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, } } C:\Users\Vitriv-Desktop\Desktop\sqldjango>python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Vitriv-Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\base_user.py", line 52, … -
django messages for a successfully delete,add or edit item
I have started using django messages for creating items. It works great for creating adding a new item. but.. I want to have functions for each action - delete,create,edit ( I have different buttons for each) I have only post function.. it really confuse me when I try to create a message that the item has been deleted successfuly.. how can I know a delete was submitted and not post? since everything goes through post function. The PostEdit and Delete don't have the "request" that it requires for messages. So for now I h ave only messages.succuess that runs everytime I create a server. I want to have a different message for delete, edit, create and same for errors. Does anyone have a clue? index.html - {% if messages %} <ul class="messages"> {% for message in messages %} <div class="alert alert-success alert-dismissible fade show" role="alert"> <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endfor %} </ul> {% endif %} views.py - # Create your views here. from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, … -
ModuleNotFoundError: No module named 'cart.forms'
Python3.6 Django project. views.py: from django.shortcuts import render, get_object_or_404 from .models import Category, Product from cart.forms import CartAddProductForm output: ModuleNotFoundError: No module named 'cart.forms' I already installed cart, but still have this error. -
How to get the object from a Django Rest Framework serializer init method?
I have my serializers code set up as follows: class ProductSerializer(serializers.ModelSerializer): """ * Serializes Products. """ def __init__(self, *args, **kwargs): print kwargs.pop('product_passed') super(ProductSerializer, self).__init__(*args, **kwargs) Now, this serializer is being called from a view using the code below: product_passed = self.get_object(pk) product_serializer = ProductSerializer(product_passed) What I want to do is call the product_passed from my serializer init method. How can I do this? Right now, my method does not work. -
Sorting a partially linked list in sql
I have declared a task-priority list in SQL like so: CREATE TABLE TaskList( id int not null primary key, execute_before int null, SomeData nvarchar(50) NOT NULL) I now want to select rows from this table such that the rows would be sorted by id, but any rows that "execute_before" a given row would be placed before such rows, again sorted by id. So, if the table contains data like this: id execute_before 1 null 2 null 3 2 4 3 5 2 6 null the result should be like so: id execute_before 1 null 4 3 3 2 5 2 2 null 6 null My target SQL server is PostgreSQL, but I'm using it through Django, so either of these solutions is fine. -
Django Rest framework not giving 403 error for unauthenticated user
I'm making an api with django normal view using Django restframework token, decorator and permissions like below @api_view(['GET']) @permission_classes((IsAuthenticated, )) def test(request, format=None): permission_classes = [IsAuthenticated] content = {"hello":"world"} return Response(content) It Always give me the result even if i didn't add a token to the header note that i added all the required settings my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'rest_framework', 'rest_framework.authtoken', #'utils', 'schedule', ] # SWAGGER_SETTINGS = { # 'JSON_EDITOR': True, # } MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), # 'DEFAULT_RENDERER_CLASSES': ( # 'rest_framework.renderers.JSONRenderer', # ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2, 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' }REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), # 'DEFAULT_RENDERER_CLASSES': ( # 'rest_framework.renderers.JSONRenderer', # ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2, 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' } As per the documentation it should give 403 status error since user is not authenticated but it is giving 200 response with normal data