Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python django adding multiple database
How to create or add multiple databases in django. Where always my models are created in default database .how to change it -
Django form updating after adding data to database
I'm building a form for user's to run a query on a database. The model is called Sample and the user is selecting the names they want to include in the query results. In this case the name field is unique but other fields done the same way aren't. Form.py from django import forms from .models import Sample class SampleForm(forms.Form): samples = Sample.objects.all() names = [(s.id, s.name) for s in samples] initial = [c[0] for c in names] Rock_Names = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=names, initial=initial, label='Name') The problem I'm having is when a new sample has been added the form won't update with that sample name until I restart the server. I have a list view for all samples and it updates with the new sample fine. I've tried running Sample.objects.update() after the new sample is saved, but that didn't help. Is there a way to force this to update? Is there a better way to build a query form? -
Django Group Permissions in React
In Django I have added a group and can see it on my template by using: {{ perms.mygroup }} I have a React front end app which has a number of links to navigate around the front end but the 'Edit' link must only be visible if the user has the 'mygroup' permission stated above. How is it that I pass the server permission to the front end app? Am I missing something simple here as I can't find out how to do it. I've read about using React's new context API but the examples I've seen are setting the context on the front end, rather than bringing in a variable from the template. -
Making a dataframe from a queryset in django
This is a general question that might not quite fit the title. Basically I have queryset which I loop over like for q i queryset: q.new_var=... in order to produce new variabels. When I send queryset to the template I get these new variable values in the webbpage. So that works as expected. But now I also want to make a data frame from the queryset, using Pandas and django-pandas. So I write df = read_frame(queryset) I would have thought that if I do that after the loop I would get the new variables included in the data frame, but I do not. Instead it is the same as if I put it before the loop. Why, and how do I fix it? -
Passing objects to Detail View with filter (Django)
Hi I am trying to pass query of comments (Comment model) to a DetailView of Post model using filter to get in DetailView only comments, related to particlural post. Post model: class Post(models.Model): title = models.CharField(max_length=300) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) Comment model: class Comment(models.Model): content = models.CharField(max_length=500, help_text='ΠΠ΅ Π±ΠΎΠ»Π΅Π΅ 500 Π·Π½Π°ΠΊΠΎΠ²') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(on_delete=models.CASCADE) post_id = models.ForeignKey(on_delete=models.CASCADE) Detail veiw: class PostDetailView(DetailView): context_object_name = 'post' model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(post_id = self.model.id) return context And it returns TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' Could you please help with reccomendation regarding how correctly use a filter to get in DetailView only comments, related to this Post? Thanks! -
Django Choice list between objects created with model class
i have a following class in models.py class Project(models.Model): project_name = models.CharField(max_length=100,unique=True) project_headers = models.TextField(unique=True) projects_urls = models.TextField() project_timestamp = models.DateTimeField(auto_now_add=True) project_results = models.TextField(blank=True,null=True) def __str__(self): return self.project_name And let's suppose i have created a 2 Projects objects with above class with following project_name. google.com facebook.com I want to create a form where i can add Django Choices list as project_name objects to update their fields such as project_urlsetc, based on project_name selected by User. -
JSON:API with django-rest-framework-json-api and JWT
I thought it might be a good idea to use the standard JSON:API for my new project. Unfortunately I immediately failed to get the JWT authentication working. My setup: Django Django REST framework REST framework JWT Auth Django REST Framework JSON API If I get OPTIONS for my auth path: { "data": { "name": "Obtain Json Web Token", "description": "API View that receives a POST with a user's username and password.\n\nReturns a JSON Web Token that can be used for authenticated requests.", "renders": [ "application/vnd.api+json", "text/html" ], "parses": [ "application/vnd.api+json", "application/x-www-form-urlencoded", "multipart/form-data" ], "allowed_methods": [ "POST", "OPTIONS" ], "actions": { "POST": { "username": { "type": "String", "required": true, "read_only": false, "write_only": false, "label": "Username" }, "password": { "type": "String", "required": true, "read_only": false, "write_only": true, "label": "Password" } } } } } If I then try to POST naively with Content-Type: application/vnd.api+json: { "data": { "user": "user1", "password": "supersecretpw" } } I get 409 Conflict response: { "errors": [ { "detail": "The resource object's type (None) is not the type that constitute the collection represented by the endpoint (ObtainJSONWebToken).", "source": { "pointer": "/data" }, "status": "409" } ] } How can I either retrieve the token correctly or use the β¦ -
Download files in django from database and also view pdf file in that
Well, I am trying to make a simple app in django in which I upload files from admin panel. The user is greeted with a simple search page in which he enters an id which thus needs to produce the related file. The file is to be in pdf format. So if there is a way I could view the pdf file in the browser and a download button which downloads the file. The code is hosted on Github, the link is https://github.com/tahseen09/delhipatho -
Django DB Model, Create two identical tables, one inheriting from the other
I have a requirement where I would like to have identical tables in Django. For example MyTableCurrent and MyTableArchive. The tables should be identical except of the class/table name and the foreign key references. Is there a way to basically maintain the schema on MyTableCurrent, then under MyTableArchive, I inherit from the base class of MyTableCurrent but override just the foreign key fields to match the corresponding Archive table? -
Send alert message(data) from one login user session to another
I have a use case where a user (manager) creates a task (1st view) and another logged in user (employee) can view the task created (2nd view). If the employee rejects the task clicking reject button, an alert should notify the manager. How do I achieve this functionality? Thanks for any guidance. -
Django: Retrieve a model Queryset that created today but has no entries before.
Lets take a situation, class A(models.Model): customer = models.FK(User) ... I need to fetch all the rows created today but only the rows that is created for the first time against each customer. Suppose a customer made an entry yesterday and today, we do not want to include it. But if the customer is making an entry for the first time today in the table it has to be included. This can be achieved using two different querying steps , one to fetch all entries today then check if the customer is made that entry for the first time in this table using next step of query. What I am searching for is a better optimized way to achieve this. Is there a better solution, a better way to use Django ORM? -
Django "redirect" by adding a query parameter to URL
I would like to achieve the following behavior: The user types www.example.com/list in the browser and hits Enter In their browser, the URL is automatically changed to www.example.com/list?page=1 The URL with page parameter is evaluated by Django How to achieve this using Django generic ListView with pagination? class RecordList(ListView): model = Record paginate_by = 25 -
static files not found in django 1.11
I am getting "Not Found" when accessing any page on localhost. I have read all related posts but still cannot understand why. I have included 'django.contrib.staticfiles' in INSTALLED_APPS. I have DEBUG = TRUE in my settings.py my project layout and code is as the following. Thank you in advance. repo_root βββ manage.py β βββ project_root β β β βββ accounts β β βββ migrations β β βββ __init__.py β β βββ admin.py β β βββ apps.py β β βββ models.py β β βββ tests.py β β βββ views.py β β βββ urls.py β β β βββ templates β β βββ index.html β β β βββ static β βββ assets β βββ bootstrap β βββ css β βββ fonts β βββ img β βββ js β βββ config_root β βββ __init__.py β βββ settings.py β βββ urls.py β βββ wsgi.py β settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join( BASE_DIR, 'project_root/static/assets') ] STATIC_ROOT = os.path.join( BASE_DIR, 'project_root/staticfiles') index.html <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no"> <title>index</title> <meta name="description" content="sample_content"> <link rel="stylesheet" href="'static/assets/bootstrap/css/bootstrap.min.css'"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,400i,700,700i,600,600i"> <link rel="stylesheet" href="'static/assets/fonts/simple-line-icons.min.css'"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.css"> <link rel="stylesheet" href="'static/assets/css/smoothproducts.css'"> </head> urls.py url(r'^index/$', IndexView.as_view()) views.py class IndexView(TemplateView): template_name = "index.html" -
Django ORM. Retrieve 10 items for each category
I have 2 models in My Django REST. class Category(models.Model): name = models.CharField() class Item(models.Model): name = models.CharField() category = models.ForeignKey(Category) I need build queryset where i get 10 items for each category. I dont know i need Filter Category or Item, but maybe somebody can help me. I think i need something like this: Item.objects.filter.. if item with same category not > 10. I will be pleasure if somebody show me some way or decision. -
Django rest api redirect to S3 download link returns mime type warning in chrome console
I'm using Django Rest Framework to build an API and I'm trying to redirect my endpoint to download files from AWS S3. It's working but in Chrome I'm getting the following warning: Resource interpreted as Document but transferred with MIME type application/force-download This is my get method from my view: def get(self, request, pk, format=None): file_item = self.get_object(pk) serializer = FileSerializer(file_item) response = redirect(serializer.data['file_url'], content_type ='application/force-download') return response As you can see, I have passed content type, why does it Chrome still throw a warning? I need to be able to download files in various formats e.g. pdf, jpg etc. -
Can't loas static files Django 1.9
Template cant find static files and load it on page. This is my settings: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'cargo/templates') # STATIC_DIR = os.path.join(BASE_DIR,'cargo/static') DEBUG = True ALLOWED_HOSTS = [] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = 'os.path.join(os.path.expanduser("~"), "domains/h2h.su/static/")' This my path to files cargo/static/cargo/images and templates at the same path in cargo app cargo/templates/cargo/index.html Can someone help me? -
python django sort with lambda with if statement
I have date and some dollar gross model: class FirstDate(models.Model): gross = models.DecimalField(max_digits=12, decimal_places=2, default=0) updated = models.DateTimeField(auto_now=True) class SecondDate(models.Model): gross = models.DecimalField(max_digits=12, decimal_places=2, default=0) updated = models.DateTimeField(auto_now=True) And want to sort it by gross, and if gross is the same, then sort it with updated field For example, qs1 = SoloDate.objects.all()[:2] qs2 = GroupDate.objects.all()[:2] result_list = sorted( chain(qs1, qs2), key=lambda x: x.gross # and if gross is the same, for the gross same objects, x.updated and then update was also the same, x.pk, ) I mean, let me say that there is two objects individually from qs1 and qs2. # objects from qs1 qs1_obj1 = { 'pk': 1, 'gross': 5, 'updated': 2018-11-24 10:53:23.360707+00:00 } qs1_obj2 = { 'pk': 2, 'gross': 5, 'updated': 2018-11-25 10:53:23.360707+00:00 } # objects from qs2 qs2_obj1 = { 'pk': 3, 'gross': 5, 'updated': 2018-11-24 10:53:23.360707+00:00 } qs2_obj2 = { 'pk': 4, 'gross': 1, 'updated': 2018-11-23 10:53:23.360707+00:00 } It's result_list order will be qs1_obj1, qs2_obj1, qs1_obj2, qs_2_obj_2. Reasons is it: qs1_obj1: 1.by gross is big, 2.by updated, 3.by pk, qs2_obj1: 1.by gross, 2.by updated, 3. but pk was not good, qs1_obj2: 1.by gross, 2.but by dpdated was late, qs2_obj2: 1.gross was small. Maybe it is not β¦ -
Invalid HTTP_HOST header - Django
I started receiving a lot invalid HTTP_HOST on my django server, out of nowhere.... The allowed_hosts are correct, I think someone is trying to break in... here are the fails: Invalid HTTP_HOST header: 'www.google.com'. You may need to add 'www.google.com' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '127.0.0.1:30303'. You may need to add '127.0.0.1' to ALLOWED_HOSTS. Invalid HTTP_HOST header: '/home/site/myapp.sock:'. The domain name provided is not valid according to RFC 1034/1035. Invalid HTTP_HOST header: 'xxxx.members.linode.com'. You may need to add 'xxxx.members.linode.com' to ALLOWED_HOSTS. Any idea why this starts happening? -
Django-filter for nullable Boolean Field
I would lite to use django-filter for BooleanField(blank=True, null=True). When I use it out of the box, the form generates three options: Unknown (no filtering), Yes (True) and No (False). However, I need a fourth option for None so that the filter specifically selects those records with value None. My model (relevant part): class Record(Model): accepted = BooleanField(blank=True, null=True, verbose_name=_("Accepted?")) My filter (relevant part): class RecordFilter(FilterSet): class Meta: model = Record fields = OrderedDict(( ("accepted", ["exact"]), )) My view: class RecordList(LoginRequiredMixin, FilterView): model = Record paginate_by = 25 template_name = "record/record_list.html" filterset_class = RecordFilter My template (relevant part): <form method="get" role="form" class="form"> {{ filter.form.as_p }} <button>{% trans "Filter" %}</button> </form> How can I achieve the desired behavior? -
Making a multi-selection HTML table in django
def index(request): pull_requestsList = Pull_Requests.objects.all() paginator = Paginator(pull_requestsList, 25) page=request.GET.get('page') try: pullrequests=paginator.page(page) #pullRequest_dict = {'pull_requests': pullrequest} except PageNotAnInteger: pullrequests=paginator.page(1) except EmptyPage: pullrequests=paginator.page(paginator.num_pages) return render(request, 'index.html', {'pullrequests': pullrequests}) {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css'%}"> {% block body %} <div class="container" align="center" xmlns="http://www.w3.org/1999/html"> {% block table %} <p><br><br><br><br></p> <table class="table table-bordered" border="1"> <tr> <th>Project</th> <th>Pull Request ID </th> <th>Nb comments </th> <th> LC added </th> <th> LC deleted </th> <th> Nb commits </th> <th> Nb changed fies </th> <th> Closed status </th> <th> Reputation </th> <th> Label </th> </tr> {% for field in pullrequests %} <tr> <td>{{ field.pr_project }}</td> <td>{{ field.pr_id }} </td> <td>{{ field.nd_comments }} </td> <td>{{ field.nb_added_lines_code }}</td> <td>{{ field.nb_deleted_lines_code }}</td> <td>{{ field.nb_commits }}</td> <td>{{ field.nb_changed_fies }}</td> <td>{{ field.Closed_status }}</td> <td>{{ field.reputation }}</td> <td>{{ field.Label }}</td> </tr> {% endfor %} </table> {% endblock table %} </div> {% endblock %} <div class="pagination" align="center"> <span class="step-links"> {% if pullrequests.has_previous %} <a href="?page={{ pullrequests.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ pullrequests.number }} of {{ pullrequests.paginator.num_pages }}. </span> {% if pullrequests.has_next %} <a href="?page={{ pullrequests.next_page_number }}">Next</a> {% endif %} </span> </div> I would like to allow users to be able to select multiple rows in my HTML table β¦ -
Unable import django models after compiling with Cython
have compiled django app with following command python3 compile.py build_ext --inplace, which generated models.cpython-35m-x86_64-linux-gnu.so file within app. Later on running the django server, getting following error File "/home/env3/lib/python3.5/site-packages/django/db/models/base.py", line 113, in new "INSTALLED_APPS." % (module, name) RuntimeError: Model class models.Country doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Here Country is one of the model class within models.py file -
Display intro video first visit only Django
I have a Django app that needs to display a video that gives an into to the website. I only want it to do this on the initial visit as opposed to every time the user refreshes. I feel like sessions would have something to do with this but Iβm not sure. Thanks! -
Django Rest Framework - Updating related model using ModelSerializer and ModelViewSet
BACKGROUND I have two serializers: PostSerializer and PostImageSerializer which both inherit DRF ModelSerializer. The PostImage model is linked with Post by related_name='photos'. Since I want the serializer to perform update, PostSerializer overrides update() method from ModelSerializer as stated in official DRF doc. class PostSerializer(serializers.ModelSerializer): photos = PostImageSerializer(many=True) class Meta: model = Post fields = ('title', 'content') def update(self, instance, validated_data): photos_data = validated_data.pop('photos') for photo in photos_data: PostImage.objects.create(post=instance, image=photo) return super(PostSerializer, self).update(instance, validated_data) class PostImageSerializer(serializer.ModelSerializer): class Meta: model = PostImage fields = ('image', 'post') I have also defined a ViewSet which inherits ModelViewSet. class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer Finally the PostViewSet is registered to DefaultRouter. (Omitted code) Goal The goals are simple. Send PUT request via PostMan with url like 'PUT http://localhost:8000/api/posts/1/' Since Image files should be included, request would be done by form-data like below. Problem I'm getting 400 Response with error message as following. { "photos": [ "This field is required." ], "title": [ "This field is required." ], "content": [ "This field is required." ] } (Should you plz note that the error messages might not exactly fit with DRF error messages since they are translated.) It is obvious that none of my PUT β¦ -
Password protect individual urls with url specific passwords in Django?
So I have a bunch of pages with urls that look like: /article/detail/1 /article/detail/2 /article/detail/3 ... I would like to password protect some of these urls and the ones that are protected will have their own passwords so it may look like: -------URL---------Password-------- /article/detail/1 | password1 /article/detail/2 | s3cret /article/detail/3 | This really does not need to be all that secure because the information stored here isn't all that important. I am storing the 'passwords' in plain text in my database. And ideally, all I want is that whenever the user tries to access one of these URLs, if it has no password, user goes directly to the page, if it does have a password, they are taken to some intermediate page where they can put in this password. Whats the simplest way of achieving this? I can post exact code here if required but essentially all of these pages have a views.py that looks like: class ArticleDetailView(LoginRequiredMixin, ListView): template_name = 'cb_detail.html' login_url = 'login' def get_queryset(self): return Data.getAllPosts() def get_context_data(self, **kwargs): # populate context return context So there is no model being used here. The LoginReqiredMixin is used to ensure that the user is actually logged in but I β¦ -
Is there a way to move a my ΩDJANGO program to other computer without the need of re installing all the required module?
Is there a way to move a my Ωdjango-python program to other computer without the need of re installing all the required module?