Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Don't know how to convert the Django field skills (<class 'taggit.managers.TaggableManager'>)? graphql
I am trying to change my rest end points to graphql and I had a library called TaggableManager as one of the model fields. Anyone know how this can work with graphql? Thanks in advance -
Django - inclusion tag
In my html, there is a div containing all the comments. I need to restrict the amount of comments to be shown. So, I created an inclusion tag: <div class="past_comments"> {% limit_amount_in_a_page page_nr=page_nr topic_id=topic.id amount=4 %} </div> @register.inclusion_tag('post/comment_block.html') def limit_amount_in_a_page(page_nr, topic_id=1, amount=5): topic = get_object_or_404(Topic, id=topic_id) comments = Comment.objects.filter(topic=topic) selected_comments = [] starting_index = page_nr*amount for index in range(starting_index, starting_index + amount): if index >= len(comments): break; selected_comments.append(comments[index]) return { 'topic': topic, 'page_nr': int(page_nr), 'selected_comments': selected_comments, 'amount_comments': comments.all().count(), 'limit_amount_comment': amount, } so, this tag shows the code from comment_block.html {% load static %} {% load post_tags %} {% load post_filters %} {% for comment in selected_comments %} <div class="comment_body"> <div class="user_info_block"> <div class="content"> <div class="photo_profile"></div> <div class="user_info"></div> </div> </div> <div class="content_block"> <p>{{comment.content}}</p> </div> </div> {% endfor %} topic id is {{topic.id}} page nr is {{page_nr}}<br> comment amount is {{amount_comments}}<br> limit amount is {{limit_amount_comment}}<br> {% if page_nr != 0 %} <a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a> {% endif %} {%page_not_over_amount page_nr amount_comments limit_amount_comment%} {% if comment_not_over_amount %} <a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a> {% endif %} As you can see, I created another tag page_not_over_amount after all comments are shown to hide the link directing to the … -
Wrong table used when running tests Django Pycharm
I used inspectdb to import the Models schema from MySQL database connected with MySQL Connector/Python. When I run the tests, the system shows: django.db.utils.ProgrammingError: Table 'test_mydb.cards' doesn't exist But the table name is just mydb.cards, not test_mydb.cards Why is this prefix being added? My app's name is just container. -
Django Javascript
I'm trying to add some javascript to my Django template from this example, that dynamically changes the backround of rows in a table if a checkbox is selected. http://jsfiddle.net/hkL43/7/ $('table').on('change', ':checkbox', function() { $(this).closest('tr').toggleClass('selected', this.checked);}) .find(':checkbox').trigger('change'); I have other javascript scripts running in my block add_to_header - and all these scripts work like I expect them to, for the most they are encapulated in script tags with a function name eg. <script type="text/javascript"> function checkAll(bx) { var cbs = document.getElementsByTagName('input'); for(var i=0; i < cbs.length; i++) { if(cbs[i].type == 'checkbox') { cbs[i].checked = bx.checked; } } } </script> And activated by 'onClick' events and other events. I have jquery in my base template - and as far as I can tell there should be no problem running this code. I tried embedding the code in script tags to get it to execute when the page loads - but nothing seems to work eg. <script type="text/javascript"> $( function() { $('table').on('change', ':checkbox', function() { $(this).closest('tr').toggleClass('selected', this.checked); }) .find(':checkbox').trigger('change'); </script> or <script type="text/javascript">$(document).ready(function() { $('table').on('change', ':checkbox', function() { $(this).closest('tr').toggleClass('selected', this.checked); }) .find(':checkbox').trigger('change'); } </script> What am I doing wrong? -
Output a paragraph with line breaks in Django inside a list item
I have a bulletin board on a Django website. A single bulletin body is defined as bulletin_body = models.TextField('Body', max_length=5000) in class Bulletin inside models.py. When a bulletin body is placed in a template as a separate paragraph, it displays all the line breaks that the body contains as expected. That is, <h2>{{bulletin.bulletin_body|linebreaksbr}}</h2> works fine. But when a bulletin body is a list element, (e.g. in a page that contains bulletin feed) no line breaks are displayed. Example: <ul> {% for bulletin in latest_bulletin_list %} <li>{{bulletin.bulletin_body|linebreaksbr}}</li> {% endfor %} </ul> I've only found answers suggesting to check if the model is TextField and to use linebreaks or linebreaksbr tag. I follow both advice and still can't display line breaks. -
Trying to implement user owned tags in django-taggit for specific objects
I am trying to implement a Video model in Django 1.11 which are tagged by both global tags (which are added by the admin when the video is first uploaded) which are able to be viewed by everyone accessing, and user specific tags (added by users per video) which are specific to the user logged in. Currently, the model looks something like this: class Video(models.Model): video_name = models.CharField(max_length=50) video_pub_date = models.DateTimeField('date published') video_file = models.FileField() video_thumbnail = models.ImageField(null=True, blank=True) global_tags = TaggableManager() video_views = models.IntegerField(default=0) User model is just using from django.contrib.auth.models import User but not explicitly defined in my models.py file However, in addition to global_tags, I need a way to have private tags (user specific). This answer In django-taggit, how to get tags for objects that are associated with a specific user? shows how to filter tagged objects based on object ownership, but this is not what I want since the object themselves (in my case Video), is not owned by anyone in particular, but the tags themselves are to be owned by specific user. -
Django : Context processors
What is the mechanics behind context processors in Django? I have used them before, but if someone asks me to teach them what context processors are about, I probably could not answer. This is from Django documentation: context_processors is a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context. Can someone elaborate on this. What are context processors exactly ? -
Bing Ads API / Suds Python deserialise parameter error
I have some (working) Python 3.5.2 code to download a report from Bing Ads via their API which I'm attempting to put into a Django application. When I run the code via the Django shell, after I call SubmitGenerateReport(ReportRequest=report_request) I get this error: Traceback (most recent call last): File "C:\Python35-32\lib\site-packages\googleads\util.py", line 123, in PatchedHttpTransportSend fp = self.u2open(u2request) File "C:\Python35-32\lib\site-packages\suds\transport\http.py", line 132, in u2open return url.open(u2request, timeout=tm) File "C:\Python35-32\lib\urllib\request.py", line 472, in open response = meth(req, response) File "C:\Python35-32\lib\urllib\request.py", line 582, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python35-32\lib\urllib\request.py", line 510, in error return self._call_chain(*args) File "C:\Python35-32\lib\urllib\request.py", line 444, in _call_chain result = func(*args) File "C:\Python35-32\lib\urllib\request.py", line 590, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 500: Internal Server Error During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python35-32\lib\site-packages\suds\client.py", line 613, in send reply = self.options.transport.send(request) File "C:\Python35-32\lib\site-packages\suds\transport\https.py", line 66, in send return HttpTransport.send(self, request) File "C:\Python35-32\lib\site-packages\googleads\util.py", line 134, in PatchedHttpTransportSend raise suds.transport.TransportError(e.msg, e.code, e.fp) suds.transport.TransportError: Internal Server Error During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\joe.heffer\PycharmProjects\wisepanda\report\models.py", line 401, in query report_submission = reporting_service_client.SubmitGenerateReport(ReportRequest=report_request) File … -
Django admin display filter depending on other filters
Here is an example of models: class Books(models.Model): ... class Chapter(models.Model): ... book = models.ForeignKey('Books') class Exercise(models.Model): ... book = models.ForeignKey('Books') chapter = models.ForeignKey('Chapter') And here is the Admin class for exercise: class ExerciseAdmin(admin.ModelAdmin): ... list_filter = (('book',admin.RelatedOnlyFieldListFilter),('chapter',admin.RelatedOnlyFieldListFilter)) admin.site.register(Exercise, ExerciseAdmin) I now have the filters book and chapter for exercise. When I click on a book in the filter book, it shows me all the exercises of the selected book accordingly. But in the list of filter chapter, it still shows all the chapters of all the books. Is there a way to only display, in the filter chapter, the chapters of the book that I selected in the first filter book? How? -
Django ifequal and if Statement Always Going to Else tags
I Am currently trying to compare the product id to the id given in the URL. But the if statement in the template always returns "else" even though testing provides both to be equal. views.py (where data is given) def editstatus(request, product_id): try: request.session['user_id'] except KeyError: return redirect("/login") products = Product.objects.all() context = { "product":products, "theid" : product_id, } return render(request, 'posystem/status.html', context) status.html (with not working if statement) {%for product in product%} <tbody> <tr> <td>{{product.id}}</td> <td>{{theid}}</td> <td>{{product.product_description}}</td> <td>{{product.product_number}}</td> <td>{{product.product_quantity}}</td> <td>{{product.unit_cost}}</td> <td>{{product.final_cost}}</td> <td>{{product.status}}</td> {% ifequal product.id theid %} <h1>hello</h1> {% else %} <h1>hello2</h1> {% endifequal %} {% if theid %} {% if product.id == theid %} <td><select> <option value="5 Votes Needed">5 Votes Needed</option> <option value="Ready to Order">Ready to Order</option> <option value="Needs to Be Signed">Needs to Be Signed</option> <option value="Ordered">Ordered</option> <option value="Recieved">Recieved</option> </select></td> <td><form class="" action="/changestatus/{{product.id}}" method="post"> {% csrf_token %} <button type="submit" name="edit">Save</button> </form></td> {% endif %} {% else %} <td><form class="" action="/status/{{product.id}}" method="post"> {% csrf_token %} <button type="submit" name="edit">Edit</button> </form></td> {% endif %} </tr> </tbody> {% endfor %} I am confused on why it will neither work with a ifequal tag nor a normal if tag. -
Django - customer filer not reading data
I created a filter: @register.filter(name='increase') def increase_variable(value, increase): data = value + int(increase) return data and use it in html: {% if page_nr != 0 %} <a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a> {% endif %} I tried to print variable page_nr, it works, gives me a correct number and this is how I pass the page_nr to this html: @register.inclusion_tag('post/comment_block.html') def limit_amount_in_a_page(page_nr, topic_id=1, amount=5): topic = get_object_or_404(Topic,id=topic_id) comments = Comment.objects.filter(topic=topic) selected_comments = [] starting_index = page_nr*amount for index in range(starting_index, starting_index + amount): if index >= len(comments): break; selected_comments.append(comments[index]) return { 'topic': topic, 'page_nr': int(page_nr), 'selected_comments': selected_comments, 'amount_comments': comments.all().count(), 'limit_amount_comment': amount, } However, when I run the webpage, it gives me an exception. Here is the traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/post/2/2/ Django Version: 1.11.3 Python Version: 3.6.2 Installed Applications: ['post.apps.PostConfig', 'music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Nutzer\PycharmProjects\selfTry\post\templates\post\comment_block.html, error at line 23 must be str, not int 13 : 14 : <p>{{comment.content}}</p> 15 : </div> 16 : </div> 17 : {% endfor %} 18 : topic id is {{topic.id}} 19 : page nr is {{page_nr}}<br> 20 : {{amount_comments}}<br> 21 : {{limit_amount_comment}}<br> 22 … -
What I can user insted bulk_create in django?
I have Django model which has save() method. In save() method I have to do some manipulation after object is saved. I need to implement function which will read from csv file and save model instances in database. amount of rows can be huge. So I considered bulk_create as good solution in order to make less requests to database. I need to call save method for all objects. But Django documentation says: The model’s save() method will not be called, and the pre_save and post_save signals will not be sent. How can I replace bulk_create and do not increase database requests? -
Display stored value of field for choice in Django admin
I have a Django model with a choice: class Project(models.Model): A = 'A' B = 'B' PROJECT_TYPE_CHOICES = ( (A, 'Plan Type A'), (B, 'Plan Type B'), ) project_type = models.CharField(max_length=1, choices=PROJECT_TYPE_CHOICES) name = models.CharField(max_length=500) def __str__(self): return self.name In the admin list view for this model I want to display the stored value: 'A' or 'B' instead of the "display" value of the choice: 'Plan Type A' or 'Plan Type B'. When my admin.py looks like this: class ProjectAdmin(admin.ModelAdmin): list_display = ('project_type', 'name') pass admin.site.register(Project, ProjectAdmin) I get the display value of the choice (I guess the admin is trying to be helpful and calling get_project_type_choices_display for me or something). How can I force it to return the stored value? -
Generating migration scripts after upgrading django and moving from mysql to postres
We have a django app that is running in production. It used to run django 1.4.3 against a mysql database. We had all our migration scripts using django south. We recently upgraded to django 1.11.6. Along with it we moved the data to a postgres database. The app runs fine, but the migration scripts that are generated using django migrations by using the django models are not fully consistent with the existing schema. Almost all of the differences seem to be in the index names that are generated. What are our options to make the django migrations and the database consistent? How do we go forward with this? Should we generate a new empty database using the django migrations, and migrate the data from the old to the new empty database? I know we can edit the models.py and set the index names manually but that is too cumbersome, we need to edit hundreds of models; is there an easy way to do that? Is there a way I can generate the migration scripts from the existing database, and verify if the models are compatible? -
Django/WeasyPrint: PermissionError: [Errno 13] Permission denied in Win-10 PC
I am working a Django project. I am using Django 1.11.6 with python3.6. I am creating Pdf using weasyprint module. But I got error. This is happened with weasyprint when I run my django project localhost within Windows-10 PC. I want to make pdf file with weasyprint. But When I run my windows 10 PC, I got a permission error. this is views.py file def get_pdf_file(request, customer_id, sys_type): sys_type = customer_id area = "pdf" site_credit = site_credit1 time_now = timezone.now() customers = get_object_or_404(CustomerInfo, pk=customer_id) due_taka_track = customers.duetaka_set.all() if due_taka_track == None: due_taka_track = 0 unpaid_taka = int(customers.customer_price - customers.customer_due_taka_info) due_taka_track = customers.duetaka_set.all() sum_cost_taka = due_taka_track.aggregate( sp=Sum('customer_due')).get('sp', 0) if sum_cost_taka == None: sum_cost_taka = 0 total_paid_taka = sum_cost_taka + customers.customer_due_taka_info payment_status = 'complete' payment_message = ' ' remain_taka='Full Paid ' remain_msg='' if customers.customer_due_taka_info < customers.customer_price: payment_status = 'incomplete' payment_message = 'সম্পূর্ন টাকা পরিষোধ করা হয়নি' remain_msg='টাকা বাকী আছে' baki_ase="পাওনা আছে " remain_taka = customers.customer_price - customers.customer_due_taka_info context = {'customers': customers, 'sys_type': sys_type, 'area': area, 'site_credit': site_credit, 'site_name': 'Moon Telecom', 'sys_type': sys_type, 'due_taka_track': due_taka_track, 'total_paid_taka': total_paid_taka, 'payment_message': payment_message, 'time_now': time_now, 'unpaid_taka': unpaid_taka, 'payment_message': payment_message, 'remain_taka': remain_taka, 'sum_cost_taka': sum_cost_taka, 'remain_msg': remain_msg} from weasyprint import HTML, CSS html_string = render_to_string('shop/pdf_invoice.html', context) with codecs.open('out.html', 'w', … -
Make a cryptical fields in Model
Is it possible to create fields in Django models, which: 1) In Django Form, which renders my Model I have one fields (let it be "secret_key"), where I input very important key which nobody should know or see. 2) In my Django Model that field will be stored as cryptical string (for example, i inputed 12345, it will be stored as *9h^%) 3) When I will need to use that field in my web site, I need to get that field from Model (Model.secret_key) as 12345, not as *9h^% Thank you in advance. -
Apache2 : Limit virtual host to one domain name
i want to do something but i can't find an answer (Maybe i baldy searched). I don't know if it is possible so say me if it's not. I would like to limit an apache virtual host to one and only domain name : bde.yggdrasil.cafe. So that if the user try to access this website using 90.90.3.57 or another domain name it is listed as not existing website. Here is my extra/bde.conf which is included in httpd.conf, you'll understand the problem : <VirtualHost *:80> ServerName bde.yggdrasil.cafe ServerAdmin my@email.fr DocumentRoot /srv/http/bdeweb #Some django config #[...] RewriteEngine on RewriteCond %{SERVER_NAME} =bde.yggdrasil.cafe RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> Listen 443 <VirtualHost *:443> ServerName bde.yggdrasil.cafe ServerAdmin my@email.fr DocumentRoot /srv/http/bdeweb #Some django config #[...] SSLEngine on Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/bde.yggdrasil.cafe/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/bde.yggdrasil.cafe/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> If i use this code and i try to connect to 90.90.3.57 or yggdrasil.cafe using http protocol my request is catched by django which return an error 400 (It is good but not what i want to get). if i connect to bde.yggdrasil.cafe using http it redirect me correctly to https. DNS Redirection I think it can be usefull so i give you my DNS Redirections : yggdrasil.cafe --> 90.90.3.57 bde.yggdrasil.cafe … -
Django - multiple url params with included template
I'm trying to include an template and utilize it in two different views, where the first one gets one url param and the second gets the same plus another one. Inside my included template there is an iteration with a {% url %} tag that I need to pass both params, since the second view needs them, but doing this causes NoReverseMatch when trying to render my first view, probably because it only accepts one param. Is there any way to specifying the second param is optional? Here is my code: urls.py ... url(r'^portfolio/(?P<category_slug>[-\w]+)/$', views.category, name='category'), url(r'^portfolio/(?P<category_slug>[-\w]+)/(?P<album_slug>[-\w]+)/$', views.album, name='album'), ... models.py ... class Album(models.Model): cover = models.ImageField() title = models.CharField(max_length=200, unique=True) description = models.CharField(max_length=200, blank=True) posts = models.ManyToManyField(Post, blank=True) slug = models.SlugField(max_length=200) class Category(models.Model): cover = models.ImageField() title = models.CharField(max_length=200, unique=True) albums = models.ManyToManyField(Album, blank=True) slug = models.SlugField(max_length=200) @receiver(pre_save, sender=Album) @receiver(pre_save, sender=Category) def save_slug(sender, instance, *args, **kwargs): instance.slug = slugify(instance.title) ... views.py ... def index(request): main_categories = Category.objects.filter(...) return render(request, 'index.html', {'main_categories': main_categories}) def category(request, category_slug): try: category_selected = Category.objects.get(slug=category_slug) except Category.DoesNotExist: category_selected = None albums = category_selected.albums.all() return render(request, 'category.html', { 'category_selected': category_selected, 'albums': albums }) def album(request, category_slug, album_slug): try: category_selected = Category.objects.get(slug=category_slug) album_selected = Album.objects.get(slug=album_slug) except Category.DoesNotExist: … -
Django-celery-beat is scheduling interval tasks continuously
I recently followed this tutorial: https://www.codingforentrepreneurs.com/blog/celery-redis-django/ in order to configure django-celery-beat. Everything works fine if I start the beat worker like this: celery -A proj beat -l info however, if I get the beat scheduler to use the django DB, as follows: celery -A proj beat -l info -S django it starts to stream out tasks to the worker continuously (and not based on the specified interval. What could be the issue? -
Cannot assign "<TheModel>": "RelatedModel.the_model" must be a "TheModel" instance
So I have a ForeignKey field on what we'll call RelatedModel, which references what we'll call TheModel. The ORM is completely freaking out when I try to access instances of RelatedModel through an instance of TheModel, example: the_model_instance.related_models.all() ValueError: Cannot assign "<TheModel: 403:>": "RelatedModel.the_model" must be a "TheModel" instance. the_model_instance.related_models.create() ValueError: Cannot assign "<TheModel: 403:>": "RelatedModel.the_model" must be a "TheModel" instance. I can still get instances of RelatedModel via the Manager just fine, but it'd be a shame to lose the convenience/syntax of getting them through the parent. Has anyone encountered this before/ have any ideas?? Also the relationship is pretty standard: class RelatedModel(models.Model): the_model = models.ForeignKey(TheModel, related_name='related_models', null=False) -
Reverse for 'sending_message' not found. 'sending_message' is not a valid view function or pattern name
I have an app called com when I try to access viewing_user template which contains a form with action to another view get the error above this is urls.py app_name = 'com' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<name>[\w\-]+)/$',views.viewing_user, name='viewing_user'), ] this is the views.py from django.shortcuts import render from django.contrib.auth.models import User # Create your views here. RECEIVER_ID = 0 def index(request): return render(request, 'com/index.html',{}) def viewing_user(request, name): #username = request.GET.get('username','') try: User_obj = User.objects.get(username = name) RECEIVER_ID = User_obj.id except User.DoesNotExist: User_obj = None return render(request, 'com/viewing_user.html',{'u':name,'obj':User_obj}) def sending_message(request): form = MessageForm() if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid: message = message_form.save(commit = False) message.date = datetime.date.now() message.from_user = user.id message._to = RECEIVER_ID message.save() else: print form.errors return render(request, 'com/viewing_user.html', {'form':form}) this is the template vieweing_user.html which seems that has a problem in the action of the form <html> {% if obj == None %} <h2>Sorry this user ({{u}}) DoesNotExist</h2> {% else %} <h3>Be honest, and Tellme what you want</h3> <br> <i>{{obj.username}}</i> <form method="post" action="{%url 'com:sending_message' %}"> {%csrf_token%} {% for hidden in form.hidden_fields%} {{hidden}} {%endfor%} {% for visible in form.visible_fields%} {{visible}} {%endfor%} <input type="submit" value='Tell'/> </form> {%endif%} </html> -
django - method only works after the first call when using multi table inheritance
I'm trying to extend the Group and Permission models of django.contrib.auth.models to have some extra functionality. This is what i've done so far: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, ContentType, Permission as Auth_Permission, Group as Auth_Group class Group(Auth_Group): # Inherited attributes from django.contrib.auth.Group # name = models.Charfield() code = models.CharField(max_length=40, unique=True) group = models.OneToOneField(Auth_Group, on_delete=models.CASCADE, parent_link=True, related_name="group_extra" ) description = models.CharField(max_length=400, null=True, blank=True) def __unicode__(self): return self.code class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=40, unique=True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) groups = models.ManyToManyField( Group, verbose_name=_('groups'), blank=True, help_text=_( 'The groups this user belongs to. A user will get all permissions ' 'granted to each of their groups.' ), related_name="user_set", related_query_name="user", ) I'm trying to override the representation of Group in the PermissionsMixin Model, so that when I call, for instance, first_group = <Account>.groups.all()[0], it returns the object as my Group class and I can then call first_group.code (This seems to be working fine). The problem lies when I try to call <Account>.get_all_permissions()... This is what happens: >>> fmt = Account.objects.all()[0] >>> fmt.get_all_permissions() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\projects\Project\App\authentication\models.py", line 158, in get_all_permissions return _user_get_all_permissions(self, obj) File "C:\projects\python3-venv\lib\site-packages\django\contrib\auth\models.py", line 178, in _user_get_all_permissions … -
Django Relation Model
i'm working around with a python test and i'm stuck here. 1) For each Book in the Book list we would like to know how many Submissions were completed. 2) For each Book in the book list we would like to know how many Submissions have Brand data. You should be able to determine if a Profile has brands data by checking to see if the Profile has associated brands ids. My Model class Books(models.Model): name = models.CharField(max_length=128, unique=True) class Submission(models.Model): book = models.ForeignKey(Activation, on_delete=models.CASCADE, related_name='submissions') profile_id = models.UUIDField() class Meta: unique_together = [ ('activation', 'profile_id') ] My Serializer class BooksSerializer(serializers.Serializer): name = serializers.CharField() class ProfileSerializer(serializers.Serializer): id = serializers.CharField(source='_id') brand_ids = serializers.SerializerMethodField() def get_brand_ids(self, obj): return list(obj.brand_ids or []) My Testing code: @classmethod def setUpClass(cls): super().setUpClass() ProfileDocType.reset() book = Books.objects.create(name='Test Book') cls.profile1 = ProfileDocType( meta={'id': str(uuid.uuid4())}, brand_ids=[1, 2], ) cls.profile1.save() cls.profile2 = ProfileDocType( meta={'id': str(uuid.uuid4())}, brand_ids=[], ) cls.profile2.save() book.submissions.create(profile_id=cls.profile1._id) book.submissions.create(profile_id=cls.profile2._id) -
Cron in Docker container parallel with Django
I am currently running a Django web application in a Docker compose setup on Rancher. Because I want the server to run Django management commands periodically I've setup a crontab for it. * * * * * root /usr/local/bin/python /usr/src/app/manage.py updatesomething >> /usr/src/app/cron.log 2>&1 I am using the Dockerfile shown below and as you can see I've tried running the crontab standalone with CMD ["cron", "-f"]. This works fine and runs the command as it should. The idea however is that it can run parallel and trigger management commands on the web app. I've also verified that the crontab file is present. The cron.log file remained empty for over 10 minutes so cron clearly is not doing its job here. Does anyone have a solution to running cron parallel in a python:3 container? Supervisor is not really an option as I have a Python 3 codebase. And I couldn't yet get Circus to work with the database in another container. ############################################################ # Dockerfile to run a Django-based web application # Based on a Python 3 image ############################################################ # Set the base image to use to Python 3 FROM python:3 RUN apt-get update -qq && apt-get install -y -qq --force-yes cron … -
Time format while using django channels
I am using Django channels to update a realtime data on my website. class VisitorBinding(WebsocketBinding): model = VisitorInfo stream = "livelist" fields = ["user_id", "ip","device_type","time_stamp","last_active","active"] @classmethod def group_names(cls, *args, **kwargs): print("grouped"); return ["binding.values"] def has_permission(self, user, action, pk): return True The time i recive in the frontend is 2017-11-07T14:27:37.683Z, where as the actual time rendered through the views is Nov 07, 2017, 07:56 pm How can I make it timezone aware and use the same time formatting? html code: <script> $(function () { var ws_path = "/stream/"; console.log("Connecting to " + ws_path); var webSocketBridge = new channels.WebSocketBridge(); webSocketBridge.connect(ws_path); webSocketBridge.listen(); webSocketBridge.demultiplex('livelist', function(payload, streamName) { // Handle different actions // Handle different actions console.log("a"); if (payload.action == "create") { // Create the new integer value console.log("b"); var content = "<tr id='" + payload.pk + "'><td id=1><a href=\"/action_map/"+payload.pk+"\">" + payload.data.user_id + "</a></td> <td id=2><a href=\"/action_map/"+payload.pk+"\">" + payload.data.ip + "</a></td><td id=3><a href=\"/action_map/"+payload.pk+"\">" + payload.data.device_type + "</a></td> <td id=4><a href=\"/action_map/"+payload.pk+"\">" + payload.data.last_active + "</a></td> <td id=5><a href=\"/action_map/"+payload.pk+"\">" + payload.data.active + "</a></td> </tr>"; $("#table2").prepend(content); } else if (payload.action == "update") { if($('#'+payload.pk).length){ if(payload.data.active==false) { $("tr[id=" + payload.pk + "]").remove(); }else{ $("tr[id=" + payload.pk + "] td[id="+1+"]a").text(payload.data.user_id); $("tr[id=" + payload.pk + "] td[id="+2+"]a").text(payload.data.ip); $("tr[id=" + payload.pk + …