Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 + … -
Django count of each subgroup
Imagine I've the following models: class User(): pass class Category(): title = CharField class Photo(): owner = models.ForeignKey(User, related_name='photos') category = models.ForeignKey(Category) published = models.BooleanField() I want to have the number of published photos users posted for each category for each user. I tried something like: User.objects.annotate(num_entries=Count( Case(When(photos_published=True, then=1), output_field=IntegerField())) ) but couldn't find how to group this by category.. The result I want to get is something like this: user0: 5 for category1 3 for category2 user4: 2 for category2 I can resort to raw sql if this doesn't work, since there are millions of users I don't want to loop over them. I am using PostgreSQL. -
views from another app doesnt work in django?
I have two apps 1. posts 2. boards. I need to create url link in boards template to view from posts app. my root urls.py: urlpatterns = [ url(r'^', include('boards.urls')), url(r'^', include('posts.urls', namespace="posts")), ] posts.urls: # -*- coding: utf-8 -*- from django.conf.urls import include, url from views import ( listofposts, create_post, detail, update_post, category, ) urlpatterns = [ url(r'^create/', create_post , name='create_post'), url(r'^category/(?P<slug>[-\w]+)/$', category, name='category'), url(r'^(?P<slug>[-\w]+)/edit/$', update_post, name = 'update_post'), url(r'^(?P<slug>[-\w]+)/$', detail, name = 'detail'), url(r'^$', listofposts , name='listofpost'), ] Boards template link <a class="navbar-brand" href="{% url 'posts:listofposts' %}">Home</a> I got the mistake : Exception Value: Reverse for 'listofposts' not found. 'listofposts' is not a valid view function or pattern name. -
Sum of fields for filtered queryset using django_filters
I have the following view class AuthorList(FilterView): model = Author filterset_class = AuthorFilter context_object_name = 'authors' In the template, one of the field is {{ author.value }}, which is an integer. What I would like to do is to show the sum of all {{ author.value }} in my template, but in a dynamic way (if some filters are used, the sum is updated with the current Queryset). I have tried adding extra context with get_context_data but I couldn't find out how to make it in a dynamic way. -
django + nginx https redirect shows (414 Request-URI Too Large)
I am trying to solve nginx redirect to https but when I use www.ozkandurakoglu.com I am getting 414 Request-URI Too Large error. Here is my settings for nginx: upstream ozkan_server { server unix:/home/ytsejam/public_html/ozkansimple/run/gunicorn.sock fail_timeout=10s; } server { listen 80; server_name ozkandurakoglu.com www.ozkandurakoglu.com; return 301 $scheme:https://ozkandurakoglu.com$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; ssl on; ssl_certificate /etc/letsencrypt/live/ozkandurakoglu.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/ozkandurakoglu.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/ozkandurakoglu.com/chain.pem; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets off; ssl_prefer_server_ciphers on; add_header Strict-Transport-Security max-age=15768000; ssl_stapling on; ssl_stapling_verify on; server_name www.ozkandurakoglu.com; return 301 $scheme:https://ozkandurakoglu.com$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; ssl on; ssl_certificate /etc/letsencrypt/live/ozkandurakoglu.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/ozkandurakoglu.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/ozkandurakoglu.com/chain.pem; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets off; ssl_prefer_server_ciphers on; add_header Strict-Transport-Security max-age=15768000; ssl_stapling on; ssl_stapling_verify on; server_name www.ozkandurakoglu.com ozkandurakoglu.com; client_max_body_size 4G; root /home/ytsejam/public_html/ozkansimple/; access_log /home/ytsejam/public_html/ozkansimple/logs/nginx-access.log; error_log /home/ytsejam/public_html/ozkansimple/logs/nginx-error.log warn; large_client_header_buffers 6 16k; ... } can you help me ? Thanks -
request.user is not letting me make changes to the current user?
In my view function, I'm trying to make 2 modifications to the current user; consider him a premium subscriber by marking model field is_premium_subscriber as True and adding him to a group named Premium Agents. However the changes don't seem to be registering in my views.py! Here is my code: def payment_response(request): new_charge = PremiumSubscriptionCharge() if request.method == "POST": ... Some code here try: ... lots of code here new_charge.agent = request.user # This line is working fine, meaning request.user is properly assigned to the current user request.user.is_premium_subscriber = True # This is not working, is_premium_subscriber is still false after the request premium_agent_group = Group.objects.get(name='Premium Agents') premium_agent_group.user_set.add(request.user) # This is not working either, the current user does not get added to the group. request.user.save() # I don't know if this is necessary, but I put it here just in case. except stripe.error.CardError as ce: ... some code else: ... some code My user model for reference. I created a custom User model by inheriting AbstractUser... could this have caused the issue? class Agent(AbstractUser): is_premium_subscriber = models.BooleanField(default=False) -
Get the matched url pattern on Django
I am working on an existing Django application where there are many url patterns with same name. For example these three url patterns have same url name / view method: url(r'^create/type/(?P<negotiation_type>.*)/(?P<infomodel_uuid>.*)/$', 'setup_negotiation', name='setup_negotiation'), url(r'^create/type/(?P<negotiation_type>.*)/$', 'setup_negotiation', name='setup_negotiation'), url(r'^create/(?P<processmodel_uuid>.*)/$', 'setup_negotiation', name='setup_negotiation'), I want to know which pattern current url is matched with. I can get named url from resolve(request.path_info).url_name but what I need is to get the matched pattern string '^create/(?P<processmodel_uuid>.*)/$' or something like that. -
Website not sending any data : ERR_EMPTY_RESPONSE unreliably.
I have a (Https) website running with django 1.17.11, nginx 1.4.6 and gunicorn 19.7.6. Yesterday my website seemed to be running correctly, but since today it's displaying an error. It is inconsistent but this is what appears to be happening. First time, the site will load without problem. Upon refresh, or while navigating to another page on the website, the site will either load or display {my-site} didn’t send any data. ERR_EMPTY_RESPONSE Once a page display ERR_EMPTY_RESPONSE once, it will consistently display this error. Even though the homepage might display the error, a different page could still be working. (E.g. site.com doesn't work, but site.com/a does work) This is happening in Chrome and Firefox (haven't tested in other browsers) This happens on windows 10, Ubuntu 14.04 and Android Oreo (only ones tested) There do not appear to be any additional errors, nor anything related reported in the error logs. Does anybody know what this could be related to? Or any additional tests I could run to try to get at least an consistent error? Any possible fixes?