Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django FullCalendar Make Event Persist
I am using the Full Calendar Js library to create a scheduling functionality. I used the select method which allows the user to open up a modal form upon clicking on a date(s). My code manages to save all newly added events onto the database using some sweet Ajax. $.ajax({ type:'POST', url:'createEvent/', data:{ name: name, start: start.format("YYYY-MM-DD"), end: end.format("YYYY-MM-DD"), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, sucess:function(){ alert("Event added") } }); Then I used the loading method to print out the corresponding events using some django magic: $('#calendar').fullCalendar({ loading: function(bool){ if (bool){ {% for object in objects %} var name = "{{ object.name }}"; var start = "{{ object.start }}"; var end = "{{ object.end }}"; var event={id:1 , title: name, start: start+"T14:30", end:end,}; $('#calendar').fullCalendar( 'renderEvent', event, true); {% endfor %} } }, }); Then if I were to refresh the page, logout then log in, the events will persist! However, I discovered a bug. As you may know, the full-calendar comes equipped with buttons to traverse through the months. Unfortunately, whenever this button is clicked, it acts like an refresh which causes the calendar to render duplicate events. As you may have guessed, the for loop inside the loading method gets run every time … -
How to create a User model object using Django REST framework?
I'm using the shell to make this happen: serializer = UserSerializer(data={'first_name':'brody', 'username':'brodyboy'}) serializer.is_valid() // returns True serializer.save() // I save it, assuming it should create a new User object. When I check to see the User objects I've made: User.objects.all() // <QuerySet [ ]> -- returns nothing. models.py: class User(models.Model): first_name = models.CharField(max_length=20) username = models.CharField(primary_key=True, max_length=20) age = models.IntegerField(default=19) def __str__(self): return self.first_name Serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name', 'username') def create(self, validated_data): return User.objects.create(**validated_data) -
Is it possible to have the same model for its own field in Django?
I'm making an app where I have City model. I need to add nearby_cities field. City can have multiple nearby cities. How would I make such field? Also what would be the best approach to my problem? Should I have a NearbyCity model? Thanx -
Ask REST API for specific data and if satisfied with answer open django app url
What I want to achieve may be a bit of an overkill, but I want to check if that's even possible. I'm a newbie at angularjs. How can I use angular, so: Sends GET to REST API (let's say /product/) If it receives specific value (let's say x > 0) it redirects to django app url (let's say /add/), Else it may generate error (let's say ). -
One form across two pages django
I want to create a form that does the following: the user specifies the number of questions that they want to ask and then on the next page, the user is able to fill out the relevant details pertaining to the number of questions that they to ask. I was wondering if there is a simple way to do this using django forms? My approach is as follows: I use one form to record the number of questions that the user wants to ask with a general description, then when the user clicks submit/next, the next view would create a form with those number of questions; however, I'm running into a complication when trying to use this method. I want to link the first form to the second form, but not sure how to because I can't preserve any information in the view from each call. Is there a better way of going about this problem? -
Django Product Gallery
I create shop for train Django. I have problem with product gallery. I want create somethink like this And in do it. <img src="{{ product.image_url|default_if_none:'#' }}"> but I have only one image How can I add "product gallery" ? I must add ne field on Product models to storage photos ? -
ModelChoiceField with values of object
I have a problem with ModelChoiceField in my formset. First my ModelChoiceField looks like this: age = forms.ModelChoiceField(label='Age', widget=forms.Select(attrs={'class': 'form-control'}), queryset=BirdAge.objects.values_list('age_title')) It shows age title in HTML select and it looks ok, but validation of this field was False. Then I realized that Django want relation between this form and the second one. So I put only objects to queryset, like this: age = forms.ModelChoiceField(label='Age', widget=forms.Select(attrs={'class': 'form-control'}), queryset=BirdAge.objects.all()) Validation is True now, but I have a problem to get age_title in option values in HTML select. I think it must be easy but I can't figure out how to make it. I found this in documentation: from django.forms import ModelChoiceField class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "My Object #%i" % obj.id ModelChoiceField in Django documentation If I will use __str__ method I cant define option values for other ModelChoiceFields in my form. So I expect I should use subclass of ModelChoiceField and override label_from_instance for every ModelChoiceField but how can I use it for my ModelChoiceField. This is my last trial: class BirdAgeModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.age_title class BirdAgeFilter(forms.Form): age_choices = [(i['age_title'], i['age_title']) for i in BirdAge.objects.values('age_title')] age_title = forms.ChoiceField(choices=age_choices) class ObservationForm(forms.ModelForm): # ...other fields and ModelChoiceFields age = … -
Socket keeps disconnecting and reconnecting Channels/Django
So when I access the "/login/index/12/" page the socket keeps disconnecting and reconnecting as shown below. I am using channels with django [2017/02/05 19:46:19] WebSocket CONNECT /login/index/12/stream/ [127.0.0.1:47876] [2017/02/05 19:46:19] WebSocket DISCONNECT /login/index/12/stream/ [127.0.0.1:47876] [2017/02/05 19:46:20] WebSocket HANDSHAKING /login/index/12/stream/ [127.0.0.1:47878] [2017/02/05 19:46:20] WebSocket CONNECT /login/index/12/stream/ [127.0.0.1:47878] [2017/02/05 19:46:20] WebSocket DISCONNECT /login/index/12/stream/ [127.0.0.1:47878] I am trying to figure out what would be causing this problem. I'd upload code but I'm not sure which files are relevant -
Sort table listings first by Date then by priority (Django)
I am building a tasker application where items are sorted first by Date/Time due then each section of items due on the same date are re-sorted by priority. I know how to sort items by date-time, but how do I go about re-sorting each subsection again. Priority is an integer from 0-9. Sorry that I don't have any code to submit, I am still working through the design to how I will code my models. I couldn't find any items related on google (or I don't know how to word the query) Thank you! -
Django fails to redirect properly
I am new to Django, and working on a URL shortener project like bitly. I am running into issues at the moment when trying to click the link created in the success.html template, it does not redirect, and appends the path + short_url + url: DEBUG-URLRedirectView::get(): obj.url: www.google.com [05/Feb/2017 19:02:27] "GET /gesw1m/ HTTP/1.1" 302 0 Not Found: /gesw1m/www.google.com [05/Feb/2017 19:02:27] "GET /gesw1m/www.google.com HTTP/1.1" 404 2216 Here is the project tree: -src_shrtnr manage.py -shrtnr hosts.py settings.py urls.py -hostconf urls.py views.py -shortener models.py views.py -templates -shortener already-exist.html home.html success.html -analytics ... Here is the success.html template and image: <div style='align-text: center; width: 800px; margin: 0 auto;'> <h1>Created!</h1> <p>{{ object.url }}</p> <p>Count: {{ object.clickevent.count }}</p> <p><a href='{{ object.get_short_url }}'>{{ object.get_short_url }}</a></p> <a href='/'>+New</a> </div> Here is the shortener models.py file: class ShrtnrURL(models.Model): url = models.CharField(max_length=220, validators=[validate_url, validate_dot_com]) shortcode = models.CharField(max_length=SHORTCODE_MAX, unique=True, blank=True) ... def get_short_url(self): url_path = reverse('scode', kwargs={'shortcode': self.shortcode}, host='www', scheme='http') print('DEBUG-ShrtnrURL::get_short_url(), url_path: ', url_path) return url_path Here is the shortener views.py relevant view: class URLRedirectView(View): qs = ShrtnrURL.objects.filter(shortcode__iexact=shortcode) if qs.count() != 1 and not qs.exists(): raise Http404 obj = qs.first() print('DEBUG-URLRedirectView::get(): obj.url: ',ClickEvent.objects.create_event(obj), obj.url) return HttpResponseRedirect(obj.url) Here is hostconf urls.py: from .views import wildcard_redirect urlpatterns = [ url(r'^(?P<path>.*)', wildcard_redirect), ] Here … -
Filter related model django
I am building the example django polls application. I want to exclude all polls, which have no choices. For that I have to access the related choices objects: return Question.objects.filter( pub_date__lte=timezone.now() ).exclude( choice_set__count=0 ).order_by('-pub_date')[:5] But this query results in a field error: Cannot resolve keyword 'choice_set' into field. Choices are: choice, id, pub_date, question_text How can I query related models from the query? -
Having trouble accessing my API hosted in Cloudflare but not Python Dev Shell
So I have a website, lets call it microphone.com. This website has a few apis in it under microphone.com/api1, microphone.com/api2. I'm using ajax to send a request to the APIs with Authorization: JWT as the header. I've set my settings to accept JWT tokens as authentication for API. Everything works well for when I test it with a virtual python server through my aws (python manage.py runserver 0.0.0.0:8000) But when I host the actual site live through Cloudflare's DNS, I get a 401 not authorized whenever I try to access the API. (I can login using session based [meaning going to the APIview and then logging in with the credentials to access API] fine, but when I try to access it remotely through either an ajax request (through microphone.com) or use 'curl -H "Authorization: JWT < token >" microphone.com/api' from my local computer's terminal, I get a 401 authentication credentials were not provided'. Is this because of Cloudflare's security or something? How do I bypass this? I notice there's a cfuid cookie when I enter the live site. this is my ajax request setup $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }); $.ajax({ beforeSend: function(request) { request.setRequestHeader("Authorization", " JWT "+jwtToken); … -
Temporary files in Django and on the fly file manipulation
Using InMemoryUploadedFile in Django applications for file manipulation i read some interesting post here for this task. InMemoryUploadedFile is a Django object, used in form file uploads, but it also can be used on its own. Using StringIO.StringIO as a temporary file with recent Django versions may results in exceptions when Django tries to call a methods that doesn't exist. Using ContentFile on a for example image data may result in broken image file. InMemoryUploadedFile is a Django friendly solution for such file operations. I used it in tests and also in thumbnail generation in ckeditor before saving the result via Django File Storage API. but how to take right images from the html form using that code ? what changes i need ?because i am comfused now. code : def get_temporary_image(): io = StringIO.StringIO() size = (200,200) color = (255,0,0,0) image = Image.new("RGBA", size, color) image.save(io, format='JPEG') image_file = InMemoryUploadedFile(io, None, 'foo.jpg', 'jpeg', io.len, None) image_file.seek(0) return image_file class ImageUploadViewTests(TestCase): def test_if_form_submits(self): test_image = get_temporary_image() response = self.client.post(reverse('upload-image'), {'image': test_image}) self.assertEqual(302, response.status_code) html code : <form action="./" method="post" enctype="multipart/form-data">{% csrf_token %} <label for="file">Filename:</label> <input type="file" name="num" id="num" /> <br /> <input type="submit" name="submit" value="submit" /> </form> -
Django custom user model: initial migration depends on migration for auth
I'm working on a new Django app, and moved over to a custom user model provided by an app called accounts before creating any users or doing any actual work. This seemed to go fine- I've since created a couple users & customized the admin so that I can edit & create users from there. I cloned my repo to another computer & ran into an error when attempting to start the dev server: This makes sense, as I can't find any auth migrations in my project directory. However, when I create a new DB on my main dev machine & run ./manage.py migrate, the output includes 8 migrations for the auth app: On my secondary machine, I can comment out the dependency in the accounts initial migration, and things seem to work fine- the dev server starts, I can see the users added from my main dev machine (I'm using an sqlite3 DB for now), & use the Django admin however I need. I figured that dependency might have been a leftover somehow, so I thought I might be able to remove the reference. However, if I comment out that dependency on my dev machine & attempt to migrate … -
Django QuerySet object has no attribute 'objects
I have problem with show product in category. (Products are show but when i click on category (tshirt) i have this problem AttributeError at /man/tshirt/ 'QuerySet' object has no attribute 'objects views.py def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(section='man', available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.objects.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products}) urls.py urlpatterns = [ url(r'^$', views.main, name='main'), url(r'^man/$', views.product_list, name='product_list'), url(r'^man/(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'), ] models.py class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) list.html {% extends "shop/base.html" %} {% load static %} {% block title %}VPW{% endblock %} {% block content %} <ul> {% for c in categories %} <li> <a href="{{ c.get_absolute_url }}">{{c.name}}</a> </li> {% endfor %} </ul> {% for product in products %} {{ product.name }} {% endfor %} {% endblock %} -
How can I use Redis cache based storage in our django Rest framework project?
I am developing an application in which user can add, delete , retrieve or update the transactions. I want to store transactions data in the redis cache based storage to improve the performance, what steps should I follow to achieve this? -
How to customize breadcrumbs in Django REST Framework Browsable API
Currently the Browsable API seems to derive the breadcrumbs from the classname of my views. However I am using nested resources for my API so I can get Breadcrumbs like: Root / User List / User Detail / User Invite List / User Invite Detail However the fact that the 'User Invite'-views show User again is pretty redundant. I would rather have that their breadcrumbs would just be 'Invite List' and 'Invite Detail'. Now the most obvious solution would ofcourse be to just rename the view classes but that is not an option for me since I also have the classes ChatInviteList and ChatInviteDetail that share the same problem. So I can't name both of them InviteDetail and InviteList. Is there a way to customize these breadcrumbs in another way? For example by setting some variable in the view class or something. I tried searching the docs but couldn't find anything. -
Django - filter on an annotated query expression that spans a relation
I am new to Django, and am trying to port one of my Flask/sqlalchemy projects to it as a learning experience. I am getting hung up on a couple of things, and the Django docs haven't been super helpful. I'm using Django 1.10.5, Python 3.6, and postgres (on Heroku). Here are the relevant parts of my models: class Sale(models.Model): pub_name = models.CharField(max_length=255) issue_date = models.DateField() net = models.DecimalField(max_digits=10, decimal_places=2) class Publication(models.Model): name = models.CharField(max_length=255) revenue_offset_days = models.IntegerField(default=0) What I'm trying to do is filter Sale on a computed field, revenue_date, which is Sale.issue_date + Publication.revenue_offset_days (currently achieved by way of postgres's interval type), joined via Sale.pub_name == Publication.name. My super-naive approach, just trying to get the join working, was this: sale_query = Sale.objects.annotate( revenue_date=ExpressionWrapper( F('issue_date') + Publication.revenue_offset_days, output_field=DateField() ) ).filter( revenue_date__gte=report_date_start, revenue_date__lte=report_date_end, ) ... but that gives me "can't adapt type 'DeferredAttribute'", which I assume is because of the direct use of a field object (revenue_offset_days). Any pointers would be most welcome. For reference, here's the SQL generated by my Flask app: SELECT sale.pub_name, ((sale.issue_date)::date + (publication.revenue_offset_days || ' days')::interval), sum(sale.net) FROM sale JOIN publication ON publication.name = sale.pub_name WHERE ((sale.issue_date)::date + (publication.revenue_offset_days || ' days')::interval) >= %(param_1)s AND ((sale.issue_date)::date … -
How to deploy django on VPS with external subdomain.?
Good day. I have a web app that I have developed using django. I tested fine on my local, and I'm happy with how it works. However I'm facing an issue bringing it online I used those two guides to reach my deployment: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 and http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/ However my page is giving me a forbidden page. I suspect my issue is with the way I'm handling the subdomain. So the site . has been developed using php, and I have worked on my part with django and been provided with a subdomain which is member.domain.com, So I'm deploying it on the VPS and have to make it use the subdomain. This is how my allowed hosts looks in the settings.py ALLOWED_HOSTS = ['member.domain.com'] and in my nginx: upstream app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/home/path/project/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name member.domain.com; client_max_body_size 4G; access_log /home/path/project/logs/nginx-access.log; error_log /home/path/project/logs/nginx-error.log; location /static/ { alias /home/path/project/src/static/; } location /media/ { alias /home/path/project/src/media/; } location / { # an HTTP header important enough to have … -
Django & database password: best to go with Environmental variables?
As the title suggests, are Environmental the best solution in terms of password safeguarding? I read alternate opionions and would love to hear the advice of the community. -
django admin auto populate inlined models with javascript
I have 3 Models (Client, Pricing and Bill). a client can subscribe to many services each month.. look at my models: class Client(models.Model): ... class Pricing(models.Model): client = models.OneToOneField(Client, on_delete=models.CASCADE) service1 = models.PositiveSmallIntegerField(default="1000") service2 = models.PositiveSmallIntegerField(default="750") service3 = models.PositiveSmallIntegerField(default="350") ... class Bill(models.Model): month_choices = ( ('9', 'september'), ... ) client = models.ForeignKey(Client, on_delete=models.CASCADE) month = models.CharField(max_length=2, choices=month_choices) service1 = models.BooleanField(default=True) service2 = models.BooleanField() service3 = models.BooleanField() total = models.PositiveSmallIntegerField() advance = models.PositiveSmallIntegerField() date = models.DateField(default=datetime.datetime.today) in admin.py, the models Pricing and Bill are display as TabularInline for the client model like so: class TarifInline(admin.TabularInline): model = Pricing formset = RequiredInlineFormSet can_delete = False class BilleInline(admin.TabularInline): model = Bill ... In the inlined Bill, i need is to fill the field 'total' with the sum of the prices of cheacked services.. any help will be appreciated -
how can I store and read a Python list of Django model objects from and to the session?
I am looking for a way to put Django model objects into a list and then store this in the session. I found out that it requires serialization before it can be stored in the session. So when reading the list from the session I first serialize it. But then I was hoping to be able to access my initial objects as before, but it turns out to be a DeserializedObject. Does anyone know how I should approach my requirements ? In a nutshell this is the code I was trying, yet unsuccessfully team1_list = generate_random_playerlist() #generates a list of Player() objects request.session['proposed_team_1'] = serializers.serialize('json', team1_list) #some code inbetween des_list = serializers.deserialize('json', request.session['proposed_team_1']) for player in des_list : print("name of player:"+player.last_name) #fails -
Getting "Please correct the errors below" when saving changes in django admin
The models are created from the following mysql db with "python manage.py inspectdb --database=mydatabasename": CREATE TABLE `authors` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) DEFAULT NULL, `birthday` date DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; CREATE TABLE `books` ( `id` int(11) NOT NULL AUTO_INCREMENT, `titel` varchar(45) DEFAULT NULL, `year` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; CREATE TABLE `authors_books` ( `author_id` int(11) NOT NULL, `book_id` int(11) NOT NULL, KEY `fk_authors_books_2_idx` (`book_id`), KEY `fk_authors_books_1` (`author_id`), CONSTRAINT `fk_authors_books_1` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_authors_books_2` FOREIGN KEY (`book_id`) REFERENCES `books` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `awards` ( `author` int(11) NOT NULL, `award_name` varchar(45) NOT NULL, `year` int(11) DEFAULT NULL, PRIMARY KEY (`author`,`award_name`), CONSTRAINT `fk_awards_1` FOREIGN KEY (`author`) REFERENCES `authors` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; The models looks like this: class Authors(models.Model): name = models.CharField(max_length=45, blank=True, null=True) birthday = models.DateField(blank=True, null=True) class Meta: managed = True db_table = 'authors' verbose_name_plural = 'Authors' def __unicode__(self): return self.name class AuthorsBooks(models.Model): author_id = models.OneToOneField('Authors', models.DO_NOTHING, db_column='author_id', primary_key=True) book_id = models.OneToOneField('Books', models.DO_NOTHING, … -
django url not working when directions followed
This is driving me crazy. Everything looks good. I am getting this error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/home Using the URLconf defined in gds.urls, Django tried these URL patterns, in this order: ^admin/ ^fixiss/ The current URL, home, didn't match any of these. Here is my root url: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^fixiss/', include('fixiss.urls')), ] My app url: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name="index"), ] And the view in my app: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("Home page!") Any help would be greatly appreciated! -
How to get JavaScript to recognize a context_dict object from views.py in Django
I've taken over a Django project from a former co-worker and I've got to edit his code to add a line to a Google Viz line chart. Since the line chart already exist I'm trying to follow the logic used to create it as much as possible (given that I've never done anything like this before). I added the new data model to models.py, successfully migrated it, and found the part of views.py where he set up the data for the line chart and a table below it. I tried to copy what he did in views.py and then the code seems to pick up from there in a JavaScript file where the chart is actually created. However when I get to JavaScript it seems to recognize his object from views.py but not mine, based on what I've seen in the Web Console log. His key object created in views.py was module_progressjs. My object with the data for the new line is called tii_progressjs. It looks to me like an array called context_dict is used to pass the data from Python to JavaScript, but I copied this approach and it didn't seem to work. Here is the heart of the …