Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Group my-sql column objects of a model having same data on Django admin side
I have a model with the following definition class exam_questions(models.Model): exam_name=models.ForeignKey(exam,on_delete=models.CASCADE) question=models.ForeignKey(questions,on_delete=models.CASCADE) class Meta: db_table = 'examquestions' unique_together = (("exam_name", "question"),) def __str__(self): return '%s - %s' % (self.exam_name, self.question) The data on sql table will look like this +----+----------------+-------------+ | id | exam_name | question | +----+----------------+-------------+ | 2 | test2 | 29 | | 3 | test1 | 41 | | 6 | test2 | 40 | | 7 | test1 | 42 | +----+----------------+-------------+ On Django admin I am looking the model objects like the following: test2-29 test1-41 test2-40 test1-42 Now I want to group questions of same test and want to look them like the below: test2-29,40 test1-41,42 I tried using normal python string operations, none of them worked on amdin django instead gave me errors. Is there way for doing this. Any help is greatly appreciated. Thanks -
Django channels and socket.io-client
I'm trying to use them for the first time and wonder I'm headed to the right direction. Here are my understandings, socket.io is a wrapper around websocket, and falls back to sub-optimal solutions when websocket is not available. Django channels can talk websocket as well. (I think it converts django as a message queue like system. although this understanding or misunderstanding should affect this question) So I'm trying to use Django channels on the server and socket.io-client on the client. socket.io has api which looks like socket.on(type, (payload)=> {}) Whereas Django channels has a form of message.reply_channel.send({ "text": json }) is the "text" type of socket.on(type)? Can Django channels and socket.io-client talk to each other? -
Django messaging application schema review
Currently I am making a simple messaging application in django. Creating messages Each user can open up a chat room with another user (and only one other user) and send messages back and forth. Listing chat rooms Users will also be able to delete messages, and mark them as read/unread. And they are ordered by the time of latest message Creating chat rooms New chat rooms can be opened by entering the recipient's username and a subject and message Models that I currently have class User(models.Model): name = models.CharField(max_length=30, primary_key=True) class Link(models.Model): user = models.ForeignKey('User') chat = models.ForeignKey('Chat') read = models.BooleanField() class Chat(models.Model): id = models.AutoField(primary_key=True) subject = models.CharField(max_length=300) class Message(models.Model): id = models.AutoField(primary_key=True) text = models.CharField(max_length=300) date = models.DateTimeField() from = models.ForeignKey('User') chat = models.ForeignKey('Chat') Queries that I currently have # creating a new chat room chat_room = Chat(subject='Some subject') link1 = Link(user=me, chat=chat_room, read=True) link2 = Link(user=other, chat=chat_room, read=False) # adding a new message to some chat room new_message = Message(text='blablabla', date=timezone.now(), from=me, chat=some_chat_room) # listing out all chats that I am currently in - showing these # 1) who I am talking to # 2) whether I have read it # 3) subject # 4) time of … -
Django: Storing templates in DB: Define API (variables in context)
I want to store django templates in the database and make them editable for via web. Next, I want to define template types: A template type defines the allowed variables of the context. Examples: Invoice-Template-Type gets these variables: customer_name, invoice_id, ... Voucher-Template-Type gets these variables: voucher_id, voucher_amount, ... The people how edit the templates (stored in db, edit via web) should see the available variables and get a warning if they use variables which are unknown. How to get this done or am I reinventing the wheel? -
Understanding Django GenericForeignKey and GenericRelation
I'm building vocabulary and have following models: class Word(Model): name = CharField(max_length=75) class EnNoun(Model): word = OneToOneField(Word) class FrNoun(Model): word = ForeignKey(Word) gender = CharField() Same word can be in both EnNoun and FrNoun. Is it possible to fetch result for given word for both EnNoun and FrNoun, using the least number of queries (there will be more similar classes for language and part of speech, like ItAdverb)? How to store translation from one lang to another (quering 20+ tables is not an option). Are GenericForeign keys of any use? How do I use them in general? Thank you. -
Override POST, PATCH & DELETE methods
How do I override the POST, PATCH & DELETE methods for multiple ViewSets to allow me add a mandatory backend parameter? Logic. Am building a multi-tenant app which has got a "tenant_id" in all the relevant tables. This tenant_id identifies the tenant and as such all requests must include this parent key to avoid users seeing/modifiying content that is not theirs. For Get queries, I have created a custom filter backend which enables me to add a mandatory filter object to limit what a user can get class CustomFilterBackend(filters.BaseFilterBackend): """ Filter that only allows users to see entries related to their tenant. """ def filter_queryset(self, request, queryset, view): tenant_id = get_tenant_id_from_token(request) return queryset.filter(is_deleted=False, tenant_id=tenant_id) I have then added this filter to all ViewSet Classes via the filter_backends = () option Question is, is there a way to achieve the same for POST, PATCH, DELETE requests? My current thinking is that one would override the model.save method for all models? But that won't take care of HTTP DELETE method. -
Django redirect to a different site if url contains keyword preserving the subdomain
if ("keyword" is in the url) site A redirects to site B preserving what follows the site www.google.com/zh-cn/site=10 if "zh-cn is keyword" then go to www.google.cn/site=10 how can i do this? -
How to send extra argument with pre_delete signal?
I want to delete a model (House) but before that, insert it in deleted table. so far: @receiver(pre_delete, sender=House) def delete_house(sender, instance, **kwargs): reason = kwargs.get('delete_reason', '') if sender == House: deleted_house = DeletedHouse(doc_code=instance.doc_code, tell=instance.tell, address=instance.address, delete_reason=reason) deleted_house.save() for member in instance.child_set: m = DeletedMember(first_name=member.first_name, last_name=member.last_name, house=deleted_house ) m.save() House will delete all children (CASCADE). so I have to save deleted house and children in pre_delete. The problem is I do not know how to pass delete_reason in kwargs to my method -
How to iterate over every foreign key in a model?
If I have a model like the following: class Keyword(models.Model): model1 = models.ForeignKey(Model1, null=True, blank=True, default=None) model2 = models.ForeignKey(Model2, null=True, blank=True, default=None) model3 = models.ForeignKey(Model3, null=True, blank=True, default=None) model4 = models.ForeignKey(Model4, null=True, blank=True, default=None) not_foreign_key = models.CharField(max_length=10, null=True, blank=True) How can I iterate over each foreign key? I'm imaging some sort of for loop like this (pseudocode): for each foreign key in Keyword: do something with the foreign key Thank you for your help. -
How to add map in djnago template
I am new to django. i have to add map in my django project. please help me this is my models class UserProfile(models.Model): user = models.OneToOneField(User) phone_no= models.CharField(max_length=10, null=True) shop_name=models.CharField(max_length=244, null=True) shop_address=models.CharField(max_length=200,null=True,blank=True) city=models.CharField(max_length=20,null=True) country=models.CharField(max_length=20,null=True) abn=models.CharField(max_length=11) website = models.CharField(max_length=200, blank=True, null=True) created_at = models.DateTimeField(default=datetime.now, blank=True) updated_at = models.DateTimeField(default=datetime.now, blank=True) Emg_no=models.CharField(max_length=10, null=True,blank=True) area_code=models.CharField(null=True,blank=True,max_length=2) landline_number= models.CharField(null=True,blank=True,max_length=9) payment_date = models.DateTimeField(default=datetime.now, blank=True) status=models.ForeignKey(Status,blank=True,null=True) user_image = models.ImageField(upload_to='user_image') def __str__(self): return self.user.first_name class Meta: db_table = 'registration_userprofile' i want to show map from my above model and shop_address field -
please tell me the installation steps for django 1.8 . i am using Python 3.3 for windows 7
please tell me the installation steps for Django 1.8 . i am using Python 3.3 for windows 7.I have installed pip also. but anyhow facing syntactical errors.do help me asap. -
Getting a unexpected link in django template
I'm practicing a simple blog site, where if I clicked in author names, it shows the associated post! If I used two different view function the output is fine but if I implemented in one function, in author's post page it shows a url which should not! The screenshot of the html page: The Url Link contain author post page link! but according to the code it should display the post link! <a href="{{ post.url }}">Url Link</a> I'm pasting my all code for better understanding. Thanks in advanced! This is my urls.py: urlpatterns = [ url('^$', views.url_list, name='url_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$', views.post_details, name = 'post_links'), # url(r'^author/(?P<author_slug>[-\w]+)/$', views.author_posts, name = 'url_list_by_author'), url(r'^author/(?P<author_slug>[-\w]+)/$', views.post_details, name = 'url_list_by_author'), ] and my view.py is: def post_details(request, year=None, month=None, day=None, post=None, author_slug=None): author_post_list = None if year: post = get_object_or_404(UrlPost, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day, ) if author_slug: author_post_list = UrlPost.author_manager.author_post(author_slug) post = None return render(request, 'detail.html', {'post': post, 'author_post_list': author_post_list}) and html page: {% extends "base.html" %} {% block title %}{{post.title}}{% endblock %} {% block content %} <h1>{{ post.title|title }}</h1> <p>{{ post.publish }}</p> <ul> {% for author in post.author.all %} {% if forloop.first %} <li><h4>Author: &nbsp;</h4></li> {% endif %} <li><h4><a href="{% url "blog:url_list_by_author" author %}">{{ … -
Django, order by ManyToMany date
Lets say for example we have the following models class Parent(models.Model): name = models.CharField(max_length=20, primary_key=True) class Children(models.Model): name = models.CharField(max_length=20, primary_key=True) parent = models.ManyToManyField('Parent') # mom & dad class GrandChildren(models.Model): name = models.CharField(max_length=20, primary_key=True) birth = models.DateTimeField() children = models.ForeignKey('Children') # only 1 parent (i know its a bit contrived) How can I, given a particular parent object, get all the attached children and other them according to the grandchildren birthday? 1. James (children) (1st earliest grandchild birth 1m ago) 2. Ricky (children) (2nd earliest grandchild birth 5m ago) ... Note that we are ordering by essentially the last birthed grandchild, since there can be many of them. If, ricky suddenly gave birth to another grandchild, then it would be 1. Ricky (children) (1st earliest grandchild birth 0m ago) 2. James (children) (2nd earliest grandchild birth 1m ago) -
filtering model of a table using filterset of another table-django
I have 3 models[fields]: (1) stations[station_id,station_code] (2) route[route_id] and (3) sequence[route_id,station_id,sequence_no]. I want to filter stations.objects (and fetch its fields) such that it contains stations of a given route_id only. So far I was able to write only this line which I guess is incorrect st=stations.objects.filter(station_id=sequence.objects.filter(route_id=rid)) Please help me find a correct solution to it -
Django Tests running abnormally
I am trying to test the number of DB queries executed by an API in my Django application. So, I have a test case similar to the following: class DatabaseQueriesTestCase(TestCase): scan_uri = "something" def test_API_1(self): payload = { 'id': 12, 'name': "ABCD" } self.assertNumQueries(13, self.client.post, self.scan_uri, data=payload) On running the test multiple times, some pass while others fail. Some fail, saying one more query was run. Why is this happening? Is this a problem with assertNumQueries ?? -
XLRDError : Expected BOF record; found '\x1f\x8b\x08\x00\x00\x00\x00\x00'
My code is trying to open and convert xls or xlsx files to CSV first however this error occurs: XLRDError : Expected BOF record; found '\x1f\x8b\x08\x00\x00\x00\x00\x00' Through other answers this seems to be another format, UTF-16 , therefore I also tried to do a struct.unpack('>i', filename) but the method is looking for a string. I'm not sure if I should use it for the file or each row on the file, so I deleted that implementation first. I'm sure that I saved correctly in .xls format. Below is the code that I use to handle the files: views.py def fileConvert(layers): #Convert all xls, csv files to geojson for layer in layers: doc = Document.objects.get(id = layer.documentLayer_id) print (doc.extension()) if doc.extension() == '.xls' or doc.extension() == '.xlxs': excelFilePath = doc.getPath() #Convert excel to csv csvFilePath = excelToCsv(excelFilePath, doc) #Convert csv to geojson csvToGeojson(csvFilePath, doc) elif doc.extension() == '.csv': csvFilePath = doc.getPath() #Convert csv to geojson csvToGeojson(csvFilePath, doc) fileConverter.py import comet.settings as settings import xlrd, csv, struct def open_xls_as_xlsx(filename): # open using xlrd book = xlrd.open_workbook(filename) index = 0 nrows, ncols = 0, 0 while nrows * ncols == 0: sheet = book.sheet_by_index(index) nrows = sheet.nrows ncols = sheet.ncols index += 1 … -
Create a social network with Django/MySQL
Is it possible to create a social network with Django/MySql? I was thinking of Parse backend but that's closed down. So now I want use MySql/Django to create a social network? Will it be possible for these 2 to handle friend requests/only visible wall to friends... etc? -
how to get the latest in django model
In this model: class Rank(models.Model): User = models.ForeignKey(User) Rank = models.ForeignKey(RankStructure) date_promoted = models.DateField() def __str__(self): return self.Rank.Name.order_by('promotion__date_promoted').latest() I'm getting the error: Exception Value: 'str' object has no attribute 'order_by' I want the latest Rank as default. How do I set this? Thanks. -
Is Django itself a backend?
I have been reading into Python/Django but I was unable to find good info. I have learned that Django is a backend, but some people are saying that django itself runs on PostGreSQL? So I need to learn both python/PostGreSQL? Or is DJANGO itself a backend? -
How to create block with a list of choices in page admin, outputs list of model instance URLS?
My goal: to give page creators the ability to output a list of courses available per faculty, where faculty is chosen from a list in the page admin. I'm basically trying to create a block to put in a stream field which does this: 1. user selects courselist block from stream panel - CourseListBlock inherits from ChoiceBlock or ChooserBlock 2. user selects faculty from drop down list in block 3. page outputs list in html of these URLs Each URL already exists for each course, returned by award.get_absolute_url(): businesslist = [award.get_absolute_url() for award in Award.objects.filter(school__name__contains='Business')] educationlist = [award.get_absolute_url() for award in Award.objects.filter(school__name__contains='Education')] sciencelist = [award.get_absolute_url() for award in Award.objects.filter(school__name__contains='Science')] In the shell, these list comprehensions output a list of URLs, exactly as I want them, eg: ((['/awards/doctor-philosophy-phd/', '/awards/master-arts/', '/awards/master-philosophy-mphil/', '/award/bachelor-science/', )) award: what we call courses, or degrees here. Is a regular django model. school: another name for faculty, or department. Is also a regular django model The URL is built from the award.slug attribute. Currently, the Page admin in wagtail provides the dropdown for the choice of faculty. It will output the name of the faculty in a div according the streamfield's rendering approach. Using the 3rd SO link … -
Generating a list of uncreated foreign keys
How I can get the items that are NOT translated in a given language when my models are structured as follow: class Language(models.Model): name = models.CharField(max_length=20, unique=True) code = models.CharField(max_length=5, unique=True) class Item(models.Model): id = ... class Translation(models.Model): name = models.CharField(max_length=100) language = models.ForeignKey('languages.Language') item = models.ForeignKey(Item) I need an efficient solution are there will be million of records. So I basically need to loop over a list and add the missing translations. -
How do I route the POST,PUT and GET to different business logic on Django-REST framework?
I have started working on django-rest framework.... I selected this framework because I wanted to integrate the same api's with a mobile application(android). I had done this before with nodeJs(Express) , I used to write GET,POST,PUT and DELETE request for the same url and write business logic in it. How do i implement the same with DjangoRest.... How do I route the PUT or POST request to business logic and give a response like I do in ExpressJs Something like below: module.exports = function (router) { router.get('/demoEndPoint', function(req,res){ /*business logic here res.send('hello world'); }); router.post('/demoEndPoint', function(req,res){ /*business logic here res.send('hello world this Post Request'); }); router.put('/demoEndPoint', function(req,res){ /*business logic here res.send('hello world put request'); }); }; -
How to force django to accept non-unique slugs
So for one of my apps I don't want slugs to be unique, I want instances to be able to have same slugs. I have tried to make this possible using the unique=False widget, but it doesn't seem to work. I then tried changing slug to use regular CharField but it still won't let me, and instead gives me the exact same error. I removed all db instances of this app, then removed previous migrations, migrated again and retried using both fields, but the error persists. Tried with both slug = models.CharField(max_length=50, unique=False) and slug = models.SlugField(max_length=50, unique=False) Error IntegrityError at /admin/pages/page/add/ duplicate key value violates unique constraint "pages_page_slug_key" DETAIL: Key (slug)=(tot) already exists. The part that is confusing me is the 'key value'. Why exactly is slug key value? Even when it's a charfield? -
Access apache2 server through the external IP (Ubuntu)
I am trying to make my apache2 server accesable through the internet. I managed to set my site up in apache with the help of this guide: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04 So if I go to localhost I can see my site. From what I've come to understand, to make my site accesible I need to: Open port Set apache to listen to that port. I've read a lot about port 80, so I tried to open it to no avail. Instead I somehow managed to open port 8080, so if I go to sites like canyouseeme.org, it shows that it is open. I set my apache to listen to port 8080, so my ports.conf looks like this: # If you just change the port or add more ports here, you will likely also # have to change the VirtualHost statement in # /etc/apache2/sites-enabled/000-default.conf Listen 8080 <IfModule ssl_module> Listen 443 </IfModule> <IfModule mod_gnutls.c> Listen 443 </IfModule> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet And changed the /etc/apache2/sites-available/000-default.conf so it looks kind of like this: <VirtualHost *:8080> . . . Alias /static /home/user/myproject/static <Directory /home/user/myproject/static> Require all granted </Directory> <Directory /home/user/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/user/myproject:/home/user/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject … -
Django Static Files Not Loading in Deployment
I've been going at this for about 3 hours now and I'm completely lost and running in circles. I'm trying to get my static and media files into deployment. My settings file looks like this: DEBUG = False ... STATIC_ROOT = '/home/huhu/webapps/eng30_static_media/static' MEDIA_ROOT = '/home/huhu/webapps/eng30_static_media/media' STATIC_URL = '/static/' MEDIA_URL = '/media/' I've run collectstatic and my static files are in /home/huhu/webapps/eng30_static_media/static I still have no idea what to do with the media files. What am I missing here? I currently don't have any static js, static img, static css, or media uploaded via the admin panel showing.