Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - filtering by user
I want to render data from the Route model that belongs to the Driver in their 'accounts' page - so displaying the leave_from, destination etc data they have saved in the database so far. Models.py: class Driver(models.Model): user = models.OneToOneField(User, default=1) first_name = models.CharField(max_length=120, blank=True, null=True) last_name = models.CharField(max_length=120, blank=True, null=True) tel = models.CharField(max_length=120, blank=True, null=True) slug = models.SlugField(max_length=120, unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.user.username def get_absolute_url(self): return reverse("account", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.first_name) super(Driver, self).save(*args, **kwargs) class Route(models.Model): leave_from = models.CharField(max_length=120, blank=True, null=True) destination = models.CharField(max_length=120, blank=True, null=True) date = models.DateField(auto_now_add=False, auto_now=False) time = models.TimeField(auto_now_add=False, auto_now=False) driver = models.ForeignKey(Driver, on_delete=models.CASCADE) def __str__(self): return self.leave_from I've played with various querysets and the below is the closest to getting there (I think... I'm new to coding and Django). Views.py: def route(request, slug): routedetails = Driver.objects.filter(route=request.user.driver.route_set.all()) context = { "routedetails": routedetails, } return render(request, "route.html", context) With that I am able to get user to display the same number of instances of data in Route for that Driver. Template: {% for route in routedetails %} <p>{{ route.user }}</p> {% endfor %} I've tried all different variations but I feel this has … -
Can't enable huey service on deploy server
I'm working in a Django project deployment. I have integrated huey to run asynchronous tasks. Locally all runs perfectly but now, at the deployment step, I'm getting troubles about huey service activation. I really can't find any information about that because I think that solution should be so simple, bat I really can't find it :(. I'm using nginx and gunicorn services. App runs perfectly on deploy server but huey tasks are not running. I have created a huey.service file located in /etc/systemd/system/, with the following content: [Unit] Description=Huey Service After=redis.service [Service] User=deploy Group=www-data WorkingDirectory=/home/deploy/projects/myproject/ ExecStart=/usr/bin/python3.6 manage.py run_huey Restart=always [Install] WantedBy=multi-user.target But I'm getting following bug: Nov 26 21:22:15 ip-172-31-11-39 python3.6[22543]: File "manage.py", line 17, in <module> Nov 26 21:22:15 ip-172-31-11-39 python3.6[22543]: "Couldn't import Django. Are you sure it's installe Nov 26 21:22:15 ip-172-31-11-39 python3.6[22543]: ImportError: Couldn't import Django. Are you sure it's Nov 26 21:22:15 ip-172-31-11-39 systemd[1]: huey.service: Main process exited, code=exited, stat Nov 26 21:22:15 ip-172-31-11-39 systemd[1]: huey.service: Unit entered failed state. Nov 26 21:22:15 ip-172-31-11-39 systemd[1]: huey.service: Failed with result 'exit-code'. Nov 26 21:22:15 ip-172-31-11-39 systemd[1]: huey.service: Service hold-off time over, scheduling Nov 26 21:22:15 ip-172-31-11-39 systemd[1]: Stopped Huey Service. Nov 26 21:22:15 ip-172-31-11-39 systemd[1]: huey.service: Start … -
django : how to use filter option in this case?
I have one question here is my code view.py class testView(ListView): model = Photo template_name = 'photo/photo_detail.html' context_object_name = 'main_list' def get_context_data(self, **kwargs): context = super(testView, self).get_context_data(**kwargs) context['extra_value'] = Album.objects.filter(Album__name=Photo.album.name) return context and model.py class Album(models.Model): name = models.CharField(max_length=50) description = models.CharField('One Line Description', max_length=100, blank= True) owner = models.ForeignKey(User, null=True) Category = models.ForeignKey(Categories, null=True) price = models.CharField(max_length=20, null=True) productInfo = models.CharField(max_length=50, null=True) objects = models.Manager() second_manager = SecondAlbumManager() class Meta: ordering = ['name'] verbose_name = 'Album' verbose_name_plural = 'Albums' def __str__(self): return self.name def get_absolute_url(self): return reverse('photo:album_detail', args=(self.id,)) @python_2_unicode_compatible class Photo(models.Model): album = models.ForeignKey(Album) title = models.CharField(max_length=50) image = ThumbnailImageField(upload_to='photo/%Y/%m') description = models.TextField('Photo Description', blank=True) upload_date = models.DateTimeField('Upload Date', auto_now_add=True) owner = models.ForeignKey(User, null=True) class Meta: ordering = ['title'] verbose_name = 'Photo' verbose_name_plural = 'Photos' def __str__(self): return self.title def get_absolute_url(self): return reverse('photo:test', args=(self.id,)) Photo object has ForeignKey(Album) so, I want to use Filtered Album objects in template(photo_detail.html) However, I would like to compare the Album foreign value of one Photo object with Album__name and output it to the template, but I do not know how to change Photo.album.name part. Please let me know. i'm sorry Translated into Google Translator. Thank you for reading -
UNIQUE constraint failed: rango_category.name
Hi im following the tango with django tutorial.. I've searched for a solution to this but nothing! the error: IntegrityError at /rango/add_category/ UNIQUE constraint failed: rango_category.name my model: from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=128, unique=True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) def __unicode__(self): return self.name class Page(models.Model): category = models.ForeignKey(Category) #ForeignKey denotes a relationship between page and category title = models.CharField(max_length=128) url = models.URLField() views = models.IntegerField(default=0) def __unicode__(self): return self.title my add_category view: def add_category(request): # Get the context from the request. context = RequestContext(request) # A HTTP POST? if request.method == 'POST': form = CategoryForm(request.POST) #Have we been provided with a valid form? if form.is_valid(): #save the new category to the database form.save(commit=True) # Now call the index() view. # The user will be shown the Homepage. return index(request) else: # The supplied form contained errors - just print them to the terminal print (form.errors) else: form = CategoryForm() # Bad form (or form details), no form supplied... # Render the form with error message(if any). return render_to_response('rango/add_category.html', {'form':form}, context) my forms: from django import forms from rango.models import Page, Category class CategoryForm(forms.ModelForm): names = forms.CharField(max_length=128, help_text="please enter the category … -
Django celery tasks number limit issue
I have problem run celery workers to execute same task multiple times in parallel. I ran 3 workers and set --concurrency to 2 for all workers. But it only executes 3 tasks over all 3 workers. I hope to run about 10 workers. celery -A my_app worker -l info -c 2 -n worker1 celery -A my_app worker -l info -c 2 -n worker2 celery -A my_app worker -l info -c 2 -n worker3 Please help me whether I can run more than 3 tasks at a time. -
Django Rest Framework: filtering using a method
I am using Django Rest Framework as a backend for an app. I have a User that has one Wallet. Then I have Item. If a User wants an Item it creates an instance in his/her Wallet called WalletItem. All works well. Now I want to limit the number of items for the User using an attribute limit_usage. First, I added a check to post method adding new instance that checks the number of item instances in User's Wallet. So the user gets 403 when trying to add third WalletItem if limit_usage == 2 for this Item. I would like to override a get_queryset() method or queryset in list()/retrieve() methods so that if anonymous user calls /items/ there are unfiltered items in response. However if the user is authenticated I would like to filter only those Items that s/he is allowed to put in the Wallet, i.e. those that have not exceeded limit_usage for current user. class Wallet(models.Model): user = models.OneToOneField('auth.User', related_name='wallet') class Item(models.Model): valid_from = models.DateTimeField() valid_to = models.DateTimeField() limit_usage = models.PositiveSmallIntegerField(default=0) class WalletItem(models.Model): wallet = models.ForeignKey('Wallet', related_name='%(class)ss') offer = models.ForeignKey('Item', related_name='offer') class ItemViewSet(viewsets.ReadOnlyModelViewSet): queryset = Item.objects.all().order_by('-created_at') serializer_class = ItemSerializer def list(self, request, *args, **kwargs): time_now = now() self.queryset … -
Django admin showing duplicate entries
I'm building an internal application tool with Django where I need to keep track of Point() objects. These objects are connected to Reservation model with custom through relationship. The problem Django seems to be duplicating some Waypoint objects in the admin list view. I think it's got something to do with ordering = ('reservationwaypoint__order',) since if I remove it, the count is correct. So to override I tried adding order_by() to distinct but it didn't work. Seems like order_by is not overriding ordering for some reason.. Admin PostgreSQL models.py class Waypoint(models.Model): class Meta: ordering = ('reservationwaypoint__order',) coords = models.PointField(geography=True) place_id = models.CharField(max_length=100) name = models.CharField(max_length=50) alias = models.CharField(max_length=30, blank=True) client = models.ForeignKey(Client) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) @property def get_alias(self): return '{} *'.format(self.alias) if self.alias else None def __str__(self): return self.name.encode('utf-8') def __repr__(self): return self.name.encode('utf-8') class Reservation(models.Model): # .. some other fields route = models.ManyToManyField( Waypoint, through='ReservationWaypoint', related_name='route', ) class ReservationWaypoint(models.Model): class Meta: ordering = ['order'] reservation = models.ForeignKey(Reservation) waypoint = models.ForeignKey(Waypoint) order = models.PositiveIntegerField(default=0) admin.py class WaypointAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'alias', 'client', 'place_id'] list_filter = ('client',) def get_queryset(self, request): return super(WaypointAdmin, self).get_queryset(request).order_by().distinct() admin.site.register(Waypoint, WaypointAdmin) -
Django models not displaying in html tempate
Here is the models I am trying to pass into the html template. It is a model that adds on to the user profile. Every with the models is working correctly and I have already created an object with the model. class Profile(models.Model): # ----- Model Choices ----- STATE_CHOICES = (('AL', 'Alabama'), ('AK', 'Alaska'), ('AS', 'American Samoa'), ('AZ', 'Arizona'), ('AR', 'Arkansas'), ('AA', 'Armed Forces Americas'), ('AE', 'Armed Forces Europe'), ('AP', 'Armed Forces Pacific'), ('CA', 'California'), ('CO', 'Colorado'), ('CT', 'Connecticut'), ('DE', 'Delaware'), ('DC', 'District of Columbia'), ('FL', 'Florida'), ('GA', 'Georgia'), ('GU', 'Guam'), ('HI', 'Hawaii'), ('ID', 'Idaho'), ('IL', 'Illinois'), ('IN', 'Indiana'), ('IA', 'Iowa'), ('KS', 'Kansas'), ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('ME', 'Maine'), ('MD', 'Maryland'), ('MA', 'Massachusetts'), ('MI', 'Michigan'), ('MN', 'Minnesota'), ('MS', 'Mississippi'), ('MO', 'Missouri'), ('MT', 'Montana'), ('NE', 'Nebraska'), ('NV', 'Nevada'), ('NH', 'New Hampshire'), ('NJ', 'New Jersey'), ('NM', 'New Mexico'), ('NY', 'New York'), ('NC', 'North Carolina'), ('ND', 'North Dakota'), ('MP', 'Northern Mariana Islands'), ('OH', 'Ohio'), ('OK', 'Oklahoma'), ('OR', 'Oregon'), ('PA', 'Pennsylvania'), ('PR', 'Puerto Rico'), ('RI', 'Rhode Island'), ('SC', 'South Carolina'), ('SD', 'South Dakota'), ('TN', 'Tennessee'), ('TX', 'Texas'), ('UT', 'Utah'), ('VT', 'Vermont'), ('VI', 'Virgin Islands'), ('VA', 'Virginia'), ('WA', 'Washington'), ('WV', 'West Virginia'), ('WI', 'Wisconsin'), ('WY', 'Wyoming')) FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' … -
django easy pdf can't display include static files (css/ images)
I am trying to include some images and css into my pdf using django-easy-pdf, however they aren't showing up. getFile '/static/open-iconic/font/css/open-iconic-bootstrap.css' '...\\mysite\\__dummy__' '...\\mysite\\__dummy__' Traceback (most recent call last): File "...\Python\Python36-32\lib\site-packages\xhtml2pdf\context.py", line 828, in _getFileDeprecated nv = self.pathCallback(name, relative) File "...\Python\Python36-32\lib\site-packages\easy_pdf\rendering.py", line 35, in fetch_resources path = os.path.join(settings.STATIC_ROOT, uri.replace(settings.STATIC_URL, "")) File "...\Python\Python36-32\lib\ntpath.py", line 75, in join path = os.fspath(path) TypeError: expected str, bytes or os.PathLike object, not NoneType line 0, msg: getFile %r %r %r, fragment: My template file: {% load static %} <link href="{% static '/open-iconic/font/css/open-iconic-bootstrap.css' %}" rel="stylesheet"> my folder structure: mysite - mysite - app -static The static files are working when serving normal webpages, but not in the pdf. Any suggestions? -
How to check if model has an attribute (OneToOneField) with queryset?
I am using the default User model with Agent acting as a OneToOne profile model. I want to create a queryset of all users who has Agent as a field. I'm aware of hasattr but it returns a True/False boolean value so I couldn't implement that into my query. views class AgentSearchResults(ListView): model = User template_name = 'agent_search_results.html' def get_queryset(self): queryset = super(AgentSearchResults, self).get_queryset() # Write something here to check if all users in 'queryset' has 'agent'. return queryset models for reference class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='agent') -
Access the filer plugin directly to link pages with thumbnails
I'm looking at creating a thumbnail based upon the first image which is placed on a page. I was thinking that the best way of doing this would be by accessing the filer plugin directly. The documentation isn't clear on how I can do this. Does anybody know? I know that I can access the Page Titles using: from cms.models import Title Title.objects.all() Is there a similar method for accessing the images on each page? -
Combining DRF unrelated models
I cant seem to figure this out. I want to sort by user joined time and user's photo time. views.py class UserExploreAPIView(generics.ListAPIView): """ User explore API view. """ serializer_class = TimelineSerializer permission_classes = (IsAuthenticated,) pagination_class = SmallResultsSetPagination def get_queryset(self): merged_queryset = Places.get_explore_queryset(self.request.user) queryset = Places.objects.filter(pk__in=merged_queryset) ann_user = User.objects.annotate(photo_time=Extract('date_joined','epoch')) return list(chain(ann_user, queryset)) serializers.py class SomeUserModelSerializer(serializers.ModelSerializer): class Meta: model = SomeUserModel fields = ('photo','id') class PlacesSerializer(serializers.ModelSerializer, IdFieldMixin): photo_link = serializers.CharField(read_only=True) user = UserRelatedSerializer() class Meta: fields = ['id', 'user'] model = Places class TimelineSerializer(serializers.Serializer): photo_time = serializers.CharField(read_only=True) places= PlacesSerializer() #this is the error someuser= SomeUserModelSerializer() class Meta: fields = ['photo_time', 'someuser','places'] ordering = ('photo_time') When I try to get places it says, User has no attribute places. Well yes. places is a foreignkey to user, user wouldn't have places only the reverse. How do I combine these two models? SomeUserModel works because it has onetoone with user, but it doesn't work with places. -
django-tables2 header row urls wrong....can't sort
I can't figure out how to solve this issue about sorting my table: table is rendered at this url: 127.0.0.1:8000/ip_teams/ but when I click on the name of the column to sort the table, url became: 127.0.0.1:8000/?sort=name it excludes the "ip_teams/" path. This is my view: class PagedFilteredTableView(SingleTableView): """ Generic class from http://kuttler.eu/post/using-django-tables2-filters-crispy-forms-together/ which should probably be in a utility file """ filter_class = None #formhelper_class = None context_filter_name = 'filter' def get_queryset(self, **kwargs): qs = super(PagedFilteredTableView, self).get_queryset() self.filter = self.filter_class(self.request.GET, queryset=qs) #self.filter.form.helper = self.formhelper_class() return self.filter.qs def get_table(self, **kwargs): table = super(PagedFilteredTableView, self).get_table() if('page' not in self.kwargs.keys()): self.kwargs['page'] = 1 RequestConfig(self.request, paginate={'page': self.kwargs['page'], "per_page": self.paginate_by}).configure(table) return table def get_context_data(self, **kwargs): context = super(PagedFilteredTableView, self).get_context_data() context[self.context_filter_name] = self.filter return context class FoundationIPTypeList(PagedFilteredTableView): model = tracker_models.FoundationIPType table_class = tables.FoundationIPTypeTable filter_class = tracker_filters.FoundationIPTypeFilter table_pagination = { 'per_page': 10 } this is my table: class FoundationIPTypeTable(django_tables.Table): name = django_tables.Column() class Meta: model = FoundationIPType attrs = {'class': "table table-striped table-condensed table-hover"} fields = ["name", "help_contact_email"] this is my urls: urlpatterns = [ # url(r'^$', views.HomePageView.as_view(), name='home'), # Notice the URL has been named url(r'^about/$', views.AboutPageView.as_view(), name='about'), url(r'^ip_teams/$', views.FoundationIPTypeList.as_view(), name="ip_team_list"), this is my template: {% extends "base.html" %} {% load render_table from django_tables2 %} … -
ConnectionError 111 in Django admin when hitting FB api
I'm making a custom django admin page that hits up our fb account in python requests to create a user using the fb test users and authenticate with our service. The function hits up: https://graph.facebook.com/v2.10/{}/accounts/test-users to create a new fb user and uses the access token returned in the response to authenticate with our service. When importing the create_new_user function directly it works in a python shell however when using the django admin page and filling out the form the page will throw a ConnectionError 111. Function: def create_new_user(gender, location, registered_date) new_user = status_ok(requests.post( FACEBOOK_URL + TEST_USERS.format(settings.FACEBOOK_APP_ID) + '?' + ACCESS_TOKEN + '&installed=true')) logging.info(new_user) # Now we should authenticate and signup with the app authentication_body = json.dumps({'access_token': new_user['access_token']}) login_response = requests.post(ENV + LOGIN, data=authentication_body, headers=HEADERS) coordinates = Nominatim().geocode(location) payload = {'gender': gender, 'latitude': coordinates.latitude, 'longitude': coordinates.longitude} status_ok(requests.put(ENV + PATH_PROFILE, data=json.dumps(payload), headers=HEADERS)) profile = Profile.objects.get(uid=new_user['id']) profile.registered_date = registered_date profile.save() Form: class CreateTestUserForm(forms.Form): gender = forms.ChoiceField(choices=(('m', 'm'), ('f', 'f')), widget=forms.RadioSelect()) location = forms.CharField(initial='San Francisco') registered_date = forms.DateTimeField(initial=datetime.datetime.now(), widget=forms.SplitDateTimeWidget()) -
object has no attribute 'model' -- returning a queryset (Django)
I'm trying to modify some code (that I did not originally author) so that I return a queryset to my client in a dict along with another array. It returns to me, depending on the form of my response: File "/usr/local/lib/python2.7/site-packages/django_filters/rest_framework/backends.py", line 54, in get_filter_class assert issubclass(queryset.model, filter_model), \ AttributeError: 'JsonResponse' object has no attribute 'model' My searches on the matter reveal answers a little more complicated than what I'm sure is a simple solution. Below is my latest attempt. queryset = Package.objects.filter(user=userInstance) feedback_arr = [ ['a','b','c'], [1,2,3] ] queryset_dict = list(queryset.values().distinct()) uploadsAndFeedback = { 'uploads' : queryset_dict, 'feedback': feedback_arr } return JsonResponse(uploadsAndFeedback) -
Django Url NoReverseMatch, reverse with key arguments not found
I have a trouble with URl mapping. I want that title of the post to be in the url and have NoReverseMatch error when trying to do this. Here is app/urls.py file from django.conf.urls import url from .views import PostsListView, PostDetailView app_name = 'era' urlpatterns = [ url(r'^$', PostsListView.as_view(), name='posts_list'), url(r'^post/(?P<title>[\w-]+)/$', PostDetailView.as_view, name='post_details') ] app/views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class PostsListView(ListView): model = Post class PostDetailView(DetailView): model = Post context_object_name = 'post_details' template_name = 'era/post_details.html' and finally era/post_list.html {% extends 'era/base.html' %} {% block content %} {% for post in post_list %} <div class="post-block" style="width: 27%;float: left; margin: 3%; background-color: rgba(169, 169,169,0.5); padding: 2%; border-radius: 15px"> <h3>{{ post.title }}</h3> <br> {{ post.image_title }} <br> {{ post.short_description }} <br><br> <a href="{% url 'era:post_details' title=post.title %}" class="btn btn-primary" style="float: right">Read more</a> </div> {% endfor %} {% endblock %} Will be very gratefull for help! -
Django method in JavaScript causes TemplateSyntaxError
I am using ajax in javascript to send and receive database information that populate the html page. When I receive the data, I append it to the div elements. Every object I append should have a delete function. So I create a onclick method that passes along the unique id of that object My problem is that I can't seem to properly format the django url method with quotes for this call: onclick='removeFile("{% url 'delete_file' model['pk'] %}");' The full line look like this: $('#gallery tbody').append("<tr><td><a href='" + object['url'] + "'>" + object['file'] + "</a><span style='float:right'><button type='button' id='delete_button' class='btn btn-lg btn-danger' onclick='removeFile("{% url 'delete_file' model['pk'] %}");'></button></div></td></tr>") The error I get is a TemplateSyntax error Could not parse the remainder: '['pk']' from 'model['pk']' If I log the value of 'model['pk']' in the console, I get the correct ID. It loads correctly when I delete the onclick method (no delete function though). I have tried putting it in the html directly like this <button type="button" class="glyphicon glyphicon-remove-sign" onclick='removeFile("{% url 'delete_file' a.pk %}"); return false'> </button> where a is the model object from django and it works fine. How can I properly add the onclick method to the javascript append method? The full javascript … -
Updating Data: No Page Refresh
I'm trying to create a Like button, Here's what I tried, $('.like-click').on('click', function(e){ e.preventDefault(); var element = $(this); var quesURL = element.attr('like-href'); $.ajax({ url: quesURL, method: 'GET', data: {}, success: function (data) { var like_text = $(data).find('.like-click').html(); $(element).html(like_text); } }) }); Here's the HTML code for button, {% for data in datas %} ... <a class="like-click" like-href="URL">{% if user in Likes %}Liked{% else %}Like{% endif %}</a> ... {% endfor %} This code is working fine only for the First like button on webpage only not for others. How can I solve that problem? Thanks in advance! -
How to implement video call between users on django app
I have a django based website running, and want to allow my users to have video calls between them. Is there an API for that ? -
Django: How Do I load CSV data into a html template?
I'm building my first Django Web App and I'm trying to load data from a csv file into my html template. I've tried searching for a solution for the past hour but cannot find what I'm looking for. I would just like to load a row of data from a csv file and put it into my html template. I've no idea where to start. Any help would be greatly, greatly appreciated. -
Target WSGI script '/home/ubuntu/Django/bot/wsgi.py' cannot be loaded as Python module
i'm trying to devloping Django project. and i'm beginner. suddenly, today my server does not work. i think i do nothing. so i don't understand what is the problem. this is my /var/log/apache2/error.log mod_wsgi (pid=27808): Target WSGI script '/home/ubuntu/Django/bot/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=27808): Exception occurred processing WSGI script '/home/ubuntu/Django/bot/wsgi.py'. and when I try to enterd my server http://MYURL, 500 Internal Server Error occur. this is my wsgi.py code import os import sys sys.path.append('/home/ubuntu/Django') #sys.path.append('/home/ubutu/Django/bot') sys.path.append('/home/ubuntu/Django/myvenv/lib/python3.5/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bot.settings") application = get_wsgi_application() since i create my project, i have done anything on my wsgi.py however the error occurred now. -
How to send room name in connect function in Django Channels
I have several rooms in my programs. Each user can connect to these rooms and send messages. for each room, I have a group. I want to specify a room name for these group in connect function. but I don't know how to send room name in connect function. @channel_session_user_from_http def chat_connect(message): message.reply_channel.send({'accept': True}) @touch_presence @channel_session_user def chat_receive(message): data = json.loads(message['text']) myRoom = data['room'] messageChat = data['messagechat'] if not message.user.is_authenticated(): return Group(myRoom).add(message.reply_channel) Room_channels_presence.objects.add(myRoom, message.reply_channel.name, message.user) message.channel_session['room'] = myRoom #store in db try: room = Room.objects.get(slug=myRoom) message_model = Message( user = message.user, room = room, text = messageChat ) message_model.save() except: pass my_dict = { 'user': message.user.username, 'messagechat': messageChat } Group(myRoom).send({'text': json.dumps(my_dict)}) -
Zurb foundation Interchange with Django templates?
Is Zurb Foundation's Interchange compatible for use with Django templates? I can't see a way to get them to work together, though the issue is just a technical one - Interchange seems to want html file paths, while Django's html templates render inline. I suppose it would be possible to render the necessary templates each request into temporary files and hand those to Interchange, but that's not a very clean solution and would require a lot of boilerplate. I'm looking for a cleaner solution or for an alternative within Foundation and Django. -
Get sub-key's count in admin list-filter
Here is my models.py: class Category(models.Model): category = models.CharField(max_length=50, verbose_name=u"文章分类", default="") add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间") class Meta: verbose_name = u"文章分类" verbose_name_plural = verbose_name def __unicode__(self): return self.category class Article(models.Model): category = models.ForeignKey(Category, verbose_name=u"文章分类") title = models.CharField(max_length=100, verbose_name=u"文章题目", default="") content = UEditorField(width=1000, height=500,imagePath="media/", filePath="media/",verbose_name=u"文章内容") read_nums = models.IntegerField(default=0, verbose_name=u"阅读量") comment_nums = models.IntegerField(default=0, verbose_name=u"评论数") add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间") class Meta: verbose_name = u"文章" verbose_name_plural = verbose_name def __unicode__(self): return self.title Now I need to show how many articles in category at django-admin page, in this page: How should I do? -
Django UpdateView get blank values?
So I'm creating a django website and I have an Edit Button. The edit shows a pop up with a few forms to edit. The problem is that the forms to edit are blank! instead of having the previous data. e.g- ServerName="Yossi" When I click edit instead of having "Yossi" in the form I have nothing. What do I need to add to the index.html or to the Class of PostEdit so I will have the previous data in the forms and not blank forms? models.py - from django.db import models # Create your models here. class serverlist(models.Model): ServerName = models.CharField(max_length = 30) Owner = models.CharField(max_length = 50) Project = models.CharField(max_length = 30) Description = models.CharField(max_length = 255) IP = models.CharField(max_length = 30) ILO = models.CharField(max_length = 30) Rack = models.CharField(max_length = 30) Status = models.CharField(max_length = 30) #date = models.DateTimeField(auto_now=True) views.py - # Create your views here. from django.shortcuts import render_to_response from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query …