Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I prevent sentry from capturing events for some uncaught exceptions and logging messages?
As recommended by Sentry's docs [1][2] for their new unified python sdk (sentry_sdk), I've configured it with my Django application to capture events on all exceptions or "error"-level logs: import sentry_sdk import logging from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.logging import LoggingIntegration sentry_logging = LoggingIntegration( level=logging.DEBUG, event_level=logging.ERROR ) sentry_sdk.init( dsn="{{sentry_dsn}}", integrations=[DjangoIntegration(), sentry_logging] ) However, since this hooks directly into python's logging module and internal exception handling, it means anything that uses this Django environment will be shipping events to sentry. There are some tasks (such as interactive manage.py commands, or work in the REPL) that need the Django environment, but for which I don't want events created in Sentry. Is there a way to indicate to sentry that I'd like it to not capture events from exceptions or logging calls for the current task? Or a way to temporarily disable it after it's been globally configured? -
django calculated field immediately
what is the best practice to create a calculated field and show immediately in the form? Example: class User(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. price=models.IntegerField(db_column='Price') extra_field=models.DecimalField(db_column='extra_field') ... @register(Test) class TestAdmin(admin.ModelAdmin): readonly_fields=['extra_price'] When I add a new record for test mode, I would like to show in the field extra_price the eval value extra_price=price*0,60. How can I do it? Thanks -
Django Queryset Execution
In Django, does a Queryset execute a new SQL query to the database every time I filter the queryset down or parse a field from an object? For example... if I execute: a = test.objects.all() a2 = a.filter(name='Alex') a3 = a.filter(name='John') a4 = a.filter(name='Steve') Does this sequence send 4 queries to the database? Or does it just send 1, and then handle the filters within Python? I'm trying to make as few queries as possible to the DB for speed purposes... and didn't know if this is actually creating more of a speed bottleneck? Thanks. -
Parallel processing of Session variables in Django
I developed an application in Django with mod_wsgi. My problem is that everything runs normally until two users access the application at the same time. In this situation it happens that: - user A authenticates and processes the selected data; - user B authenticates and starts processing the selected data; - processing for user A stops and user B runs normally; - if user A refresh the page, it will display user B's processing data. In development: - Django views.py communicate with the templates by HttpResponse and JsonResponse; - Templates send data to views.py by ajax requests, using the POST method; - I use session variables in views.py to pass data between requests, using session ['x'] = x My question is if there's any configuration in Django that allows parallel processing of threads for different users, or if there's a way to invoke the values of session variables per user or if there's any other better trick to solve this issue? Thank you. -
Convert Django Queryset to Dict
I'm trying to convert the following queryset into a dictionary that I can then parse via a html template. team | season | type | scope | rank | value a | 2018 | reg | l5 | 5 | 0.118 a | 2018 | reg | l10 | 6 | 1.251 b | 2018 | reg | l5 | 20 | 0.005 b | 2018 | reg | l10 | 15 | 3.058 c | 2018 | reg | l5 | 35 | 0.785 The issue I'm running into is that I need all rows, and I can't filter down to the 1 instance I need. I need to be able to place the values in specific spots in my template. I'd like to turn the query set into a dictionary, at which point I could just reference: team[a].season[2018].type[reg].scope[l5].rank and team[a].season[2018].type[reg].scope[l5].value. But I can't figure out how to do so. Any help would be appreciated! -
How to display category name on article model?
I want to render category field on an article in terms of its name(choice). Currently, it is rendered as an Id. Also, I want to be able to update the article model by entering category name(choice) instead of its Id(I am currently doing this). How can I go about implementing this? This is what I have so far. Models class Category(models.Model): """ Model for Category """ CATEGORY_CHOICES = ( ('Sports', 'Sports'), ('Music', 'Music'), ('Drama', 'Drama'), ('Money', 'Money'), ('Movies', 'Movies'), ('Cars', 'Cars'), ('General', 'General'), ) name = models.CharField(max_length=30, choices=CATEGORY_CHOICES, default='General',null=False, blank=True) def __str__(self): return self.name class Article(models.Model): """ Model for an Article """ title = models.CharField(max_length=255, null=False, blank=False) description = models.TextField(null=False, blank=False) body = models.TextField(null=False, blank=False,) category = models.ForeignKey(Category, on_delete=models.CASCADE) Serializers class ArticleSerializer(serializers.ModelSerializer): """ Serializer for Article. """ class Meta: model = Article fields = ('title','description','body',''category') class CategorySerializer(serializers.ModelSerializer): """ Serializer for Category. """ class Meta: model = Category fields = ('name',) Current output Expected output -
How can I update a json-file with a Django/Heroku structure?
I have set up a Django website https://www.wasjournalistenverdienen.de/ on Heroku and it is going alright. But I have one problem. The autocomplete on this website is based on the easyautocomplete plugin in JS and a predefined JSON-file of German publisher names that is located in the static/-folder of my Django-structure. The idea is that whenever someone enters a name that does not match the predefined keys of the JSON, this new name gets pushed into the JSON and next time someone starts typing in this name, the autocomplete also suggests this new option. This works fine when I check my Django locally. But the problem is that Heroku is ephermal and that any changes to the JSON are not saved. I tried to update the JSON through the IndexView and store the changes on heroku but the updated JSON is seemingly not saved. I also tried using AWS as a workaround, change a JSON there but then the problem becomes that the autocomplete cannot load the JSON as it comes from another server. Has anyone experience with how to create at least temporary files via views.py on heroku and how to also reference to them in JS? -
Google App Engine instances behave differently with the exact same API call
I have a Django application with a DRF API deployed in a flexible environment on Google App Engine. I am using PostgreSQL with the PostGIS extension. After deployment, I have two instances running. I have an API that makes us of GeoDjango to retrieve certain locations from my database. With the exact same API call, it fails about 50% of the time. As I can see from the GCP Console Logs, one of the GAE instance always work while the other systematically returns a 500 with the following error: ImportError: Could not find the GEOS library (tried "geos_c", "GEOS"). Try setting GEOS_LIBRARY_PATH in your settings. However, the GEOS library is installed (see Dockerfile below). Any idea on why the two instances behave differently and what can I do to prevent that? Dockerfile # [START dockerfile] FROM gcr.io/google_appengine/python # Install libraries RUN apt-get update && apt-get install -y \ binutils \ libproj-dev \ gdal-bin \ python-gdal # Change the -p argument to use Python 2.7 if desired. RUN virtualenv /env -p python3.6 # Set virtualenv environment variables. This is equivalent to running # source /env/bin/activate. ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH ADD requirements.txt /app/ RUN pip install -r requirements.txt ADD . … -
Django,getting only unique values from related object
I wish I could render in my website list of most used tags,which I do.The problem is,displayed tags often repeat and I'm sure it would be much better if only unique tags were displayed. In my model I have writen method unique_tags class ArticleTag(models.Model): article = models.ForeignKey('ep.Article', on_delete=models.CASCADE, related_name='tags') tag = models.ForeignKey('ep.Tag', on_delete=models.CASCADE) def unique_tags(self): return self.objects.values_list('tag').distinct() and when I tested it in python shell it works fine.But it doesnt render any tag.My template looks like this: <div class="widget-tags"> <ul> {% for prev_article in object.articles.all %} {% for article_tag in prev_article.article.tags.all.unique_tags %} <li><a href="#">{{article_tag.tag.verbose_name}}</a></li> {% endfor %} {% endfor %} </ul> </div> Where object is from model that makes relation with Article table and Field table,so with object.articles.all I've got all instances of articles that are related to specific field.I use detail view in my views. So,my first question is,Is this valid approach? I mean,adding new method in model class, or perhaps I should add this in views?.Also I still not comfortable with django template language so maybe there is problem.And I know there is this filter in template like {{ some_object | function}} but I've read that it is good practice to keep as little logic in template as … -
Django connecting to postgres password authentication failed
I'm developing a django application which has been running on my development server (a Raspberry Pi running Raspbian with postgresql 9.6) and I'm now starting to try running it in what will be its production environment (an AWS instance running ubuntu with postgresql 10). While setting up the first user of my site, using a lightly modified version of django's standard user signup page (I've added one more field), I get an error: FATAL: password authentication failed for user "makersuser" I've set the password at the postgres prompt again just to be sure, temporarily replaced the call to decouple in settings.py that reads the password from .env with a hardcoded password (as a string literal), so I can be really sure it is the same password that I set on the postgres command line, I've set the password expiry for that user to infinity (as in Postgres password authentication fails), and I've set the authentication to md5 as mentioned in Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails My pg_hba.conf now looks like this: # Database administrative login by Unix domain socket local all postgres peer # TYPE DATABASE USER ADDRESS METHOD … -
How to get all items from django-admin panel?
I have a html page where is <body> <h8> MY BLOGS </h8> <ul> {% for bl in all_blogs %} <li>{{bl.header}}</li> {% endfor %} </ul> In "ul" it must show all items from all_blogs what is def list_blogs(request): all_blogs = Blog.objects.all return render(request, 'blogs.html', {'blogs': all_blogs}) and Blog is class Blog(models.Model): header = models.CharField(max_length=100) data = models.CharField(max_length=500) def __str__(self): return self.header and the output of the html page is just "MY BLOG" without any blogs in it, in my admin panel I have 4 blogs, I tried to print for bl in all_blogs: print(str(bl)) but it doesnt work, I also checked local db for blogs, and it was fine. -
Customizing Wagtail Streamfield
Can anyone provide the code necessary to create the Wagtail Streamfield options that are previewed on the wagtail.io website front page? https://media.wagtail.io/images/w1_5pmaP1U.original.width-1600.png Specifically, I'm interested in Aligned Image, Wide Image, Bustout, Raw HTML, and Markdown. -
Why post.post isnt being displayed (Post)
Hi I am trying to display post.post for when a user posts something {{ post.post}}, it worked previously but now it doesn't. The name of the user and date show, and the post is submitting.. but no success with post.post. What is actually happening is posts are being submitted under the latest post.post (highlighted it in output). TIA html: {% extends 'base.html' %} {% block body%} <div class="container"> <h1>Home</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> <h2>{{ text }}</h2> {% for post in posts %} <h1>{{ post.post }}</h1> <p>Posted by <b>{{ post.user.get_full_name}}</b> on {{ post.date }}</p> {% endfor %} </div> {% endblock %} models.py: class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) views.py: class HomeView(TemplateView): template_name = ('home/home.html') def get(self, request): form = HomeForm() posts = Post.objects.all() args = {'form': form, 'posts': posts} return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['Post'] form = HomeForm() return redirect('home:home') args = {'form': form, 'text': text} return render(request, self.template_name, args) output: gdggdg Posted by john wick on Oct. 11, 2018, 6:56 p.m. yrterteet Posted by john wick on Oct. 11, 2018, 6:56 … -
Ajax call is not going to view function django
Hi I am sending request to a django view but its not accessing view function . Both are in same app . And I am using debugging tool so I tried to debug but on my view no call is received and My ajax call code is like this $.ajax({ url: '/edit_profile/', type: 'get', // This is the default though, you don't actually need to always mention it success: function(data) { alert(data); }, failure: function(data) { alert('Got an error dude'); } }); url.py path('edit_profile/', views.edit_profile , name="edit_profile"), view.py def edit_profile(request): print(request) print(request) if request.method == 'POST': return render(request, 'authenticate/edit_profile.html', context) I am debugging but call is not received in this view function . -
Django + ajax like button. On ListView, how to make each like button 'unique'
I set up this like button in my post detail view and it works pretty well: <script type="text/javascript"> function toggleLike(){ $.ajax({ url: "{% url 'photo_blog-post_like_api' post.id %}", data: {}, dataType: "json", success: function(data) { $("#likeCount").html(data.like_count + ' likes'); $('#ImageElement').replaceWith(data.img); console.log(data); } }); }; </script> Basically everytime the button is pressed, the data-liked toggles between true and false and the #ImageElement in my html toggles between the image for a liked post and an unliked post. I've tried to use this same code on the homepage which lists posts by saying: {% for post in posts %} {{post.author}} ...................... <a class="ImageElement"><a> {% endfor %} It works for the first post, but not the rest. When the second post is 'liked' the image for the first post is toggled. The console says the values are changing, but since the #ImageElement is repeated, the first one gets replaced, and not the one that is getting liked. How can I create a unique #ImageElemnt for every post?/There's probably a better way to do this? -
django.db.utils.ProgrammingError: permission denied: "RI_ConstraintTrigger_a_25437" is a system trigger
I am trying to disable the triggers for one of my PostgreSQL table using the following code def disable_triggers(self): with connection.cursor() as cursor: cursor.execute('ALTER TABLE "frontend_awsregions" DISABLE TRIGGER ALL;') But this is giving me following error ... ... return self.cursor.execute(sql) django.db.utils.ProgrammingError: permission denied: "RI_ConstraintTrigger_a_25437" is a system trigger when I execute the same query in PGAdmin, its working properly -
DeleteView marking inactive instead deleting?
Is there some elegant solution to using Django's DeleteView but instead actually deleting the objects, marking them inactive? I like the simplicity of the DeleteView but would want to keep the data at the backend, instead of removing it. -
Bypass decorator with mock in django test
I am trying to write a simple test however my views are decorated with nested user_passes_test statements. They check things like a stripe subscription and is_authenticated. I have found various posts such as this which address how to bypass a decorator with patch but I can't quite work out how to integrate everything together. tests.py @patch('dashboard.views.authorised_base_user_checks', lambda func: func) def test_dashboard_root_exists(self): response = self.client.get('/dashboard/') self.assertEqual(200, response.status_code) decorator in views def authorised_base_user_checks(view_func): decorated_view_func = login_required(user_active(subscriber_exists(subscriber_valid(view_func)))) return decorated_view_func views.py @authorised_base_user_checks def IndexView(request): ... The above still fails to pass through the decorator. Thanks! -
How can I resolve custom fields for django models using django_graphene?
Looking at graphene_django, I see they have a bunch of resolvers picking up django model fields mapping them to graphene types. I have a subclass of JSONField I'd also like to be picked up. : # models class Recipe(models.Model): name = models.CharField(max_length=100) instructions = models.TextField() ingredients = models.ManyToManyField( Ingredient, related_name='recipes' ) custom_field = JSONFieldSubclass(....) # schema class RecipeType(DjangoObjectType): class Meta: model = Recipe custom_field = ??? I know I could write a separate field and resolver pair for a Query, but I'd prefer it to be available as part of the schema for that model. What I realize I could do: class RecipeQuery: custom_field = graphene.JSONString(id=graphene.ID(required=True)) def resolve_custom_field(self, info, **kwargs): id = kwargs.get('id') instance = get_item_by_id(id) return instance.custom_field.to_json() But -- this means a separate round trip, to get the id then get the custom_field for that item, right? Is there a way I could have it seen as part of the RecipeType schema? -
Django insert with multiple nested models performance
I have following models definition: class Workflow(models.Model): name = models.CharField(max_length=255) class Step(models.Model): workflow = models.ForeignKey(Section, on_delete=models.CASCADE, related_name='steps') title = models.CharField(max_length=255) class Section(models.Model): body = models.CharField(max_length=255) step = models.ForeignKey(Section, on_delete=models.CASCADE, related_name='sections') class Question(models.Model): description = models.CharField(max_length=255) section = models.ForeignKey(Section, on_delete=models.CASCADE, related_name='questions') class Option(models.Model): set_fail = models.BooleanField() question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='options') class Action(models.Model): yes_no = models.BooleanField() option = models.ForeignKey(Option, on_delete=models.CASCADE, related_name='actions') # Workflow -> Step -> Section -> Question -> Option -> Action And I have following body sent from client for inserting data (request body is big, I can't paste it here) https://jsoneditoronline.org/?id=e970abc01b2a489c9933464867d11eaf You can see the data is big and each level has multiple records, then performing insert really takes time. I am currently applying this inserting approach: class WorkflowUpdateSerializer(serializers.Serializer): def update(self, workflow, data): self.update_steps(workflow, data) # data is request JSON body def update_steps(self, workflow, steps): step_clones = [{key: value for key, value in step.items() if key != 'sections'} for step in steps] step_instances = Step.objects.bulk_create( [Step(workflow=workflow, **step) for step in step_clones]) for index, step in enumerate(steps): self.update_sections(step_instances[index], step.pop('sections')) def update_sections(self, step, sections): section_clones = [{key: value for key, value in section.items() if key != 'questions'} for section in sections] section_instances = Section.objects.bulk_create( [Section(step=step, **section) for section in section_clones]) … -
How do i temporarily disable db integrity constraints in django - postgresql
I am writing a Django command to seed an existing table, I need to truncate the table before seeding, but there are foreign key constraints on that table. because of that, I am getting django.db.utils.IntegrityError while truncating the table, How do I turn the Foreign Key Checks off temporarily in Django? I saw SET FOREIGN KEY CHECK = 0 but don't know where to put them :( The Django Command class: class Command(BaseCommand): help = "Command to seed the aws regions" regions = [ { 'name': 'Us East (N. Virginia)', 'region': 'us-east-1', }, { 'name': 'US West (Oregon)', 'region': 'us-west-2', }, { 'name': 'EU (Ireland)', 'region': 'eu-west-1', }, ] def handle(self, *args, **options): self.stdout.write('seeding regions...') AwsRegions.objects.all().delete() # this is where i get errors for name, region in self.regions: self.stdout.write(region) AwsRegions.objects.create(name, region) self.stdout.write('done seeding regions') -
Django - error_403() got an unexpected keyword argument 'exception'
When the user is not allowed to see the contents of the instance, when the PermissionDenied exception was thrown, instead of forwarding it to the 404.html template, it has an error. DetailView: class OccurrenceDetail(OccurrenceModel, BaseDetailViewWithLogin): permission_required = ('occurrences.see_occurrence') def get_object(self, queryset=None): perm = self.request.user.has_perm(self.permission_required) obj = super(OccurrenceDetail, self).get_object(queryset=queryset) if not perm: raise PermissionDenied() return obj Urls: handler403 = 'apps_core.core.views.error_403' Views: def error_403(request): data = {} return render(request,'errors/403.html', data) -
Django filter on multiple array list values
I have to do a filter according to 3 fields , Doctor , Client and Branch each one of them is an array of ids so i want to filter by these ids , i want to filter according to those elements all My django view code: my_dict = {'BranchId': [0,1,2,4],'DoctorId' : [2,4,5] , 'ClientId' : [2,3,5]} Branches = my_dict['BranchId'] Doctors = my_dict['DoctorId'] Clients = my_dict['ClientId'] query = Event.objects.all().filter(e_d__in = Doctors , e_b__in= Branches , e_c__in = Clients) print(query) -
Django annotate difference of foreign keys
On Django with a mysql db class Price(models.Model): date = models.DateTimeField(auto_now_add=True) value = models.DecimalField(...) stock = models.ForeignKey('Stock', related_name='price') class Stock(models.Model): pass I want to annotate to each Stock, the difference of price of the last hour in a single Query. It is possible to do such thing? Otherwise, how can i do it using the least amount of querys? I've already read this question, but it's not what i'm looking for. -
How to combine default fields in form on Django admin page
I have 3 fields in model.py in two of them I put random number def random1(): #return first random number def random2(): #return second random number class Shakf(models.Model): random1 = models.CharField(max_length=10, default=random1) random2 = models.CharField(max_length=10, default=random2) How do I make a third field which would combine those two? For example: random1 = 3333 random1 = 5555 third_field = "3333 | 5555" There is a important condition: "after reloading admin page they have to change". If I do like that: third_field = models.CharField(max_length=10, default=random1 + " | " + random2) then I got different random1 numbers and different random2 numbers if I call function then after reload page I got the same numbers (without changing) .