Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deserialize json data in django
def save_embed(request): if request.method == "POST": form = SubmitEmbed( request.POST ) if form.is_valid( ): url = form.cleaned_data['url'] r = requests.get( 'http://cubito.co.in/cab-location-assignment/?trip_id=M-1452944200-01-367' + url ) json = r.json( ) serializer = EmbedSerializer( data=json ) -
handsontable not working on django project
I have downloaded handsontable using bower and I tried it in plain HTML and it works but when i try it with django app it doesn't work. Can anyone give me a way to setup handsontable in django. -
Can't get Django Rest Framework GET vs POST structure to differ
I have a model that looks like this: class Pet(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=200) primary_contact = models.ForeignKey(Person) My Serializer looks like this: class PetSerializer(serializers.ModelSerializer): class Meta: model = Pet fields = ('id', 'name', 'description', 'primary_contact') My Viewset: class PetViewSet(viewsets.ModelViewSet): queryset = Pet.objects.all() serializer_class = PetSerializer My Problem: If I do a "GET" at my endpoint, my result looks like this: [ { "id": 1, "name": "Ripley", "description": "Black / Tan Yorkie", "primary_contact": 1 } ] The primary_contact only brings back the ID of the Person object. This is exactly how I want the POSTing structure to look like. When I POST, I only want to supply the ID of the Person object. However, when I GET, I want the content to look like this: [ { "id": 1, "name": "Ripley", "description": "Black / Tan Yorkie", "primary_contact": { "id": 1, "first_name": "MyFistName", "last_name": "MyLastName", "phone": "312-xxx-xxxx", "email": "aarsan@abc123.com" } } ] I can get the above structure by setting depth=2 in my serializer but then if I try to POST, it tries to create the primary_contact, which I not want to do since it already exists. The workaround I've been using is creating a different endpoint for POST and … -
django Field names must not end with an underscore. Field names must not contain __
I am new to django. While referring to django check framework documentation, I came across the following points :- Field names must not end with an underscore. fields.E002: Field names must not contain "__". I am not able to know, why such restriction exists. Moreover, the django documentation is not clear about such restriction. I have googled about the same, but could not get any good answer for the same. Thanks in advance. -
Django Rest Framework sets related serializer field to null on save for no reason
Here are the models. class Dealer(models.Model): first_name = models.CharField(max_length=255) ... class Form(models.Model): dealer = models.ForeignKey(Dealer, blank=True, null=True) ... Here are the serializers. class FormShortSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Form fields = ('url',) class DealerSerializer(serializers.HyperlinkedModelSerializer): forms = FormShortSerializer(source='form_set', many=True) class Meta: model = Dealer Here are the viewsets. class DealerViewSet(viewsets.ModelViewSet): queryset = Dealer.objects.all() serializer_class = DealerSerializer class FormViewSet(viewsets.ModelViewSet): queryset = Form.objects.all() serializer_class = FormSerializer So, the API response for Dealer URL is this. { "url": "http://localhost:8000/rest-api/dealer/1/", "forms": [ { "url": "http://localhost:8000/rest-api/form/1/" }, { "url": "http://localhost:8000/rest-api/form/2/" } ], "first_name": "First Name" } But, when I do PUT or PATCH to this URL, say, updating the first_name to something else, for some reason DRF sets dealer field on all forms to null, and the response looks like this. { "url": "http://localhost:8000/rest-api/dealer/1/", "forms": [], # Forms are empty. "first_name": "Changed Name" . # Name changed. } Any idea why guys? None of the models overload save methods or doing any magic behind the scenes. Only Meta class __unicode__ methods are defined there, but I think it's irrelevant here, so I haven't included it in the code. Thanks ahead. -
Using PasswordReset in Django rest_auth without adding password_reset_confirm url into urls.py
I am buiding an Django web app and using PasswordReset of rest_auth. I have to add this url in my top urls.py so that PasswordReset work well. url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', TemplateView.as_view(template_name="password_reset_confirm.html"), name='password_reset_confirm'), Without above code, I will face to an error: Reverse for 'password_reset_confirm' with arguments '()' and keyword arguments '{'uidb64': b'Nw', 'token': '4gi-bcaec8580adf86408ab2'}' not found. 0 pattern(s) tried: [] But I don't want to use that code in my urls.py. Is there any way to do ? -
django model building table name wrong
I have a postgresql RDS instance on aws free tier with my ec2 instance. I should have used EB, but didn't really know about it until I had a lot built out and am not excited about starting over on a new ami. I am trying to build my first interaction with the db, have a table there called server_config, created as: SELECT * FROM server_configs; DROP TABLE SERVER_CONFIGS; CREATE TABLE SERVER_CONFIGS ( config_key VARCHAR(63) NOT NULL, config_value VARCHAR(63) NOT NULL, UNIQUE (config_key) ); INSERT INTO SERVER_CONFIGS (config_key,config_value) VALUES ('ClientMustVerify','TRUE'); INSERT INTO SERVER_CONFIGS (config_key,config_value) VALUES ('Auditing','FALSE'); COMMIT; and in my django app, I have: models.py: from django.db import models class serverConfig(models.Model): config_key = models.CharField(max_length=63) config_value = models.CharField(max_length=63) excerpt of view.py: from limbo.models import serverConfig def editServer(request): myConfigs = serverConfig.objects.all() configHtml = "" # for item in myConfigs #serverConfig.objects.values() # configHtml += item.config_key + "\t" + item.config_value + "\n" if request.method == 'POST': form = serverForm(request.POST) if form.is_valid(): integer = form.cleaned_data['int_field'] request.session['integer'] = integer # call out to limboLogic.py to update values, add them to the session message = 'The value \'' + str(integer) + '\' has been updated.' return render(request, 'limboHtml/ServerConfiguration.html', {'form': form, 'SubmitMessage': message, 'CurrentConfigs': myConfigs}) else: message = … -
django admin truncate text in list_display
Need to trunate text in admin list_display Have the following in admin model but still shows full text. from django.template.defaultfilters import truncatewords 15 16 17 18 def get_description(self, obj): 19 20 return truncatewords(obj.description, 10) 21 get_description.short_description = "description" 22 23 24 25 class DieTaskAdmin(admin.ModelAdmin): 26 27 28 list_display =['severity','priority', 'subject', 'status','created',get_description.short_description'] 29 30 admin.site.register(DieTask, DieTaskAdmin) i.e original text of description field contains more than 255 char. I like to only display the first 10 char plus ... -
Issues while running Django web app and wordpress on the same apache server
I am working on building a wordpress blog for my website. I am deploying the whole application on an AWS instance. I want to see my website when i am redirecting to the PublicDNS of my instance and when i use PublicDNS/blog i want to see my blog. I have my web app developed using python. I am trying to setup a reverse proxy to achieve this. Also, I followed the link below to set up mod_wsgi https://www.sitepoint.com/deploying-a-django-app-with-mod_wsgi-on-ubuntu-14-04/ what I did was this sudo vi /etc/apache2/sites-enabled/000-default.conf <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin ubuntu@localhost # DocumentRoot /home/ubuntu/myproject DocumentRoot /var/www/html/ # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # … -
How to setup database routers (db per app) in django using only django-cassandra-engine?
I have tried setting up the routers in django but for some reason both of my apps use only one DB out of two. I am using the django-cassandra-driver v1.0 (latest) with django v1.10.2 and cassandra v3.9. I have setup: django routers.py file as described in this post and put it under mainsite/mainsite directory setup two cassandra connections(each to different keyspace) as described in django-cassandra-engine documentation Is database routing not possible using django-cassandra-engine? or am I missing something here? -
How to store singular dynamic values in a Django web application?
In Django when I want to store models like users, places and so on I may use an SQL database, but when I want to store a particular value (only one) I have no idea what to use. So, I'm doing a website where there is some information that changes monthly. Giving one example: <meta name="description" content="This team is in {{ ranking }} in the world ranking"> I'll need to change that value, ideally from Django Admin monthly and a Model with one object seems too much (not too much work but simply too much). I started looking at NoSQL and from this question I'm inclined to use Redis or a similar key-value DB. Is it the right approach or am I completely off track? -
Django python querysets order numbers properly
Hello guys I having some troubles trying to order numbers I hope you can help me because I do not know the way to do it properly. I think it suppose to work, but I can not achieve it works. I have a data base with this numbers. "001","009","010","099","100","999","1000","1001","1009","1099","10000" This is the order in the data base. I'm trying to order them because I need that order, from 001 to infinite. I'm trying with this: hello = Database.objects.all().order_by('noclient') What I got is this: 001 009 010 099 100 1000 10000 1001 1009 1099 999 Even if I change to this: hello = Database.objects.all().order_by('-noclient') or using .reverse, I got: 999 1099 1009 1001 10000 1000 100 099 010 009 001 Wich is not correct, how can I get all those number in order ? I'll really appreciate a hand! Thank you guys! -
When a leave a blank form i get an ValueError
i have this view: class LoginView(View): def get(self, request, *args, **kwargs): # create a new form instance form = forms.LoginForm() return render(request, "login.html", {'form': form}) def post(self, request, *args, **kwargs): # create a form instance and populate it with data from the request form = forms.LoginForm(request.POST) # check whether is valid if form.is_valid(): form.save() user_name = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=user_name, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/boletim/') else: return HttpResponseRedirect('/login/') else: return HttpResponseRedirect('/login/') so every time i don't put text on the form and push the submit button, i get this error: ValueError at /login/ The view login.views.LoginView didn't return an HttpResponse object. It returned None instead. -
Django aggregate filters
I have 3 models similar to the below, and I am trying to get the latest sale date for my items in a single query, which is definitely possible using SQL, but I am trying to use the built in Django functionality: class Item(models.Model): name = models.CharField() ... class InventoryEntry(models.Model): delta = models.IntegerField() item = models.ForeignKey("Item") receipt = models.ForeignKey("Receipt", null=True) created = models.DateTimeField(default=timezone.now) ... class Receipt(models.Model): amt = models.IntegerField() ... What I am trying to do is query my items and annotate the last time a sale was made on them. The InventoryEntry model can be queried for whether or not an entry was a sale based on the existence of a receipt (inventory can also be adjusted because of an order, or being stolen, etc, and I am only interested in the most recent sale). My query right now looks something like this, which currently just gets the latest of ANY inventory entry. I want to filter the annotation to only return the max value of created when receipt__isnull=False on the InventoryEntry: Item.objects.filter(**item_qs_kwargs).annotate(latest_sale_date=Max('inventoryentry_set__created')) I attempted to use the When query expression but it did not work as intended, so perhaps I misused it. Any insight would be appreciated -
Django manually ImageField saving
I have a problem with my own save method in Django. I have a model: class myModel(models.Model): video_url = models.URLField() thumbnail = models.ImageFiled(upload_to='thumbnails/', null=True, blank=True) and have two methods in this model. One for generate thumbnail from models's url. it looks something like this: def generate_thumbnail(self): random_code = generate_super_random_code() # returning code like: ASD98ASD89 save_location = 'my/location'+random_code+'.jpg' clip = VideoFileClip(self.url) clip.save_frame(save_location, t=5) bg = Image.open(save_location) arrow = Image.open(path_to_arrow_png) bg.paste(... I paste arrow on my bg image) #and save to the same location bg.save(save_location) # so now I have nice thumbnail in my save location and now I want to assign this file to self.thumbnail # when I do this, nothing happen self.thumbnail = bg and osave method def save(self, *args, **kwargs): super(myModel, self).save(*args, **kwargs) if not self.pk: self.generate_thumbnail() How can I do this? Thanks -
Django: Click an image and pass the object into another directory
Description: To begin with I am basically trying to create profile page for an image and I want to click an image and post all the details about that image on another page. views.py def photo(request, photo_id): if request.user.is_authenticated(): return HttpResponse(photo_id) return HttpResponse("blahblah") urls.py url(r'^(?P<photo_id>\d+)/$', views.photo, name = 'photo_detail'), home.html <div class="gallery"> <a href="{% url 'photo_detail' photo.id %}"> <img src="{{ photo.image.url }}" height="300" alt="{{ photo.name }}"> </a> </div> -
Render cell color for max value in all columns (django)
django-tables2 has a render_foo method that can be defined for each individual column in the table. I wish to avoid a lot of repetitive coding defining a function for each and every column in every table I want to format cells... Does this package have some way to render_AllColumns? Anything that does this: class simpleTable(tables.Table): def render_AllColumns(self, value, column): if value == max(column): #set column attributes else: #set other column attributes return value I posted about the single column method here -
How do I get the absolute path from the settings file in Django
I have a simple question: I have read a lot of answers in this forum on how to get a project's root directory. However I'm running into a problem: the path is just . For example: from django.conf import settings path = settings.BASE_DIR + /somefolder/ the resulting value for path is just . I need the full path in order to save to that folder. -
Datatables Column Search with Select
Im trying to implement the Individual column sort django. I am able to convert the table into a datatable and the search bar that is displayed works perfectly in searching the table. I modified the code shown in the link mainly to have only only 1 or 2 columns searched via select However When I select an option form the dropdown the table displays no matching records found , when clearly data matching the criteria exists. Any help in figuring out the issue will be greatly appreciated. Code is pasted below: $(document).ready(function () { $('#audience-list').DataTable({ initComplete: function () { this.api().columns([1]).every(function () { var column = this; var select = $('<select><option value=""></option></select>') .appendTo($("#sort")) .on('change', function () { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search(val ? '^' + val + '$' : '', true, false) .draw(); }); column.data().unique().sort().each(function (d, j) { select.append('<option value="' + d + '">' + d + '</option>') }); }); } }); }); -
Uploaded Images need server reload
I am new at django. I upload images and it was working well when in development. I use pythonanywhere for deploy my code. The problem is I can upload image on admin but can't display unless reload the server. I can show some code snippets you want. I have no idea what the problem is -
Celery task keeps repeating old way after changing CELERYBEAT_SCHEDULE and 'celery purge'
I'm new in Celery. I've finally make it work but there is a problem that even if I do celery purge, one task keeps repeating each 10 seconds. This is my CELERYBEAT_SCHEDULE: At first, there was 'schedule': timedelta(seconds=10) which worked correctly. I've decided to change the schedule of this task to run everyday at 22:30. The problem is that even after celery purge, this tasks is being executed every 10 seconds. As you can see, the timedelta(seconds=10) is commented and there is new schedule. CELERYBEAT_SCHEDULE = { 'everyday-at-01-00-am': { 'task': 'dolava_app.tasks.check_reservation_alerts', 'schedule': crontab(hour=22, minute=40), # 'schedule': timedelta(seconds=10) }, } Do you know what to do? -
Django- how to establish relationships between different apps?
(Keep in mind that still a begginer to Django) I've been creating my first Django App for a while now. In it, I have a model that represents a geographical area. This means that each instance of that model has the purpose of representing a different area on the map. This app is OK. I've added a 2nd app, a reusable app, to my project, called django-forms-builder, that can be found here: https://github.com/stephenmcd/django-forms-builder This app allows me to create custom forms, in the Django Admin, that work fine. But they are 'stand-alone'/'separated' from anything from my own app. I would like to establish some connection, from these forms from the 2nd app, to the area model from my own app, so that, as a result, specific forms can be associated to specific areas on the map. This is really confusing to me, as I've only ever used a single app. I've read the models.py file in the 'django-forms-builder' app, and they are abstract, so it seems establishing foreign key relationships between models is not doable here, therefore I feel completely lost with no clues to follow on. So my question is how to establish a relationship between different Django apps? … -
Using Django rendered lists in Javascript on the rendered html page
I am working on a django app where I made a custom view that passes a queryset of elements to the rendered html page. In the html page I want to have an option to select a word from a select list and If the selected word matches any element from the list I got from view, I should need to display it. I tried using Java script to read these elements into array and then use that array on chnage in select box. but it didnt work as I required. Here is what I have done so far. View: from .models import words as m def test(request): words = m.objects.all() context = Context({ 'words': words, }) return render(request, 'newpage.html',context) newpage.html: <select id="sel" onChange="func();"> <option value="" selected="selected">--none--</option> <option value="word1">word1</option> .... <option value="wordn">wordn</option> </select> <script> function func() { var e = document.getElementById("sel"); var str = e.options[e.selectedIndex].value; '{% for each in words %}' var a="{{ each.word }}"; if(strUser===a) { console.log('{{each.word }}')//or passing it to a div in html } {% endfor %} } </script> what I require is If the selected element is "word1" and if the queryset "words" has "word1" in it, it should display the word in the page in … -
overriding modelform choices with __init__
I've been trying to get the fields for a choice to change based on what i give it in my view and i get name 'self' is not defined here is my view.py def CarOwnerSearch(request): if request.user.is_authenticated(): form = carOwnerForm.__init__(self,'B','None','C') return render (request,'carmanager/CarOwnerSearch.html', {'form': form}) OK ive got a modelform class carOwnerForm(forms.ModelForm): first_name = forms.charfield() last_name = forms.charfield() def __init__(self, a,b,c): super(carOwnerForm,self).__init(a,b,c) self.field["ownership_Type"].choice = [a,b,c] class Meta: model = CarOwner fields = ['ownership_type','CarModel'] and this is my model.py class CarOwner(models.Model): ownershipTpes_choices = ( ('R','Rented'),('L','Leased'),('O','Owned')) ownership_Type = models.CharField(max_length=1, choices=ownershipTypeChoices) -
Why do Django generic views call wrong function?
I'm trying to use generic views in Django because it's suppose to be better. This is the second time I've had this issue, and I don't think its just me. Basically, when the following code is run the incorrect "def form_valid" is run. views.py class DemoUserEditView(UpdateView): """Allow view and update of basic user data. In practice this view edits a model, and that model is the DemoUser object itself, specifically the names that a user has. The key to updating an existing model, as compared to creating a model (i.e. adding a new row to a database) by using the Django generic view ``UpdateView``, specifically the ``get_object`` method. """ form_class = DemoUserEditForm template_name = "auth/profile.html" #success_url = '/email-sent/' view_name = 'account_profile' success_url = reverse_lazy(view_name) #print (request.user) #print (request.user.profile) def get_object(self): return self.request.user def form_valid(self, form): # TODO: not sure how to enforce *minimum* length of a field. #print "form valid..." #print "save to user:", self.request.user, form.cleaned_data form.save() messages.add_message(self.request, messages.INFO, 'User profile updated') return super(DemoUserEditView, self).form_valid(form) account_profile = login_required(DemoUserEditView.as_view()) #attempt at changing user profile info. class DemoUserPicEditView(UpdateView): form_class = DemoUserPicEditForm template_name = "auth/profile.html" #success_url = '/email-sent/' view_name = 'account_picture' success_url = reverse_lazy(view_name) def get_object(self): return self.request.user.profile def form_valid(self, form): # TODO: …