Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
factory-boy create a list of SubFactory for a Factory
I am using django 1.6 and factory-boy. class UserFactory(factory.Factory): class Meta: model = models.User username = factory.Sequence(lambda n: 'user%d' % n) Here username is a simple CharField in model. So that each time I am calling UserFactory() I am saving and getting unique user named object. In factory-boy I can use factory.SubFactory(SomeFactory). How I can generate list of SomeFactory in ParentOfSomeFactory ? So that, if I call ParentOfSomeFactory() I will create list of SomeFactory as well as ParentOfSomeFactory database -
Django - How to allow only the owner of a new post to edit or delete the post?
I will be really grateful if anyone can help to resolve the issue below. I have the following Django project coding. The problem is: when the browser was given "/posts/remove//" or "/posts/edit/(/" as the url, it will allow the second user (not owner) to perform the remove and edit jobs, respectively. How can i allow only the owner of a new post to edit or delete the post? Thanks for the help, again. account.models.py: from django.db import models from django.conf import settings class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) def __str__(self): return 'Profile for user {}'.format(self.user.username) posts.models.py: from django.db import models from django.conf import settings from django.utils import timezone from django.utils.text import slugify from django.core.urlresolvers import reverse from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='posts_created') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique_for_date='created') image = models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True) description = models.TextField(blank=True) created = models.DateTimeField(default=timezone.now, db_index=True) updated = models.DateTimeField(auto_now=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='posts_voted', blank=True) status = models.CharField(max_length=10, default='published') objects = models.Manager() # The default manager. published = PublishedManager() # The Dahl-specific manager. tags = TaggableManager() class Meta: ordering = ('-created',) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Post, … -
ImportError on urls.py while running the python Django app
I'm doing a Python-Django web app.And I got an error on urls.py when I'm trying to run the project using python manage.py runserver The below given is my error. Not Found: /hello [09/Nov/2016 16:22:34] "GET /hello HTTP/1.1" 404 1920 Performing system checks... Unhandled exception in thread started by <function wrapper at 0xb68f7924> Traceback (most recent call last): File "/home/nishanth/nenv/local/lib/python2.7/site-packages/Django-1.10.3-py2.7.egg/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/nishanth/nenv/local/lib/python2.7/site-packages/Django-1.10.3-py2.7.egg/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/home/nishanth/nenv/local/lib/python2.7/site-packages/Django-1.10.3-py2.7.egg/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/home/nishanth/nenv/local/lib/python2.7/site-packages/Django-1.10.3-py2.7.egg/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/home/nishanth/nenv/local/lib/python2.7/site-packages/Django-1.10.3-py2.7.egg/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/nishanth/nenv/local/lib/python2.7/site-packages/Django-1.10.3-py2.7.egg/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/nishanth/nenv/local/lib/python2.7/site-packages/Django-1.10.3-py2.7.egg/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/home/nishanth/nenv/local/lib/python2.7/site-packages/Django-1.10.3-py2.7.egg/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/nishanth/nenv/local/lib/python2.7/site-packages/Django-1.10.3-py2.7.egg/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/nishanth/nenv/local/lib/python2.7/site-packages/Django-1.10.3-py2.7.egg/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/nishanth/nenv/local/lib/python2.7/site-packages/Django-1.10.3-py2.7.egg/django/urls/resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/nishanth/Documents/register/register/urls.py", line 16, in <module> from django.conf.urls import patterns, include, url ImportError: cannot import name patterns Performing system checks... This is my urls.py from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns['', url(r'^admin/', … -
How to make an authentication API with Django REST Framework?
I am trying to make an API for a view which can only be edited if you are logged in. The application I have in mind will have Facebook and Google authentication. In the DRF Tutorial the following line is given to test that a view works with authentication: http -a tom:password123 POST http://127.0.0.1:8000/snippets/ code="print 789" You can see that they have used the username and password inside the call. What I am trying to understand is how can an app make that kind of request if it doesn't know the password of the user? I believe some sort of authentication token is generated. If that is the case, then how can the above request be made with the authentication token? -
How to custom gunicorn logger formatter?
I use gunicorn + nginx + supervisor +django . I got this log : [2016-11-09 19:27:53 +0000] [14676] [DEBUG] GET /audit/list_pay/ this is my start gunicorn cmd: gunicorn myproject.wsgi:application --workers 4 --bind 0.0.0.0:8001 --log-level debug --log-file=- my supervisor conf: [program:cmdb] command= /usr/local/cmdb/cmdb_gunicorn_start directory=/usr/local/cmdb startsecs=0 stopwaitsecs=10 autostart=false autorestart=false stdout_logfile=/data/logs/cmdb_gunicorn.log redirect_stderr=true I put --access-logformat "%(h)s %(l)s %(u)s %(t)s %(s)s %(b)s" append the gunicorn start cmd , but it not work . I try another gunicorn log params , but they not work .I do not know which logger parameters can be used . what i should do to get more logger info . -
Django string_if_invalid and default
I have string_if_invalid set to 'INVALID' in my django template settings. And there is some template that looks like this: {{ some_nonexisting_value|default:'Default value' }} After rendering result looks like 'INVALID'. So, default value is not used. Is there any way to make string_if_invalid to work with default values without changing templates? -
MySQL "Deadlock found" when updating Django relationship
I'm experiencing yet another 'Deadlock found when trying to get lock; try restarting transaction' exception with MySQL. The affected table is a "linker table" with three columns: an id and two FKs to other tables' ids. (I know, I don't need an id for such a table, but I'm using Django.) It sometimes occurs when updating N:M relationships represented by that table. *** (1) TRANSACTION: TRANSACTION 991922, ACTIVE 1 sec inserting mysql tables in use 1, locked 1 LOCK WAIT 10 lock struct(s), heap size 2936, 5 row lock(s), undo log entries 2 MySQL thread id 37597, OS thread handle 0x7fa4b441e700, query id 1208524 localhost 127.0.0.1 mydb update INSERT INTO `mytable` (`column1`, `column2`) VALUES (328988, 872), (328988, 858) *** (1) WAITING FOR THIS LOCK TO BE GRANTED: RECORD LOCKS space id 32796 page no 2432 n bits 536 index `column1` of table `mydb`.`mytable` trx id 991922 lock mode S waiting Record lock, heap no 15 PHYSICAL RECORD: n_fields 3; compact format; info bits 32 0: len 4; hex 8005051d; asc ;; 1: len 4; hex 80000368; asc h;; 2: len 4; hex 8005dafa; asc ;; *** (2) TRANSACTION: TRANSACTION 991929, ACTIVE 1 sec inserting mysql tables in use 1, locked … -
Multiple Handlers for Loggers in Django
In the setting.py file of Django we have the LOGGING dictionary, which has key-value pairs of loggers and handlers, How to I set multiple handlers (e.g both file and console) for a logger. -
Django REST browsable API POST
I'm trying to make Django REST's browsable API work, however each time I'm trying to send a POST request, it somehow transforms into GET and obviously get the 405 response "detail": "Method \"GET\" not allowed." I have a view based API. The API itself works properly when I post from Javascript, for instance. Any ideas of what is going on or where to start debugging? -
Django ManytoMany filter exact list
Suppose I have a list of id's: c = ['1', '2' , '3'] class Topic(Model): categories=ManyToManyField(Category) How can I filter topics that have exact and only categories with id's from c? -
How to handle double level validation (Form + API)
I Work on a Django project that uses django forms. after forms validation I need to make call to a django-rest-framework API which validates the same form data for a second time. What is the best practices to stay DRY and to do not rewrite validation logic twice ? -
Django fresh install: Admin JS Error
After a fresh install of Django 1.10.3 I get the following Javascript error in Django admin: Browser console: GET http://s3.eu-central-1.amazonaws.com/forton/http_headers_1.js (anonymous function) @ VM5471:1 (anonymous function) @ VM5471:1 Any advice from your side? -
Log into a Django project using Magento user database SSO
So i'm currently working on a Magento website that manages the store side of the website. However, i also have a wordpress install that manages a blog and some other custom content pages. However, i'd like to replace the wordpress website (as it's a terrible state) with a django project. The current issue is users are having to register to both websites in order to seek the benefits. I will also have the same issue if i were to re-develop the application in Django. Ideally i'd like to somehow share the users from Magento with my Django project. The users don't need to be stored in Django, but they need to be able to login / register to one and essentially be able to access all aspects of the website. I've tried doing some research and i'm wondering whether SSO is a good route to go down? However, i'm not entirely sure how that works. Would it be something i install on the Django project? Then just provide Django the correct API information? I think it might be something that's a little out my league but it would be good to get a better understanding and what options I have … -
Increase the length of username field in django auth_user table using postgres database
I am working on django project and want to increase the max length of username field in auth_user table. I tried to change it from database and when i did it returned a error ERROR: must be owner of relation auth_user How can i resolve it, or is there any another easy option ? -
Display uploaded/chosen image without saving it in database in Django
I'd like to store the image which the user uploads, in a variable within views.py (and apply some opencv operations on it) and then display the resultant image. I don't want to store the image in a database. So, i don't think models are necessary for implementing this. How to proceed further? Following are the index.html and views.py. Sorry if any coding mistakes are there, i'm new to Django. index.html <form method="POST" enctype="multipart/form-data">{% csrf_token %} <div class="file-field input-field left"> <div class="btn black-text waves-effect waves-dark" style="background-color: #F5DF73"> <div>Upload</div> <input type="file" name = "input_image" onchange="readURL(this);"> </div> <div class="file-path-wrapper"> {#<input class="file-path validate" type="text">#} </div> </div> {{ image }} </form> views.py def upload_pic(request): if request.method == 'POST': form = ImageUploadForm(request.POST) image = form.cleaned_data['image'] return render(request, 'html/index.html', {"image": image}) -
Django-crispy-form: add HTML element inside of `Field` class
This is default HTML structure when using Field class of django-crispy-form. Field( 'need_meeting', autocomplete='off', id='need-meeting', ), .html <div class="form-group"> <div id="div_id_need_meeting" class="checkbox"> <label for="need-meeting" class=""> <input autocomplete="off" checked="checked" class="checkboxinput" id="need-meeting" name="need_meeting" type="checkbox"> 현금영수증 발행 </label> </div> </div> But what I want to do is to add some elements(<i></i>) inside of label element like this: <div class="form-group"> <div id="div_id_need_meeting" class="checkbox"> <label for="need-meeting" class=""> <input autocomplete="off" checked="checked" class="checkboxinput" id="need-meeting" name="need_meeting" type="checkbox"> <i></i>현금영수증 발행 </label> </div> </div> I have no idea even I searched for 2hours. Need your help. Thanks -
djnago_cron executes only once , scheduler not working?
I have to implement task on schedule , for that i am using django_cron. In setting : INSTALLED_APPS = [ 'mailsnake', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Avaana_web', 'rest_framework', 'rest_framework.authtoken', 'django_cron', ] and cron.py from django_cron import CronJobBase, Schedule,cronScheduler import datetime,os class MyCronJob(CronJobBase): RUN_EVERY_MINS = .3 RETRY_AFTER_FAILURE_MINS = 5 ALLOW_PARALLEL_RUNS = True schedule = Schedule(run_every_mins=RUN_EVERY_MINS, retry_after_failure_mins=RETRY_AFTER_FAILURE_MINS) code = 'my_app.my_cron_job' def do(self): print("hello") but when i run $ python manage.py runcrons hello Only once output shows and ends. How i can get output after every 30 seconds. -
Paginating a list returned by a ViewSet in Django Rest Framework
I have created a ViewSet class with a overridden list method like this: from rest_framework.response import Response from rest_framework import viewsets class MyViewSet(views.ViewSet): def list(self, request): return Response([ {"id": 1}, {"id": 2}, ]) How do I paginate this response? In settings.py I've the following setup: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'LinkHeaderPagination', 'PAGE_SIZE': 10 } And LinkHeaderPagination is built like this: from rest_framework import pagination from rest_framework.response import Response class LinkHeaderPagination(pagination.PageNumberPagination): page_size_query_param = 'page_size' def get_paginated_response(self, data): next_url = self.get_next_link() previous_url = self.get_previous_link() if next_url is not None and previous_url is not None: link = '<{next_url}>; rel="next", <{previous_url}>; rel="prev"' elif next_url is not None: link = '<{next_url}>; rel="next"' elif previous_url is not None: link = '<{previous_url}>; rel="prev"' else: link = '' link = link.format(next_url=next_url, previous_url=previous_url) headers = {'Link': link, 'Count': self.page.paginator.count} if link else {} return Response(data, headers=headers) This works great with ModelViewSets since they have a specified queryset, but how do I paginate a list? -
crspy-forms layout not work for django inline formset
This is my forms and inlineformset class EventForm(ModelForm): def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Field('name'), Field('description'), Field('tags'), ) self.helper.layout.append(Submit('save', 'Save')) class Meta: model = Event fields = ('name','description','tags', ) class GalleryForm(ModelForm): def __init__(self, *args, **kwargs): super(GalleryForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.form_class = 'form-inline' self.helper.form.method = 'post' self.helper.form.action = '' self.helper.layout = Layout( Div( Div('title', css_class='col-md-4', ), Div('image', css_class='col-md-4', ), css_class='row', ), FormActions( Submit('submit', 'Submit'), ), ) class Meta: model= Gallery fields = ('title', 'event', 'image') GalleryFormSet = inlineformset_factory(Event, Gallery, extra=0, min_num=1, fields=('title', 'image' )) My views: class EventCreateView(FormsetMixin, CreateView): template_name = 'member/event_and_gallery_form.html' model = Event form_class = EventForm formset_class = GalleryFormSet class EventUpdateView(FormsetMixin, UpdateView): template_name = 'member/event_and_gallery_form.html' is_update_view = True model = Event form_class = EventForm formset_class = GalleryFormSet my form.html: {% block body %} <form action="." method="post" enctype="multipart/form-data"> {{ formset.management_form }} {% csrf_token %} <legend>Event</legend> <div class="event"> {{ form|crispy}} </div> <legend> <div class="pull-right"><a href="#" class="btn btn-inverse add-photo"><i class="icon-plus icon-white"></i> Add Photo</a></div> Photo Gallery </legend> <div class="gallery form-inline"> {% for form in formset %} {{form|crispy}} {% endfor %} </div> <div class="form-actions"> <button type="submit" class="btn btn-primary">Save</button> </div> </form> {% endblock %} But it didn't give inline formset … -
How to get the head node in linkedlist python
I've been trying to find a way to get the first data. this is my data in database for example. id name next 001 task1 002 002 task2 003 003 task3 000 what I want to do is to get the first value of the headnode which should be 001 as shown in the database. this is my code while True: self.headNode = 000 try: lastNode = Task.objects.get(next=self.headNode) self.headNode = lastNode.id break except Task.DoesNotExist: break What I expect here, the value of self.headNode should be 001 but it gave me 003. Please help me how to get that 001. I've been working on this for almost a month now. -
CSRF error when using a cached response
I am doing some aggressive caching and this results in a CSRF error when I use a previously cached old response. Is there a way to just refresh the csrf token inside the cached response? Unable to understand the Caching section in https://docs.djangoproject.com/en/1.10/ref/csrf/ Can someone elaborate a bit on this? -
Correct way to save foreign key using ModelForm
I already tried to save foreign key using ModelForm,but I got this error: The LabRequestForm could not be created because the data didn't validate. Here is my code: model.py class LabRequestForm(models.Model): # lab request form product_name = models.ForeignKey(ProductName, on_delete=models.CASCADE) ref_no = models.CharField(max_length=200, unique=True) date = models.DateTimeField() batch_number = models.CharField(max_length=200, unique=True) sampling_time = models.DateTimeField() lab_test_number = models.CharField(null=True, max_length=200) forms.py class LabRequestModelForm(ModelForm): class Meta: model = LabRequestForm fields = '__all__' views.py @login_required def sampler(request): detect_user = Account.objects.get(id=request.user.id) if detect_user.is_sampler: if request.method == "POST": prod_name = ProductName.objects.get(product_name=request.POST.get('product_name')) lab_req_form = LabRequestModelForm(request.POST) lab_req_form_obj = lab_req_form.save(commit=False) lab_req_form_obj.product_name = prod_name if lab_req_form_obj.is_valid(): lab_req_form_obj.save() messages.info(request, 'Form Saved') else: print('not valid') messages.error(request, "Form is not valid") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) Manually I checked every POST data, they were correct. So I suspect lab_req_form.save(commit=False) is the main culprit. -
Django Function returning dynamic model caches values inside
Recently I have encountered a Django app in which a function return a full dynamic model. There are a some fields that are to be enabled from the admin of the site. The returning model will only keep the fields as attributes that it finds allowable at that time. When data is requested from user, the data from the fields is returned from that dynamic model, which is sort of caches the data in it. try: # This fials first time. # Interestingly this also fails after some time of inactivity. cached_model = get_model("core","FeatureClass{0}".format(self.id)) except (LookupError, ValueError): class Meta: db_table = self.sql_schema + '"."' + self.sql_table attrs = dict( __module__='mapport.core.models', Meta=Meta, fields=fields,# function defined elsewhere form=get_form,# function defined elsewhere layer=self, # this is another model's scope calling it. objects=models.GeoManager(), sql_geometry_field=self.sql_geometry_field, to_json=to_json ) site_acl = kwargs['acl'] if 'acl' in kwargs else None attrs[self.sql_geometry_field] = models.GeometryField(srid=srid) timestamp_set = False for field in self.fields(acl=site_acl): if (field.sql_name == self.sql_geometry_field or field.sql_name == self.sql_id_field): continue AttrClass = { 'integer': models.IntegerField, 'number': models.FloatField, 'date': models.DateField, 'datetime': models.DateTimeField }.get(field.type, models.CharField) attrargs = dict( db_column=field.sql_name, null=True, blank=True ) if AttrClass is models.CharField: attrargs['max_length'] = 255 if field.sql_name == self.sql_touch_field: attrargs['auto_now'] = True timestamp_set = True attrs[field.attrname()] = AttrClass(**attrargs) … -
Error "The parameter redirect_uri is required"
i am using allauth app. but when i am trying to login using faceook than it is showing me a error The parameter redirect_url is required But i already given a redirect url to it.Error while logging in using facebook Redirect uri login code <div style="position:absolute;left:420px;top:118px;height:400px;width:200px;" id="login"> <form method="POST" action=""> {% csrf_token %} <label style="position:absolute;left:60px;top:50px;color:red;">Username</label> <p style="position:absolute;left:160px;top:43px;">{{ form.username }}</p> <label style="position:absolute;left:64px;top:111px;color:red;">Password</label> <p style="position:absolute;left:160px;top:103px;">{{ form.password }}</p> <input style="position:absolute;left:210px;top:163px;height:36px;width:80px;background-color: #c52d2f;border-radius: 6px;color:white;" type="Submit" value="Login"/> <a style="position:absolute;left:64px;top:171px;font-size:15px;font-weight:800;" href="{% url 'new' %}">Reset Password</a> <a href="https://www.facebook.com/dialog/oauth?client_id={{ 198608780589573 }}&amp;scope={{ scope }}&amp;redirect_uri="{{ "http://127.0.0.1:8000/about_us" }}">Login using Facebook</a> </form> </div> -
Modeling Aggregate Weight of Parts that are Composed of Parts.
I have the following simplified model: class Part(models.Model): identification = models.CharField(max_length=50) parent_part = models.ForeignKey('Part',blank=True,null=True) weight = models.DecimalField(max_digits=12,decimal_places=3) As you can see, a Part can be composed of others parts, each with it's own weight, forming a tree. Of course, the top level part (root) will have no "parent_part". What I'm struggling right now it to implement a way to sum all the weight of all the subparts. All my ideas so far fall in some form of recursion that I know that should be avoided. BAsed in my knowledge, I think that the proper solution would be through Model Managers but I'm not sure how. Any suggestions?