Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Editing the values of two tables from one view. Django
In the Parent table, I have many objects. The user has a form in which he can choose one of the Parent objects. It looks like this: class ChildForm(forms.ModelForm): class Meta: model = OrderingMassage fields = ('parent', 'name') Now I would like to get for each object 'parent' selected by the user in the Parent table, the 'on_off button' value changed to False. How can I recover it? What can I use? Can I do it in my view using one form? For example: models.py class Parent(models.Model): name = models.CharField(max_length=15) on_off_button = models.BooleanField(deflaut=True) class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name = models.CharField(max_length=15) views.py if request.method == 'POST' and 'child_btn' in request.POST: child_form = ChildForm(request.POST) if child_form.is_valid(): child = child_form.save(commit=False) name = child_form.cleaned_data['name'] parent = child_form.cleaned_data['parent'] # Can I add an element here that will change the value parent.id on False child.name = name child.parent = parent child.save() else: child_form = ChildForm() Any help will be appreciated. -
show API Reviews from our site to other site
Is it possible to show the reviews given on my site for a particular brand by customers to that brand's official site? I am giving one example to clear my question. Suppose any customer has given review about nike on my website( Brandact) and i want to show this review to nike's official website(through the website Brandact). If yes,Can someone please help me in solving this problem. Thanks in Advance. -
Load All Data in Table from Django Models run queries from it
I would like to know how can we run queries from data after loading entirely in Memory to prevent it from hitting database everytime This is my Model class empdb(models.Model): empid = models.CharField(max_length=8,primary_key=True) empname = models.CharField(max_length=255) empdept = models.CharField(max_length=255) class Meta: ordering = ('empid',) def __str__(self): return self.empid This is what I am trying record = empdb.objects.all() ' This will load all data in "record" Now How to read from it and extract Data based on our Query I am trying below query to find out which Employees are part of HR Department dataset=backuprecord.filter(empdept='HR') print(dataset) Now this is where I am getting stuck. The Output I get is fine and it does list the Data I get , but its in below form <QuerySet [<empid: 10010>,<empid: 10121>,<empid: 12235>,<empid: 18110>]> I want to takeout the empid and empname from above queryset How do I do so ? What I want is data in below variables for i in <length of query set> foundempid[i] = ''' The Employee ID from the queryset Line foundempname[i] = ''' The Employee Name Any Help with this will be greatly appreciated. -
Polymorphicc models serializer
Im using a Polymorphic model for setting up notifications: My models: class Notification(PolymorphicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_by = models.ForeignKey(ElsUser, on_delete=models.CASCADE, default=None, related_name="creatednotifications") created_on = models.DateTimeField(default=timezone.now) created_for = models.ForeignKey(ElsUser, on_delete=models.CASCADE, default=None, related_name="receivednotifications") read = models.DateTimeField(default=None, null=True, blank=True) message = models.CharField(default=None, blank=True, null=True, max_length=800) @property def total(self): return self.objects.filter(created_for=self.request.user) class WorkflowNotification(Notification): # permission_transition = models.ForeignKey(WorkflowStatePermissionTransition, on_delete=models.CASCADE) action = models.ForeignKey(UserAction, on_delete=models.CASCADE) Currently i have just one model WorkFlowNotification inheriting from the Polymorphic model,but many would be there in the future. Im trying to get the count(total) of notifications for the logged in user in the API ..total is given as property field to help in the same my serializer: class NotificationSerializer(serializers.ModelSerializer): total = serializers.Field() class Meta: model = Notification read_only_fields = ('id',) fields = ('id','total') In the view: class NotificationsMeta(generics.ListAPIView): serializer_class = NotificationSerializer def get_queryset(self): queryset = Notification.objects.filter(created_for=self.request.user) return queryset When i try to run the server it shows: Got AttributeError when attempting to get a value for field `total` on serializer `NotificationSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `WorkflowNotification` instance. Original exception text was: Manager isn't accessible via WorkflowNotification instances. -
django times out when accessing a specific object instance
I'm trying to troubleshoot a production issue where django times out when accessing a specific model instance but not other instances of the same class. My production environment is Heroku using gunicorn with postgres as the database. Heroku is showing the following error in the logs (took out the sensitive bits): Feb 21 20:26:20 [heroku-app-name] heroku/router: at=error code=H12 desc="Request timeout" method=GET path="[url-path]" host=[my-host] request_id=[request-id] fwd="[fwd-stuff]" dyno=web.1 connect=0ms service=30000ms status=503 bytes=0 protocol=http Feb 21 20:26:21 [heroku-app-name] app/web.1: [2019-02-22 04:26:21 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:14) Feb 21 20:26:21 [heroku-app-name] app/web.1: [2019-02-22 04:26:21 +0000] [14] [INFO] Worker exiting (pid: 14) Feb 21 20:26:21 [heroku-app-name] app/web.1: [2019-02-22 04:26:21 +0000] [20] [INFO] Booting worker with pid: 20 The specific url I'm accessing is simply displaying the model instance via the generic.DetailView class (simplified for brevity): class DetailView(generic.DetailView): model = MyModel template_name = 'detail_view.html' My production database only has a few dozen entries (still a new site) so as far as I can tell, I'm not actually overwhelming the server. At this point, I'm not even sure where to go in order to figure out what's actually going wrong. The server times out EVERY time I access one specific instance of MyModel but works fine … -
django-tables2: LinkColumn: detail view links not rendering
I'm having difficulty in generating detail view links. Could somebody provide me with some insight as to where I'm going wrong. models.py class Company(models.Model): STATE_CHOICES = ( ('nsw', 'NSW'), ('nt', 'NT'), ('qld', 'QLD'), ('vic', 'VIC'), ('wa', 'WA'), ('tas', 'TAS'), ('act', 'ACT'), ('sa', 'SA') ) company_name = models.CharField(max_length = 100) client_code = models.CharField(max_length = 100) company_state = models.CharField(max_length = 3,choices = STATE_CHOICES,) def __str__(self): return self.company_name def get_absolute_url(self): return reverse('company_list') urls.py from django.urls import path from . import views urlpatterns = [ path('', views.CompanyList.as_view(), name='company_list'), path('<int:pk>/', views.CompanyDetailView.as_view(), name='company_detail'), path('new/', views.CompanyCreateView.as_view(), name='company_new'), ] views.py import django_tables2 as tables from django_tables2 import SingleTableView from django_tables2.utils import A class CompanyTable(tables.Table): class Meta: model = Company attrs = {'class': 'mytable table table-striped table-bordered table-hover'} company_name = tables.LinkColumn('company_detail', args=[A('pk')]) orderable = False class CompanyList(SingleTableView): model = Company table_class = CompanyTable class CompanyDetailView(DetailView): model = Company What am I missing here? -
Django: How can I combine 2 formsets as one so as to display as one inline table (of course with pagination) in template
say I have 3 models Groups ,Answers, Questions (Group as foreignkey and models are broken for normalization). I have created corresponding formssets for Answers and Questions for these models. on selection of a group, my goal is to display related Answers and Questions in a inline Table on form something like this: something like this I am able to get formsets on Template and able to display them in separate sections but not able to display them as one one table (Dont want to do this using HTML-JS). Is there anyway we can pass answer, question formsets as one context object so that i can be displayed as one table on template? Note: there may be 5 questions but only 3 answers for a group or viseversa. Also it would be nice to add pagination to this inline table( or formsets) #urls.py from django.conf.urls import url from .views import lists, load_questions from django.urls import path urlpatterns = [ url(r'lists', lists, name="lists"), path('ajax/load_questions/', load_questions, name='load_questions'), ] I have till now #models.py from django.db import models from django.utils.timezone import now class Groups(models.Model): class Meta: verbose_name_plural = "Groups" group = models.CharField(max_length=30) group_description = models.CharField(max_length=4000,default=None,null=True) group_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.group def … -
Atom Django-Templates not Highlighting {{}}
I recently installed the Django-templates package for Atom, but it doesn't seem to be highlighting variables in {{}}. Any help is appreciated. -
Django Passing Context
I understand the code below will not work but I am hoping that it will give an understanding of what I am trying to accomplish. def FilterTrackView(request,operation): if operation == 'today': raceDay = RaceDay.objects.filter(raceDayDate='2019-02-21') for race in raceDay: tracks += Track.objects.filter(id=race.raceDayVenue_id).values() return render(request, 'tracks/tracklist.html', {'tracks': tracks}) -
What is the best way to keep track on tables or some data for analytics?
For an instance, take django model classes as below. So, now the question is that how can I efficiently implement analytics for generating number of product sales per day, number of sales per month, number of profit by day and so on ? One Possible solution is on every sales update counts of that particular day. But if I have very large customer base (i.e 1M customer and 500 sales per hour). So is there any better way to achieve this? These schemas are just for reference only class Product(models.Model): name = models.CharField(max_length=20) category = models.ManyToManyField("Category", null=True) ... ... class Sales(models.Model): product = models.ForeignKey("Product") price = models.DecimalField(max_digits=20) timestamp = models.DateTimeField() ... ... -
How to add russian language support to Django CMS?
I've installed Django CMS following guide http://docs.django-cms.org/en/latest/introduction/01-install.html , but see only english language in interface. I've looked at docs http://docs.django-cms.org/en/latest/reference/configuration.html#i18n-l10n-reference , added ru to LANGUAGES and CMS_LANGUAGES variables in settings.py, russian languaged appeared in interface selector, but when I select it, it goes back to english and shows "[15/Feb/2019 15:06:19] "GET /ru/ HTTP/1.0" 302 0" in log. Here is language related parts of my settings.py: ... LANGUAGE_CODE = 'ru' ... LANGUAGES = ( ## Customize this ('en', gettext('en')), ('ru', gettext('ru')) ) CMS_LANGUAGES = { ## Customize this 1: [ { 'code': 'en', 'name': gettext('en'), 'redirect_on_fallback': True, 'public': True, 'hide_untranslated': False, }, { 'code': 'ru', 'name': gettext('ru'), 'fallbacks': ['en'], 'public': True, }, ], 'default': { 'redirect_on_fallback': True, 'public': True, 'hide_untranslated': False, }, } ... Could anybody help me to translate my Django CMS installation? -
Django how to join two query sets so that they are sequentially serialized
Suppose I have a model call MyModel defined as below class MyModel(models.Model): fk = models.ForeignKey('AnotherModel') rank = models.FloatField() I wish to create a query set for serialization so that instances with instance.fk.other_fk_id in some set comes before the ones that don't and then sorted by decreasing rank. So I wish to join a = MyModel.objects.filter(fk__other_fk_id__in=some_set).order_by('-rank') and b = MyModel.objects.filter(fk__other_fk_id__in=some_set).order_by('-rank') sequentially so that a comes before b when it's handed to the serializers. Any idea on how to achieve this functionality efficiently? (let's say there is 50 instances in a and 200000 instances in b so I cannot directly concat those two as lists). -
Is it better to make a file available for download in static/webpack_bundles or stored in database and have a download endpoint?
The file is an application form that is supposed to be available for everyone. What are the advantages/disadvantage of download from static? -
Adding static text in Admin
Say in this Figure 11-1: https://djangobook.com/managing-users-admin/ I would like to add some static text under 'Select user to change' I have tried this (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#other-methods) which seems to be the right answer and I followed this example customizing django admin ChangeForm template / adding custom content But neither work for me... The following are snippets of my code: admin.py: class HighscoreAdmin(admin.ModelAdmin): change_form_template = 'admin/my_app/change_form.html' def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['static_text'] = 'Some static text' return super(HighscoreAdmin, self).change_view( request, object_id, form_url, extra_context=extra_context, ) ... change_form.html: {% extends "admin/change_form.html" %} {% block form_top %} {{ static_text }} {% endblock %} -
What are the rules, laws or anything related to using geo-location?
This may or may not be a programming question but I'm sure it's related to development. I'm in the process of pre designing a web app and what technologies it will use, what services it will offer, etc etc. The most crucial is the geo location. In my web app, I will require businesses to register and input their business address when they register. The users of the web app, as the home/start page will see a map with those businesses and with option filters. For example: If the businesses are fast food restaurants, the filters will be: burgers, pizza, sushi, pancakes etc. So if a user is hungry he will be able to instantly find the closest fast food to him. Now the development questions: 1) Is there any available API where I can implement maps on my app? 2) What about rules, laws, is it legal to ask businesses and users geo location? I live in Greece and I'm an Estonian e-Resident, so I will be covered by Estonian law. 3) Is the API free? The web application will be cross platform developed and will be developed under the following technologies: HTML5, CSS3, JavaScript, BootStrap 4, ReAct, ReAct … -
Create an extra column on a Django queryset based on a JSON
this is a very specific problem. My model has a JSON called 'content', in that JSON there's a key called 'name'. My objective is to get the name into a new column to the queryset, but that seems hard to do, because the content__name, can not exist in some cases, and if you simply select it using extra, it will throw an exception. queryset = queryset.extra(select={'_content_name': "SELECT content->>'name'"}) The final result needs to include both the ones that contain the name and those who don't, the ones that don't could be replaced by and character like '-' or be completely empty. The final result needs to be a queryset, not a RawQueryset. Things I tried and didn't quite work: Using filtering before and trying to union with the difference of the original, can't union because of the queryset has different columns quantity or columns have different types. You can't union content__name that is a JSON into the same column as content->>'name' that is a string. qs = queryset.filter(~Q(content__name__iexact='')).values_list('content__name') qs2 = queryset.difference(qs).extra(select={'_item_name': "SELECT content->>'name'"}).values_list('_item_name') queryset = qs.union(qs2) In this case, it could also say that _item_name is not a valid column on the values_list even after using extra to create it. … -
Django signed cookie session storage and SESSION_COOKIE_AGE
As per the Django documentation, signed cookie session storage is vulnerable to a replay attack: Note also that while the MAC can guarantee the authenticity of the data (that it was generated by your site, and not someone else), and the integrity of the data (that it is all there and correct), it cannot guarantee freshness i.e. that you are being sent back the last thing you sent to the client. This means that for some uses of session data, the cookie backend might open you up to replay attacks. Unlike other session backends which keep a server-side record of each session and invalidate it when a user logs out, cookie-based sessions are not invalidated when a user logs out. Thus if an attacker steals a user’s cookie, they can use that cookie to login as that user even if the user logs out. Cookies will only be detected as ‘stale’ if they are older than your SESSION_COOKIE_AGE. Does this mean that: We are relying on the client-side expiration of cookies to ensure that the session data is destroyed (thus a replay attack is still possible if the cookie contents are captured before the cookie is removed by the browser), … -
Could not resolve URL for hyperlinked relationship using view name "user-detail". Django Rest Api
I am building an API using Django Rest Framework for my car-sharing app. This is my first Django project, so i used this tutorial https://codeburst.io/building-an-api-with-django-rest-framework-and-class-based-views-75b369b30396. My /users works fine, but when im trying to go to /races, this error appears: ImproperlyConfigured at /races/ Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I've tried a lot of methods that were posted in other similar questions but none of them worked.Also, I've used the path method which is not present in any of the other questions. The traceback shows more than one error, but im not sure which one causes others: Traceback (most recent call last): api_1 | File "/usr/local/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup api_1 | current = current[bit] api_1 | TypeError: 'BoundField' object is not subscriptable api_1 | api_1 | During handling of the above exception, another exception occurred: api_1 | api_1 | Traceback (most recent call last): api_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/relations.py", line 400, in to_representation api_1 | url = self.get_url(value, self.view_name, request, format) api_1 | File "/usr/local/lib/python3.7/site-packages/rest_framework/relations.py", line 338, in get_url api_1 | return self.reverse(view_name, kwargs=kwargs, … -
Django Connect to remote database using ssh and pem file
I can access database by SSH to some aws instance using pem file. How do i connect the django to that postgres database. Django Database connect has sslkey etc in options. But couldn't find the ssh tunnel option. Any pointers pls -
Django AppRegistryNotReady error for signals after editing apps.py to signals
I'm using Django signals and getting a django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. The Upload model that I'm trying to import in signals.py is not loaded yet. That's why I'm getting the error. I've edited my app's app.py file and settings.py to load apps. Still I am receiving the error. My code is below: project/apps.py from django.apps import AppConfig class EngineConfig(AppConfig): name = 'engine.signals' def ready(self): from engine import signals settings.py in installed apps from django.dispatch import receiver from .models import Upload from django.db.models.signals import post_save @receiver(post_save, sender=Upload) def upload_items(sender, **kwarg): pass What am I doing wrong? -
Sorting by only the most recent object
Models.py class Post(models.Model): article_title = models.CharField(max_length=100) content = models.TextField() date_published = models.DateTimeField(db_index=True, default=timezone.now) game = models.ForeignKey('library.Game', on_delete=models.CASCADE) article_image = models.ImageField(default='/media/default.png', upload_to='article_pics') platform = models.CharField(max_length=20) class Game(models.Model): title = models.CharField(max_length=100) description = models.TextField() date_posted = models.DateTimeField(default=timezone.now) cover = models.ImageField() cover_display = models.ImageField(default='default.png') developer = models.CharField(max_length=100) twitter = models.CharField(max_length=50, default='') Views.py 'recent_posts': Post.objects.all().order_by('-date_published')[:5], How can I retrieve the most recent post for each game and then sort the games by the most recent post's date published? I'm currently using whats in the views.py but it sorts all posts and will return duplicates if a certain game has many recent posts. -
Show content filter by user on extended CB
I am trying to show a content only post by the current logged in user on a ListView but the answer here : How to make generic ListView only show user's listing? does not solve my problem because my ListView used 4 models views.py class DashboardListView(LoginRequiredMixin,ListView): model = Links template_name = 'dashboard/home.html' context_object_name ='links_list' paginate_by = 15 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['dashboard_list']= Dashboard.objects.all()[:15] context['todo_list']= Todo.objects.all().order_by('-pk')[:15] context['todo_complete']= Todo.objects.all().count() context['PasswordUsername_list']= PasswordUsername.objects.all() return context def get_queryset(self): return self.model.objects.filter(author=self.request.user) I tried to add a get_context and a get_query_set but it's hiding only the link model. Thanks -
Django test "django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')"
Django 2.1.5, with MySQL backend. My django app works. This issue is about test. Added query prints to django code, it's failing on this line: ALTER TABLE `documents` ADD CONSTRAINT`documents_assessment_perspecti_2890f0af_fk_assess_pe` FOREIGN KEY (`assessment_perspective`) REFERENCES `assess_perspectives` (`id`) I got into MySQL through command line tool, and found that in test_db, 'assess_perspectives' table hasn't been created, when the above foreign key command ran. I wonder, how does Django decide on the sequence of table creation during test runs? Is this a Django bug, or I'm not using it right? Is there a way I can force 'assessment_perspective' table to be created first in test? To run test python manage.py test document --settings=myapp.settings.local My Simplified Model class AssessPerspective(models.Model): _id = models.AutoField(db_column='id', primary_key=True) name = models.CharField(db_column='name', max_length=255, blank=True, null=True) class Documents(models.Model): assessment_perspective = models.ForeignKey(AssessPerspective, models.DO_NOTHING, db_column='assessment_perspective', blank=True, null=True) ...... Exception Traceback (most recent call last): File "/Users/xxx/myapp/env/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 198, in execute res = self._query(query) File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/MySQLdb/cursors.py", line 306, in _query db.query(q) File "/Users/xxx/myapp/see/env/lib/python3.7/site-packages/MySQLdb/connections.py", line 217, in query _mysql.connection.query(self, query) MySQLdb._exceptions.IntegrityError: (1215, 'Cannot add foreign key constraint') The above exception was the direct cause of the following … -
【Django】Is writing all of the table definition in one model bad practice?
I'm confused at Where I have to write table definition . Django have several apps and each app have models. Table definition is written in the models. However, table relationships is comprecated,so each app calls each other's model.It is comprecated and hard to find what app have a table. So,I want to put all of the table definition into one app. project myapp models.py(just have business logics) views.py common models.py(just table definition) views.py This is simple and easy to understand,I think. Is this bad idea? -
Adding User to Django Group via Stripe API Response
I am attempting to add a user to a group once a successful Order response is returned. I have a group like below: act_group = Group.objects.create(name='ACT Group') There will most likely be multiple products, but for this specific group we will only add users to the group if their order contains an item called ACT Course I've yet to write what the post purchase will look like, but I know I will be using Django-Oscar 1.6 to handle the orders so the user will have some type of order history such as below class oscar.apps.order.processing.EventHandler({ User }) handle_shipping_event() I am looking to see the best way to have the order signal adding that specific user to the ACT Group using the username with which they are currently logged in (users will be required to create an account since they will need this for access to digital materials).