Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SimpleListFilter Dual Option Custom Query
I'm currently trying to code a SimpleListFilter that would be required to have either 2 select field to select the current state of the filtered object and also the current range of date that this would need to be filtered on then join those 2 value to create a custom filter on the object to get the required property. The current issue is create by the first filter which add is filter to the url and this filter isnt needed after the second filter is applied. I also tried to pop the filter using request.GET.pop('entered_state') but python return an error : In [1]: request Out[1]: <WSGIRequest: GET '/admin/requests/request/?entered_state=completed&entered_state_at=2_week'> In [2]: request.GET.pop('entered_state') AttributeError: This QueryDict instance is immutable Here is what i have done so far: class EnteredStateFilter(admin.SimpleListFilter): title = _('Entered State') parameter_name = 'entered_state' def lookups(self, request, model_admin): return ( ('completed', _('Completed')), ('denied', _('Denied')), ('expired', _('Expired')), ('cancelled', _('Cancelled')) ) def queryset(self, request, queryset): return queryset class EnteredStateAtFilter(admin.SimpleListFilter): title = _('Entered State at') parameter_name = 'entered_state_at' def lookups(self, request, model_admin): return ( ('today',_('Today')), ('1_week',_('Past 7 days')), ('2_week',_('This month')), ('3_week',_('This year')), ) def queryset(self, request, queryset): entered_state = request.GET.get('entered_state') today = datetime.now().date() if entered_state != None: if self.value() == 'today': kwargs ={'entered_{}_at__date'.format(entered_state):today} … -
django.core.exceptions.FieldError: Cannot resolve keyword 'timestamp' into field
Welcome friends, Unfortunately I have FieldError. Please help Environment: Django Version: 1.10.6 Python Version: 3.5.2 utils.py import datetime from django.utils import timezone from django.contrib.contenttypes.models import ContentType from .models import Action def create_action(user, verb, target=None): now = timezone.now() last_minute = now - datetime.timedelta(seconds=60) similar_actions = Action.objects.filter(user_id=user.id, verb=verb, timestamp__gte=last_minute) if target: target_ct = ContentType.objects.get_for_model(target) similar_actions = similar_actions.filter( target_ct=target_ct, target_id=target.id) if not similar_actions: # Nie znaleziono żadnych akcji. action = Action(user=user, verb=verb, target=target) action.save() return True return False I received this error traceback from the Django Shell: django.core.exceptions.FieldError: Cannot resolve keyword 'timestamp' into field. Choices are: created, id, target, target_ct, target_ct_id, target_id, user, user_id, verb [23/Mar/2017 17:20:46] "POST /account/users/follow/ HTTP/1.1" 500 18933 I received this error from browser console: POST http://127.0.0.1:8000/account/users/follow/ 500 (Internal Server Error) Does anyone coped with this? Does anyone have any advise for this? -
How to change a foreignkey field back to null?
Pretty new to django. I am trying to switch the foriegnkey field student_information.project back to a null value. As well my student_remove object doesn't seem to be defining properly as 'Remove' should be an object. Error Code AttributeError at /project_list/projects/1/ type object 'Student_Information' has no attribute 'student_remove' Request Method: GET Request URL: http://127.0.0.1:8000/project_list/projects/1/?Remove=sathya Django Version: 1.10.5 Exception Type: AttributeError Exception Value: type object 'Student_Information' has no attribute 'student_remove' Exception Location: /media/rms/Sathya's Dr/mysite/projects/views.py in post_detail, line 27 Python Executable: /usr/bin/python Python Version: 2.7.12 My views.py def post_detail(request, pk): post = get_object_or_404(Project, pk=pk) students = Student_Information.objects.filter(project=post) if request.GET.get('Remove'): student_remove = request.GET.get('Remove') Student_Information.student_remove.project = "---------" return render(request, 'projects/post_detail.html', {'post': post, 'students': students}) -
Blog posts not listing under Wagtail homepage
I've been successful in setting up the development server up to this tutorial: http://docs.wagtail.io/en/v1.9/getting_started/tutorial.html I'm currently at the step "Create a template at blog/templates/blog/blog_page.html:" and I'm able to create child pages that go in homepage/blog/blog-post but they aren't listing in homepage/blog as they do in the tutorial. I can't figure out why and I've tried playing with changing where the blog posts show up by placing them in homepage/blog as blog posts but still nothing. Thanks for the help! -
Install only the required packages that are not on a different machine
I have cloned my Django project from GitHub to my different machine. The other machine already has some of the latest python packages installed (eg Django v1.10.6), whereas in the requirements.txt file of the GitHub project it has different versions of the package (eg Django v1.10.5). Now when I run this command pip install -r requirements.txt It installs the version that's in the requirements.txt file. I know this is not a good idea because some of the code may not work because of version changes, but I need to learn as how can I install only the required packages that are not on my other machine or install the latest packages? -
Passing template context to form
As part of a question page for a forum app, each page contains multiple posts, one of which is a question. Each post may have many comments. However, because there are many posts per page, I do not know how to pass the post that each comment is assigned to up to the database. I was thinking of using HiddenInput, but not sure how to implement it. Code below: question_page.html <tr id="post-comment-row"> <!-- Post a comment --> {% if user.is_authenticated %} <tr> <form id="comment_form" method="post" action="." enctype="multipart/form-data"> {% csrf_token %} <!-- Display form --> {{ comment_form.as_p }} <!-- Provide a button to click to submit the form --> <input type="submit" name="submit" value="Post"> </form> </tr> {% else %} Please login to post a comment {% endif %} </tr> views.py: # Show each individual question def show_question_page(request, module_name_slug, question_page_name_slug, post_context=None): context_dict = {} module = Module.objects.get(slug=module_name_slug) question_page = QuestionPage.objects.get(slug=question_page_name_slug) question_posts = QuestionPost.objects.filter(page=question_page) comments = Comment.objects.filter(post__in=question_posts) if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Save user data to database # Save comment instance comment = comment_form.save(commit=False) comment.post = post_context comment.user_profile = UserProfile.objects.filter(user=request.user) comment.save() else: # Invalid form(s): Print errors to console/log print(comment_form.errors) else: comment_form = CommentForm context_dict['question_posts'] = question_posts context_dict['question_page'] = … -
Django Postgres JSON Field. How scalable is it
Hi all I have to decide wether to use a FileField that points to a very large json file or a postgres JSONField. The question is simple. How scalable, or how big can the JSONFields be? is it a good idea to keep a huge json string inside the JSONField? Any advice will help -
Testing custom Django middleware without using Django itself
I have coded my custom Django middleware in the 1.10 style, similar to this: class MyMiddleware(object): def __init__(self, get_response): self.get_response = get_response # some initialization stuff here def __call__(self, request): # Code executed before view functions are called. # Purpose of this middeware is to add new attribute to request # In brief: request.new_attribute = some_function_returning_some_object() response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response Note, that this middleware is being threaten as a separate Python module, not belonging to any particular application in my project, but living outside and being installed like any other package, via pip. It does not work itself, but only if installed in Django app. It works fine, however, I would like to test it. What I've made so far is something like this in my_tests.py: from my_middleware_module import MyMiddleware # some @patches def test_mymiddleware(): request = Mock() assert hasattr(request, 'new_attribute') is False # passes obviously # CALL MIDDLEWARE ON REQUEST HERE assert hasattr(request, 'new_attribute') is True # I want it to pass I don't know how to call middleware on request variable to modify it. I think it would be much easier if I … -
A server error occurred. Please contact the administrator
I try to run code which I get from git hub but I get this error on my screen A server error occurred. Please contact the administrator. I download this project from the github and also install necessary libries here is git hub link Git hub link of this project here Below I attach code settings.py # Django settings for django-tesseract project. import os def next_to_this_file(additional_path, this_file = __file__): return os.path.join(os.path.dirname(os.path.abspath(this_file)), additional_path) DEBUG = Falseor TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'djtesseract', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as … -
Possible to deploy WebRTC NodeJS Signaling server alongside existing Django application?
I have an existing Django application but I want to use one of the open source NodeJS signaling servers and host it on the same server as my Django app. The signaling server, as far as I know, is just a light weight service that uses websockets. I don't think the NodeJS and Django application need to communicate with each other (no need for state communication, sessions, etc...). The signaling server's only job is to initialize the peer-to-peer communication. So can I just deploy it on the same server but just have it listen on a different port? -
What is the right way to add a field in the middle in django
I am new to Django. I was trying to design a model in django. First I did with adding some fields, then I migrated the code. Later I found that I should have some other fields. I added some new fields, let say a CharField. Then while I was doing the migration, its showing error like you are trying to add a non-nullable field without a default. Can anybody tell should I add every time a default value to a new field OR Is there any other way to handle this? -
REST API asyn calls to micro services
I am working on many micro services for the users request. Any library do asyn call to many other services like billing, recommendation and do the check and response back. Ex: call some api get(request): // call three services async billing = billingService(user_id) //service end point 1 recommendation = recommendation_service(user_id) //service end point 2 // we will have results from three services //check conditions response to user if billing == OK: response (recommendation) // response to user -
Django Export csv from Template Results
i'm making a simple app for searching a database in order to generate a csv report. When the user clicks search I use a Django View way of rendering a post and get methods. So when the form.is_valid I run a query that gets me results and I pass it in context to render the results in a table. I need to export these values into CSV. I dont need to redirect the user to a new page I just need to download the file when the user click on the Export button. Here is my code: class AuditSearch(View): def get(self,request,*args, **kwargs): form = AuditSearchForm() context = { 'form':form, 'searchTitle':'Search Customer', } return render(request, '../templates/AuditSearch.html',context) def post(self, request, *args, **kwargs): form = AuditSearchForm(request.POST) header = ['First Name', 'Last Name', 'Employee #', 'Hire Date'] if request.POST.get('searchForm'): if form.is_valid(): results = [['MRr.', 'Green', '123456','2017-03-26']] context = {'results':results, 'header':header, 'searchTitle':'Search Customer ','form':form} return render(request, '../templates/AuditSearch.html', context) This is the view for the template that has the export button: the AuditSearch.html template has a include for {% include 'resultsPane.html '%} In the resultsPane.html file this is the code for the table that give me the results list and the Export CSV button. {% if … -
Django 1.10 group inherence and staff permission for only one instance in admin panel
How to create a group inheritance in django ? ex I have parent groups: dashboard, contact and I want to create child group Admin which should be in dashboard and contact groups. And the second questions is how to allow only particular staff to manage only selected child groups ex: Only add or remove User from Admin group. -
Can I store arbitrary attributes on the application's AppConfig class?
The recommended way to enable a Django application seems to be using an application configuration class. The documentation also states that "you can define any attributes documented in the AppConfig API reference" on that class. I wonder if I can define custom application-specific attributes on the configuration class, which I could later access via the application registry. Are there any drawbacks with this approach? -
Django select_related query does not return all values to the template
I have 2 models. Characters and CharactersDetails from a django site I'm fooling around with. CharactersDetails has a foreignkey relationship to Characters class CharactersDetails(models.Model): character_link = models.ForeignKey(Characters) In my view, I'm doing this: 'character_info': CharactersDetails.objects.select_related('character_link').filter(character_link_id=pk) In my template, I'm only getting back the fields from the CharactersDetails table. In the manage.py shell, I ran the same query and found it's actually returning the fields from both CharactersDetails and Characters (which is what I want), but when the view gets the context object, it's only showing the items from the CharactersDetails table. (looking_for_guild_env)klainn:~/workspace (master) $ python manage.py shell Python 3.4.3 (default, Nov 17 2016, 01:08:31) >>> from players.models import Characters,CharactersDetails >>> myjunk = CharactersDetails.objects.select_related('character_link').filter(character_link_id=1) >>> print(myjunk) <QuerySet [<CharactersDetails: CharactersDetails object>]> >>> print(myjunk.query) SELECT "characters_details"."id", "characters_details"."character_link_id", "characters_details"."character_class_id", "characters_details"."character_race_id", "characters_details"."character_level", "characters_details"."character_armory_url", "characters_details"."character_profile_image_url", "characters_details"."character_profile_avatar_url", "characters_details"."character_profile_inset_url", "characters"."id", "characters"."character_owner_id", "characters"."character_name", "characters"."character_realm_id", "characters"."character_faction_id", "characters"."insert_date" FROM "characters_details" INNER JOIN "characters" ON ("characters_details"."character_link_id" = "characters"."id") WHERE "characters_details"."character_link_id" = 1 I take that same query and paste it into the manage.py dbshell: (looking_for_guild_env)klainn:~/workspace (master) $ python manage.py dbshell sqlite> SELECT "characters_details"."id", "characters_details"."character_link_id", "characters_details"."character_class_id", "characters_details"."character_race_id", "characters_details"."character_level", "characters_details"."character_armory_url", "characters_details"."character_profile_image_url", "characters_details"."character_profile_avatar_url", "characters_details"."character_profile_inset_url", "characters"."id", "characters"."character_owner_id", "characters"."character_name", "characters"."character_realm_id", "characters"."character_faction_id", "characters"."insert_date" FROM "characters_details" INNER JOIN "characters" ON ("characters_details"."character_link_id" = "characters"."id") WHERE "characters_details"."character_link_id" = 1; 1|1|15|7|110|http://us.battle.net/wow/en/character/Stormrage/Peppiwyn/simple|stormrage/219/182881755-profilemain.jpg|stormrage/219/182881755-avatar.jpg|stormrage/219/182881755-inset.jpg|1|3|Peppiwyn|192|0|2017-03-20 And … -
Convert datetime field to specific timezone
i have set TIME_ZONE = 'UTC' USE_TZ = True i have a datetime field called "updated_at", i want to covert the value in this field to indian timezone.How can i do that? indian timezone is "Asia/Kolkata" -
In Django Views From .models import WhiteLabel the class name red underlined?
In Django Views "From .models import WhiteLabel" WhiteLabel is a class name where is created in the Models under same dir where views live. However the Whitelabe in Import will give me underredline. -
Django staff user can't see any application
I have a group of user called "support". I want them to be able to log in the django admin site, view and modifiy the instances of the class "HelpContextual" of the application "support". So I created a group "support" with the permission support | help contextual | Can change help contextual. The users can log in the django admin site, but they can't see any application. I tried to give them all the permissions of the "support" application, but still, they can't see the support app. If I use a direct link to change a "help contextual" like this one : admin/support/helpcontextual/5/change/, I get a 403. I feel like I'm missing something obvious... Can you point it to me ? -
Django REST Swagger: How to add oauth2/token endpoint
I'm using django-rest-swagger version 2.1.1. I used the oauth2_provider.urls to build the oauth2/token endpoint like this: urlpatterns = [ url(r'^oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')), ] The issue is that the Swagger don't detect it as endpoint so it's missing form my openapi.json file. What can I do to this endpoint in order to be able to detected by Swagger? -
How to access http array parameters in Django?
SCENARIO 1 The following are my http request parameters PHP REQUEST: localhost/test.php?cars['key_1']=Saab&cars['key_2']=Audi If I do a print_r($_GET) in php, i get the following response. Array ( [cars] => Array ( ['key_1'] => Saab ['key_2'] => Audi ) ) DJANGO REQUEST: localhost/test/?cars['key_1']=Saab&cars['key_2']=Audi while, in Django, on passing the same parameters, and on doing a print(request.GET), I get <QueryDict: {"cars['key_1']": ['Saab'], "cars['key_2']": ['Audi']}> SCENARIO 2 Again, if I do the requests without the keys, like PHP REQUEST: localhost/v2/test.php?cars[]=Saab&cars[]=Audi Array ( [cars] => Array ( [0] => Saab [1] => Audi ) ) DJANGO REQUEST: localhost/test/?cars=Saab&cars=Audi <QueryDict: {'cars': ['Saab', 'Audi']}> Now, the question is scenario 2 is working perfectly, but, how do I make scenario 1 work in Django, so that I get something like. Like how in php, i get an associative array, will I get a key-value dictionary in Django? <QueryDict: {'cars': {'key_1':'Saab', 'key_2':'Audi'}}> Is it possible? if so, how? -
Django UNIQUE constraint failed while updating model
My moddels.py looks like this: class FormObject(models.Model): def get_uuid4(self): return uuid.uuid4().hex def get_id(self): return len(self.owner.formobject_set.values('form_id').annotate(version=Max('version'))) def save(self, *args, **kwargs): if self.form_id == -1: self.form_id = self.get_id() super().save(*args, **kwargs) def new_version(self, new_pattern): temp = self.ulink self.ulink = self.get_uuid4() self.save() logging.debug("v: {}, id: {}, owner: {}".format(self.version, self.form_id, self.owner)) FormObject.objects.create(name=self.name, description=self.description, owner=self.owner, ulink=temp, version=self.version+1, form_id=self.form_id, pattern=new_pattern) pattern = models.TextField(primary_key=False) # TODO: JSONField with postgres db name = models.TextField(default='Новый опрос', primary_key=False) description = models.TextField(blank=True, primary_key=False) owner = models.ForeignKey(User) results = models.TextField(blank=True, primary_key=False) # TODO: JSONField # hash which works like unique link ulink = models.TextField(unique=True, null=False, primary_key=True, default=get_uuid4) form_id = models.IntegerField(default=-1, primary_key=False, unique=False) version = models.IntegerField(default=0, primary_key=False) answers = models.IntegerField(default=0) class Meta: unique_together = (('owner', 'form_id', 'version'), ) And the lines self.ulink = self.get_uuid4() self.save() Drops the following error django.db.utils.IntegrityError: UNIQUE constraint failed: forms_formobject.owner_id, forms_formobject.form_id, forms_formobject.version As Django documentation states, model.save() makes UPDATE SQL-query, so everything should work fine but it gives me this error. Why am I not able to update ulink field? -
Python scripts that runs every minute without stoping
I have a Python script that sends a post request to my API every 1 minute: while True: data = requests.post("URL_HERE", json={ "api_key":"XXXX", "concat": 1, "messages": "HI" }) time.sleep(60) Everything works fine, but every 2 hours (more or less) there are 2 records of the same minute. Example: 2017-03-22 11:34:46.977255 2017-03-22 11:37:47.231694 2017-03-22 11:37:47.231694 2017-03-22 11:39:48.849003 2017-03-22 11:40:48.907895 ... 2017-03-23 13:59:59.150108 2017-03-23 14:00:00.120431 2017-03-23 14:00:00.942033 I guess this is because the code inside the "while" takes a couple milliseconds to execute, thanks to that, one time every 2-3 hours a minute will have two records. Anyone knows how can I fix this? I can't use cronjobs. Maybe an asynchronous task? And If I want this program to execute forever, It is okey to use a "while", or should I create a Daemon o something similar? -
Django model validation
I'm facing a validation problem. I need to use form validation and model validation together, but django (1.10) doesn't seem to like this. Here is a short version of my setup: class MyModel(models.Model): fk = models.ForeignKey('ap.Model') foo = models.CharField(max_length=12) def clean(self): if self.fk.som_field != self.foo: raise ValidationError("This did not validate") class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ('fk',) def view(request): instance = MyModel(foo='bar') form = MyModelForm(data=request.POST, instance=instance) if form.is_valid(): # process # redirect # display template So I have some model field validation in the model itself. I need this here because it is re-used in other non-form related parts of my application. And I have some user input validation in the form. In this case, checking that the provided fk is valid and exists. But when the form is validated and the user provided 'fk' is not valid, the form is rejected. But the form also calls MyModel.full_clean add more model validation. The problem is that calling MyModel.clean() without having any data in the field fk will raise a RelatedObjectDoesNotExist exception. How can I do this the proper way ? I feel that MyModel.full_clean() should not be called by the form until the form itself is valid … -
Multiprocess is not working in Django
I've tried multiprocess in Django. The original code ran the expected respond,data,{'1':3}, to my web.However,the code ran a different respond,data{'1':7}, after replacing the called function part with process.start() My code from django.shortcuts import render from multiprocessing import Process,Manager def index(request): if request.GET.get('data'): m=Manager() data=m.dict({'1':7}) Process(target=test,args=(data,)).start() return render(request,'index.html',locals()) else: return render(request,'index.html',locals()) def test(aa): aa['1']=3