Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Relocating manage.py in Django project
While looking for organizing a Django project, I stumbled upon this question. I moved the manage.py to scripts/ directory, wrote a setup.py script similar to this, and did a python setup.py install to add manage.py to PATH. Things were working fine. But when I wrote a test and did a manage.py test, its not finding the test module. Doing a python setup.py install doesn't help as well. What am I missing here? I find having scripts directory with all the script files as meaningful. Is there any other way of organizing a Django project? -
Getting 0 when using json.decode
I am a beginner in Django as well as python I first generate 50 random numbers and store it in list and then in text field in model User. def generate(request, user_id): easy = [] * 55 cnt = 0 while cnt < 50: random_id = random.randint(1, 200) if random_id not in easy: easy.append(random_id) cnt += 1 current_user = User.objects.get(pk=user_id) current_user.question_array = json.dumps(easy) return render(request, 'comp/question.html', {'easy': easy[0], 'question_id': 1,'user_id':user_id}) But when i try to retrieve the value from field i get only 0. When i try to use it as list it shows error of int object cannot be subscript Following code to retrieve. def next(request,user_id, question_id): current_user = User.objects.get(pk=user_id) jsonDec = json.decoder.JSONDecoder() easy = jsonDec.decode(current_user.question_array) return render(request, 'comp/question.html', {'easy': easy, 'question_id': int(question_id) + 1,'user_id':user_id}) I have used answer of [this][1]question -
page getting redirect after ajax request
I am new to ajax and I want to delete the student from the list by ajax request and i want to print the print the response of the request on the same page in the particular div. but response getting redirect to new page. here is my views.py def delete_student(request): response = {"status": False, "errors": []} student_id = request.GET.get('student_id', '') if request.method == "POST": form = DeleteStudentForm(request.POST) if form.is_valid(): student = Student.objects.get( user__username = form.cleaned_data["username"] ) student.delete() response["status"] = True else: for key, value in form.errors.items(): tmp = {'key': key, 'error': value.as_text()} response['errors'].append(tmp) return HttpResponse(json.dumps(response)) here is my ajax request function delete_student(student_id){ $.ajax({ url: Window.base.urls.delete_student+"?student_id="+student_id, type: $this.attr('method'), data: $this.serialize(), success: function(response){ response = JSON.parse(response); if(response.status){ console.log(student_id) $('#id_response').append(JSON.stringify(response)) $('#id_student_'+student_id).remove(); $('#delete_more_student').removeClass('disabled'); $('#delete_more_student').attr('onclick', 'open_delete()'); }else{ $('#id_response').append(JSON.stringify(response)); } } }); return false; } and here is my form <form class="form-horizontal" id="id_delete_student" action="{% url 'delete_student' %}" role="form" method="post" onsubmit="return delete_student('{{ student.id }}')" style="display: none;"> {% csrf_token %} <div class="row"> <div class="col-md-12"> <div class="form-group" id="id_username_error_parent_div"> <div class="col-md-12"> <label for="id_username" class="control-label">*Username:</label> {{ delete_student_form.username }} <small class="error-msgs error" id="id_username_error" style="display: none;"></small> </div> </div> </div> </div> -
Django QuerySet.extra define new column and use where clause to filter on it
I filter a result on one of my models based on user query and criteria and that is the results value. Then, I want to sum the total of some columns creating column total and then order by desc value: finalResult = results.extra( select = { 'total': total_str }, order_by=('-total',)) The above works great! FYI the total_str is a string of which columns to sum, looks something like "columnA + columnB" or "columnC + columnA + columnR" ...etc now I want to filter on minimum score finalResult = results.extra( select = { 'total': total_str }, where = ['total > %s'], params = [minimum_score], order_by=('-total',)) but this is now failing with (1054, "Unknown column 'total' in 'where clause'") how do I make it work ? This seems to be a bug in Django, it is only checking the original columns of the table. I should mention I am running Django 1.8 and the backend database I am testing with is MySQL. django-admin.py --version 1.8 -
Django Collectstatic with AWS S3 not copying correct static and media files
I am trying to copy all of my static and media files to an S3 bucket. Unfortunately despite the fact that my media root and static root are provide in my settings.py file.... DEFAULT_FILE_STORAGE = 'jeffrey.aws_storage_classes.MediaStorage' AWS_ACCESS_KEY_ID = 'keyhere' AWS_SECRET_ACCESS_KEY = 'secretkeyhere' AWS_STORAGE_BUCKET_NAME = 'bucketname' STATICFILES_STORAGE = 'jeffrey.aws_storage_classes.StaticStorage' AWS_S3_DOMAIN = "%s.s3.amazonaws.com" % AWS_STORAGE_BUCKET_NAME STATIC_URL = "https://%s/static/" % AWS_S3_DOMAIN MEDIA_URL = "https://%s/media/" % AWS_S3_DOMAIN MEDIA_ROOT = u'/home/namehere/mysite/media' STATIC_ROOT = u'/home/namehere/mysite/static' ....files from my django contrib folder seem to be being copied, and my files in static and media folders are not. Below is my bash console: Type 'yes' to continue, or 'no' to cancel: yes Copying '/usr/local/lib/python2.7/dist- packages/django/contrib/admin/static/admin/css/fonts.css' Copying '/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/img/icon-addlink.svg' Copying '/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/img/icon-no.svg' Copying '/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/img/inline-delete.svg' .... .... Copying '/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/img/gis/move_vertex_on.svg' Copying '/usr/local/lib/python2.7/dist-packages/django/contrib/admin/static/admin/img/gis/move_vertex_off.svg' 61 static files copied. -
How to pass multiple date1 i.e(10/12/2016) , date2 i.e(23/12/2016) to url in django?
I am trying to pass starting_date i.e(10/12/2016) ,report_to_date i.e(23/12/2016) starting_date = '31/12/2015' report_to_date = '31/12/2016' <a class ="btn btn-success" href="/downloadpdf/"+starting_date+"/"+report_to_date+"/">Download</a> below url not working - url(r'^/downloadpdf/(?P<starting_date>[A-Za-z0-9+/=]+)/(?P<report_to_date>[A-Za-z0-9+/=]+)/$', views.report, name='report'), I need the date i.e '31/12/2015' and i.e '31/12/2016' format/date object to my view function : def report(request,starting_date,report_to_date): starting_date = parse('starting_date') report_to_date = parse('report_to_date') this is not working. Please help me.. Thanks in advance. -
Who I can reference the blog model of mezzanine in a Django and python project
I am developing an app in a project that has installed the Mezzanine CMS framework for Django available in https://github.com/stephenmcd/mezzanine. I would like to reference the blog model that is shown as from mezzanine.blog.models import BlogPost, BlogCategory in the original source code, but I am getting an error message that says that mezzanine is an unresolved reference as well as BlogPost, BlogCategory I tried several ways to do it like from newsletter.mezzanine.blog.models import BlogPost, BlogCategory where I get the error message File "/Users/jorgezavala/PycharmProjects/mezzanine/newsletter/newsletter/campaign/urls.py", line 4, in <module> from newsletter.mezzanine.blog.models import BlogPost, BlogCategory ImportError: No module named mezzanine.blog.models I do not have a clue how to make the references to be able to access the information available in the posts that I created with mezzanine to be processed by an independent application within the same project. Any help will be very much appreciated -
compare and complete lists with each other
I have here a very tricky task here.I want to compare x number of lists in list of lists and that lists contain dictionaries.So i want to compare the dictionaries in these lists based on the 'name' key in the dictionaries if it match it should pass if not it should copy the whole dictionary to the lists that doesn't have with editing the 'balance' key to '0'. For example let's assume we have list of lists like this : list_of_lists=[[{'name': u'Profit','balance': 10},{'name': u'Income','balance': 30},{'name': u'NotIncome','balance': 15}],[{'name': u'Profit','balance': 20},{'name': u'Income','balance': 10}]] So the result should be : list_of_lists=[[{'name': u'Profit','balance': 10},{'name': u'Income','balance': 30},{'name': u'NotIncome','balance': 15}],[{'name': u'Profit','balance': 20},{'name': u'Income','balance': 10},{'name': u'NotIncome','balance': 0}]] Here is my code but i can't get it work with 2 lists or more(I don't know the number of lists in the list (maybe 2,3 or 4 etc...) : for line in lines: for d1, d2 in zip(line[0], line[1]): for key, value in d1.items(): if value != d2[key]: print key, value, d2[key] -
How to add seperate functions to the same view?
I have a main function for my homepage and then 2 other functions (in the same views file) for register and login. I could put the other 2 functions into the main view function but I want to keep them seperate for readability. Any way to do this? Here is my code: views.py def boxes_view(request): question_list = Question.objects.all().order_by('-date') choice = Choice.objects.all() q_list = [] returned_list = [] for i in question_list: q_list.append(i) for a, b in CATEGORY_CHOICES: name = resolve(request.path_info).url_name if b == name: category = a search = request.GET.get('search') posts = Post.objects.all().filter(category=category).order_by('-date') if search: posts = posts.filter( Q(title__icontains=search) | Q(content__icontains=search) ) else: posts = Post.objects.all().filter(category=category).order_by('-date') total = 0 for post in posts: returned_list.append(post) total += 1 if total == 4: total = 0 for i in q_list: returned_list.append(i) q_list.remove(i) break paginator = Paginator(returned_list, 14) page = request.GET.get('page') try: lst = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. lst = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. lst = paginator.page(paginator.num_pages) context = { 'question_list': question_list, 'choice': choice, 'posts': posts, 'lst': lst, } return render(request, 'polls.html', context) def register(request): form = UserRegistrationForm(request.POST) if form.is_valid(): username … -
File object not saving to disk
This is my views.py from django.shortcuts import render # Create your views here. from forms import DocumentForm from models import Document def SaveDocument(request): saved = False if request.method == "POST": #Get the posted form MyDocumentForm = DocumentForm(request.POST, request.FILES) if MyDocumentForm.is_valid(): print 'It enters here' document = Document() document.name = MyDocumentForm.cleaned_data["name"] document.document = MyDocumentForm.cleaned_data["document"] print document.document document.save() saved = True else: print 'Fails' else: MyDocumentForm = DocumentForm() return render(request, 'saved.html', locals()) profile.html <html> <body> <form name = "form" enctype = "multipart/form-data" action = "{% url "SaveDocument" %}" method = "POST" >{% csrf_token %} <div style = "max-width:470px;"> <center> <input type = "text" style = "margin-left:20%;" placeholder = "Name" name = "name" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <input type = "file" style = "margin-left:20%;" placeholder = "document" name = "document" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <button style = "border:0px;background-color:#4285F4; margin-top:8%; height:35px; width:80%; margin-left:19%;" type = "submit" value = "Login" > <strong>Login</strong> </button> </center> </div> </form> </body> </html> The code works perfectly fine but it does not seem to save the file to disk. Printing the document shows that there is a document. May i know what i did wrongly? i was following this example … -
Django form template customization
New to django (and in general python). I'm trying to customize one of my forms a bit and would like to know the best way to do this. Take for example the following, a form with 3 fields, two fields for weight entry and one for a target date. class BasicFitnessGoalForm(forms.ModelForm): class Meta: model = BasicFitnessGoal fields = ('currentWeightKg','targetWeightKg','targetDate') widgets = { 'targetDate': forms.DateInput(attrs={'class':'formdatepicker'}), } labels = { 'currentWeightKg' : "Current Weight", 'targetWeightKg' : "Goal Weight", 'targetDate' : 'Goal Date' } I want to be able to display this form in my templates using something like goalForm.as_p() which generates html like the following: <p> <label></label><input><input>... What I am looking to do is on the weight fields insert an extra element after the input tags and customize the text and css classes. So I end up with something like this: <p> <label>Current Weight</label><input type=Number...><span class="customCss">Kg (or text I enter</span> </p> So is there anyway to accomplish this inside the model class? I know I could do this with javascript or by looping through the fields in the template instead of using the form.as_p tag. But I want to reuse this so it's cleanest if I can create a method to output … -
Django-filter with DRF - How to do 'and' when applying multiple values with the same lookup?
This is a slightly simplified example of the filterset I'm using, which I'm using with the DjangoFilterBackend for Django Rest Framework. I'd like to be able to send a request to /api/bookmarks/?title__contains=word1&title__contains=word2 and have results returned that contain both words, but currently it ignores the first parameter and only filters for word2. Any help would be very appreciated! class BookmarkFilter(django_filters.FilterSet): class Meta: model = Bookmark fields = { 'title': ['startswith', 'endswith', 'contains', 'exact', 'istartswith', 'iendswith', 'icontains', 'iexact'], } -
KeyError overriding django ModelAdmin.get_readonly_fields()
I'm trying to override the get_readonly_fields() method in my django ModelAdmin. If a certain condition exists, I want to return nearly all my fields as readonly_fields. Here's how that looks: from django.contrib import admin from cms.admin.placeholderadmin import PlaceholderAdminMixin from .models import (Story, StoryCategory, AVAILABLE_STORY, GLOBAL_STORY) RESTRICTED_PUB_FIELDS = ('pub_date',) RESTRICTED_FIELDS = ( 'global_status', 'title', 'byline', 'byline_headshot', 'featured_image', 'use_featured_image_on_detail_page', 'outside_article_box', 'has_detail_page', 'landing_page_link', 'link_text', 'global_categories', 'initiatives_tags', 'stat_text_before', 'stat_number', 'stat_text_after', 'offices', 'rural_liscs', ) class StoryAdmin(PlaceholderAdminMixin, admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if obj and obj.global_status == AVAILABLE_STORY: fields = self.readonly_fields + \ RESTRICTED_PUB_FIELDS + RESTRICTED_FIELDS return fields return self.readonly_fields def change_view(self, request, object_id, extra_context=None): if '_saveasnew' in request.POST: if request.POST['global_status'] == AVAILABLE_STORY: request.POST['global_status'] = GLOBAL_STORY return super(StoryAdmin, self).change_view( request, object_id, extra_context=extra_context ) fieldsets = ( ('Publishing Information', { 'fields': ( 'status', RESTRICTED_PUB_FIELDS, 'expire_date', 'slug' ) }), (None, {'fields': ( RESTRICTED_FIELDS, 'excerpt', 'local_categories', 'is_featured', )}), ) [...] admin.site.register(Story, StoryAdmin) But when the condition in get_readonly_fields() is true, a KeyError is raised -- not on the Story object but on StoryForm. I know Django dynamically creates a ModelForm for me so I assume I'm passing something around incorrectly at some point, but I can't see where. I'm trying to do almost verbatim the same thing as in … -
Integer error transferring from MySQL to PostgreSQL
I decided to move Django project in development from using MySQl to PostgreSQL. Previously everything was fine, but after first migration with PorstgreSQl I am getting this error: File "/Users/TheKotik/djboy/denv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column "how_much_new_notifications" cannot be cast automatically to type integer HINT: You might need to specify "USING how_much_new_notifications::integer". Models.py: how_many_new_notifications = models.IntegerField(null=True,default=0) I tried to run psql and insert what "I might need to specify" but it doesn't help. What should I do and what is the reason of error? -
Display dynamic results in website
I'm developing a website for a travel search engine and I want to show the results similarly with a similar concept than Hipmunk. Details are: The website is being developed with Django. Content is dynamic (results depends on each search) Bars are placed along a timeline, so positioning them would depend on the time. The bars used in the example seem too simple, so I might try something a bit more elaborated, such as a mix of circles, bars and icons, similarly to Rome2rio, but horizontally. Time filter is applied at the timeline, so depending on the user interaction with the timeline, results shown would change (see hipmunk image above). I guess the normal approach would be using javascript, but as I have no background, I was wondering if there are any alternatives or existing packages that would allow me to do this. It would be ideal if there was some module in Python, as this is my background. I heard about bokeh, but it seems focused on scientific data and charts. I also read somewhere about Skulpt, but it seems not mature yet. Is there a way to create such a thing with Python or am I condemned to … -
Interactive networkx Graph Webpage in Python
I'm building an app in Python which I would like to make available on the web. On the server side I will have a networkx graph of nodes and links, each of which will have their own pictoral representation. I'm looking for a way to represent this graph on my webpage, and looking for something that will be interactive and aesthetically pleasing. The interactivity required is that I need the user to be able to interact with the graph in an intuitive way, adding nodes and links, getting info about existing nodes, etc. It would conceptually be somewhat similar to mohiomap in web interface. I've looked into django and flask, but I don't understand if this could be accomplished using these libraries. It seems like fairly graphic oriented content, more like a game than anything. I was looking at pygame and thought that using pyjsdl this might be more appropriate. My question is, is the above something that could be achieved with python. What would be the preferred language/library? I've looked at django and flask, but am wondering if pyglet or pygame may be actually more appropriate for this task. I mainly want to avoid going to deep into anything … -
App Design in Django
I have a general algorithm design question. I am creating a Django app that will connect to an API, but I won't be storing these results (at least not at first). After I retrieve the data from the API I manipulate it accordingly and have already created a class with numerous methods to do this. Should the programming logic for this be performed in the model or the view for the Django framework? Is one more sustainable than the other (e.g. in a few months I decide to store the information). Also, is it best to encapsulate my class in its own file, and them import into the model/view? Thanks! Rob -
Passing additional attributes all the way thru to nested serializers
I've been having issues passing additional attributes thru using Django Rest Framework with nested serializers. I've created a Document model that has a ForeignKey owner/creator relationship, and several other ForeignKey related models. Some of those other model have an owner/creator ForeignKey associated as well. class Document(models.Model): owner = models.ForeignKey('auth.User',related_name='document') candidate = models.ForeignKey( Candidate, on_delete=models.CASCADE, blank=True, null=True, ) class Candidate(models.Model): owner = models.ForeignKey('auth.User', related_name='candidates') first_name = models.CharField(max_length=30, blank=True, null=True) When saving down the Document model with a nested serializer and a custom create() method, I can pass all fields down, however, the nested models don't seem to be able to pick up the Owner field, regardless of how I pass it in. Creating a Candidate alone is fine. class CandidateSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Candidate fields = ( 'pk', 'first_name', 'owner', ) class DocumentSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') candidate = CandidateSerializer(required=True) class Meta: model = Document fields = ( 'owner', 'candidate', ) def create(self, validated_data): candidate_data = validated_data.pop('candidate') document = Document.objects.create(**validated_data) Candidate.objects.create(**candidate_data) With DocumentSerializer set up like this, I get errors like this while trying to do a POST to Document with nested fields. IntegrityError: NOT NULL constraint failed: dossier_candidate.owner_id When I modify the DocumentSerializer.create() method to try to … -
Pytest support for unittest.installHandler
I'm looking at switching our Django project's tests to use Pytest and pytest-django. The problem I've run into is that I can no longer cleanly halt a test run in the middle. The default Django test runner has nice support for this: If you press Ctrl-C while the tests are running, the test runner will wait for the currently running test to complete and then exit gracefully. During a graceful exit the test runner will output details of any test failures, report on how many tests were run and how many errors and failures were encountered, and destroy any test databases as usual. Thus pressing Ctrl-C can be very useful if you forget to pass the --failfast option, notice that some tests are unexpectedly failing and want to get details on the failures without waiting for the full test run to complete. If you do not want to wait for the currently running test to finish, you can press Ctrl-C a second time and the test run will halt immediately, but not gracefully. No details of the tests run before the interruption will be reported, and any test databases created by the run will not be destroyed. Is there any … -
Django admin. Limit choices of many to many field
I have a Many to Many field. I'd like to limit the choices the admin shows in its M2M widget. I have a model like this: class A(models.Model): b_field = models.ManyToManyField(B) class B(models.Model): available = models.BooleanField() How do I limit the B objects shown in the widget only to those who have available = True? -
Error in adding a coloumn in model of django after migration also, the database had some values before
In django i had a Post model and using xamp phpmyadmin i had some entries it then one day i added a column Post_filter_keywords in this model then after migration i got this error given below -> THis is the model . class Post(models.Model): Post_id = models.AutoField(primary_key=True) Post_type = models.ForeignKey(Type, related_name='posttype' ,default='1', editable=True) Post_time = models.CharField(max_length=100,default=currentTimestamp, editable=True) Post_person1=models.ForeignKey(Person, related_name='person1' ,default='1', editable=True) Post_person2=models.ForeignKey(Person, related_name='person2' ,default='1', editable=True) # Postovo_hot=models.CharField(max_length=100,default='False', editable=True) Post_trending=models.CharField(max_length=100,default='False', editable=True) Post_person1_likes=models.CharField(max_length=100,default='0', editable=True) Post_person2_likes=models.CharField(max_length=100,default='0', editable=True) Post_filter_keywords=models.CharField(max_length=100,default='0', editable=True) -
Django Form Validation Based on Distant Related Model
I am still pretty inexperienced with Django but I am stuck on this one issue. I was given an almost-finished project where parents could fill out assessments on their children and then researchers could collect and store this data using Django and Postgresql. There are several related models located in two different apps, which all relate to one other. An "instrument" (type of test) can have multiple studies which in turn can have multiple participants. I made a badly drawn image to describe what I mean. There is one form, BackgroundForm, which collects demographic information (age, birth weight, etc). This data is then stored in the model, BackgroundInfo with the participant's administration ID. I am having issues making the form validation more flexible. Certain instruments (tests) are for specific ages and I am not sure how to get this information all the way to BackgroundForm validation since this is located several relationships away. Is there a way to enable form validation that validates depending on the attributes of a model located several relationships away? Map of Django site cdi_forms/forms.py class BackgroundForm(BetterModelForm): age = forms.IntegerField() sex = forms.ChoiceField(choices=(('M', 'Male'), ('F', 'Female'), ('O', 'Other')), widget=forms.RadioSelect) def clean(self): cleaned_data = super(BackgroundForm, self).clean() if … -
Adding/deleting fields in the same ModelForm django
I have little experience in django so I would really appreciate your help! In general, I have created a ModelForm which depending on the users who is logged in, he changes some values in the field. So consider that this form is being edited about 5 times by 5 different users. I would like to show a specific field in the template (and view) only when the third user is logged in. My model is : class Task(models.Model): Taskdetails = models.CharField(max_length=500, null=True) asset = models.ForeignKey('Asset', null=True) failure = models.ForeignKey('Failure', null=True) cause = models.ForeignKey('Cause', null=True) Created_task_date = models.DateTimeField(default=timezone.now, null=True) employee = models.ForeignKey("auth.User", null = True) and also i have created this ModelForm class Meta: model = Task fields = ('Taskdetails', 'asset', 'failure', ,'employee','cause',) Also I have 5 edititions of the TaskForm in which is user edits something. The thing I am trying to do is to show the cause field only in the third form. I tried to exclude the value but nothing apperas. If i include the field cause (just like above), I must "pass" it in the template in order to be edited from the first user (otherwise the task_form is not saved) I hope I became clear. I … -
Input current datetime in local time by default in django model
I have created a model in Django in which I want to input creation time by default in local time. I have set the following in settings.py: TIME_ZONE = 'Asia/Kolkata' USE_TZ = True I have tried the following: import pytz status_timezone = pytz.timezone('Etc/UTC') class Status(models.Model): status = models.IntegerField(default=0, blank=True) active = models.IntegerField(default=1, blank=True) creation_date = models.DateTimeField(default=status_timezone.localize(datetime.now())) This always gives the same datetime for all entries (time of model initialization class Status(models.Model): status = models.IntegerField(default=0, blank=True) active = models.IntegerField(default=1, blank=True) creation_date = models.DateTimeField(default=datetime.now) This gives datetime in UTC Could someone please tell how to input datetime in IST by default? Thanks in advance -
Django QuerySet class attributes
This question get class name for empty queryset in django exemplifies that a QuerySet in Django has the attribute model The QuerySet API documentation lists the methods, but I couldn't find a place where it lists its attributes Is there a way to retrieve them, or I am missing where they are at the documentation?