Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - objects attributes represented by BoundField in template: I just want a string
I have a Django model class like: from django.db.models.deletion import PROTECT from django.db.models import ForeignKey class TScript(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=32, null=False, blank=False, unique=True) category = ForeignKey(TCategory, PROTECT, null=False, blank=False, to_field='name') # protect TScript from deletion; TScript belongs to TCategory service = ForeignKey(TService, PROTECT, null=False, blank=False, to_field='name') platform = ForeignKey(TPlatform, PROTECT, null=False, blank=False, to_field='name') command = models.CharField(max_length=1024, blank=False, null=False) machine = models.CharField(max_length=64, blank=False, null=False) username = models.CharField(max_length=150, blank=False, null=False) # now save as string to avoid problem supervisor = models.CharField(max_length=40, blank=True, null=False) # the supervisor of this user, fill in the form of script interval = models.IntegerField(blank=False, null=False) # seconds # oid = models.CharField(max_length=256, blank=False, null=False, default="1.3.6.1.4.1.41019.2.7.1.1.30.1") timeout = models.IntegerField(blank=False, null=False) # seconds status = models.IntegerField(blank=False, null=False) out = models.CharField(max_length=1024, blank=True, null=True) error = models.CharField(max_length=512, blank=True, null=True) description = models.CharField(max_length=256, blank=True, null=True) lastrundate = models.DateTimeField(null=True) insertDate = models.DateTimeField(auto_now_add=True) # overriding to save model with user of this session got from request, to fix # '''Exception ValueError(u"save() prohibited to prevent data loss due to unsaved related object 'user'.",)''' # def save_model(self, request, obj, form, change): # obj.username = request.user.username # super(TScript, self).save_model(request, obj, form, change) def __unicode__(self): # __str__ on Python 3 return " - ".join(["ID: " + str(self.id), … -
Page not found (404) - No Product matches the given query
I'm working on a Django blog, and having implemented slug for detail page. I've stumbled upon an issue. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/susu/ Raised by: myshop.views.product_detail No Product matches the given query. This is my myshop/urls.py file from django.conf.urls import url from . import views app_name = 'myshop' urlpatterns = [ url(r'^$', views.product_list, name='product_list'), url(r'^(?P<product_slug>[-\w]+)/$', views.product_detail, name='product_detail'), url(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'), ] This is my urls.py file from django.contrib import admin from django.conf.urls import url, include from myshop import views as mv from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('myshop.urls', namespace='myshop')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is my views.py file from django.shortcuts import render, get_object_or_404 from .models import Category, Product # Create your views here. def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products}) def product_detail(request, product_slug): product = get_object_or_404(Product, slug=product_slug, available=True) return render(request, 'shop/product/detail.html', {'product': product}) And this is my models.py file from django.db import models from django.urls import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) … -
Unique Together key validation error in Django admin inline forms
I have following structure of models A, B and C. class A(models.Model): id = models.IntegerField(primary_key=True, editable=False) name = models.CharField(_('Name'), max_length=40) ... ... class B(models.Model): id = models.IntegerField(primary_key=True, editable=False) a = models.OneToOneField(A, verbose_name=_('A'), on_delete=models.CASCADE) class C(models.Model): id = models.IntegerField(primary_key=True, editable=False) a = models.ForeignKey(A, verbose_name=_('A'), on_delete=models.CASCADE) b = models.ForeignKey(B, verbose_name=_('A'), on_delete=models.CASCADE) name = models.CharField(_('Name'), max_length=40) number = models.IntegerField(_('Number')) created = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = ('b', 'name', 'number') Following is code for Model form and Tabular inline admin of class C. class CForm(forms.ModelForm): class Meta: model = C exclude = ['created',] widgets = { 'b': forms.HiddenInput, } class CInline(admin.TabularInline): model = C form = CForm classes = ['collapse'] fields = ('name', 'number', 'b', ) readonly_fields = ('created', ) extra = 0 def has_delete_permission(self, request, obj=None): return False After that I have registered CInline class as a inline in Admin of Model A as shown in below code. class AAdmin(admin.ModelAdmin): inlines = [CInline] I am able to see inline section in admin screen of model A and save it, but when I open it for change and click on save button with/without any changes in field it raises validation error C with this name, number and b already exists. I don't have … -
Python vs JS - Graphics and Graphs
I'm about to start a project with MEAN Stack, in which I need to make graphics and graphs. Which tool suits me in terms of use, performance and number of libraries to make graphics and graphs?, shoul I use Django? Any help is greatly appreciated. :) -
How to receive an POST request from Django Rest Framework?
I build a API usign Django 2 and Django Rest Framework. All get methods are ok, using authentication first to receive a token and using this token to access all the other methods. The only problem is with the only function that I have that receive a POST data. The problem is that the call for this POST method allways return, even providing the "authorization" token, this message: "{"detail":"Authentication credentials were not provided."} The funy thing is that in POSTMAN it works! Another developer tried with JavaScript and it allways return this message. I tried with PHP making a POST request using CURL and give the same error. Just with POSTMAN it works... This is my Django Rest Framework settings in settings.py: INSTALLED_APPS = [ ... 'rest_framework.authtoken', ... ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), } This is the method called trought API, in views.py: @api_view(['POST']) def api_inventory_sector_items_check(request, branch_id, inventory_id, sector_id): # Do something This is the url.py: # ... from rest_framework.urlpatterns import format_suffix_patterns # ... urlpatterns = [ ... path('.../check', # See the long URL bellow views.api_inventory_sector_items_check, name='app.api.inventory_sector_items_check'), ] # ... So I'm trying to call using POST: {{domain}}/app/api/v1/branches/1/inventories/2/sectors/100101329/items/check 'Content-Type: application/json' 'Authorization: Token Token … -
Babel Not compiling. Unexpected Token
This has been asked before but I have clearly set up the steps for this. What am I doing wrong or setting up wrong? I get the following error Failed to compile. ./src/Login.js Syntax error: Unexpected token (52:10) 50 | }; 51 | > 52 | const element = <div> The following is my .babelrc: { "presets": ["es2015", "react", "stage-2", "env"], "plugins": ["transform-class-properties"] } and then finally my webpack.config.js module: { rules: [ { //a regexp that tells webpack use the following loaders on all //.js and .jsx files test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015', 'react', 'stage-2','@babel/preset-env'] } }, I have installed the babel presets and all the packages required. I am just trying to use the JSX coding style. I am still new to this environment. -
How to make statistics in django
I'm using django fobi to allow users to create their own forms. I would like to make some reports and stats based on those forms. I have a working python code but I don't know how to "translate" that code in a django working template. The data is as follows: saved_data = ''' [ [{ "label": "Question 1?", "html_name": "question_1", "first_name": "John", "last_name": "Doe", "email": "john@doe.com", "answer": "Yes" }, { "label": "Question 2?", "html_name": "question_2", "first_name": "John", "last_name": "Doe", "email": "john@doe.com", "answer": ["Red", "White"] }], [{ "label": "Question 1?", "html_name": "question_1", "first_name": "Jane", "last_name": "Mary", "email": "mary@jane.com", "answer": "No" }, { "label": "Question 2?", "html_name": "question_2", "first_name": "Jane", "last_name": "Mary", "email": "mary@jane.com", "answer": ["Red", "Black"] }] ] ''' data = json.loads(saved_data) answer = {} for x in data: for y in x: if type(y['answer']) is list: for an in y['answer']: answer.setdefault(y['label'], {})\ .setdefault('answer', []).append(an) answer.setdefault(y['label'], {}).setdefault('full_name', []).append(y['first_name'] + ' ' + y['last_name']) answer.setdefault(y['label'], {}).setdefault('email', []).append(y['email']) elif type(y['answer']) is str: answer.setdefault(y['label'], {})\ .setdefault('answer', []).append(y['answer']) answer.setdefault(y['label'], {}).setdefault('full_name', []).append(y['first_name'] + ' ' + y['last_name']) answer.setdefault(y['label'], {}).setdefault('email', []).append(y['email']) for questions, answers in answer.items(): print('\n', questions) counting = Counter(answers['answer']) for key, value in counting.items(): print(key, value) for answer in zip(answers['full_name'], answers['answer']): if key == answer[1]: … -
Django : Filter bills with client name in the same page without reloading
in my view I have the list of bills , and I need to add a field in order to filter the list by client as bellow : so that if I choose client rgg it will get only show bill of that client. To do so, I need some orientation if I should do it with Ajax call , because I dont want to reload the page each time I change my choice. I really need to know the best way to do such thing. Thank You so much for your help -
Can't set csrf_token as hidden input value
I'm really confused. When I use csrf_token as itself e.g <div>{{csrf_token}}</div> it works perfectly and gives output like <div>aObwmGR5FiCGnfffpeZhbtMtFCFEMyjTKc0QnYT8FZcF9j9oqz5MzYnqDgcVyBBq</div>, but when I use it in my input field as a value it doesn't work.. This: <input type="hidden" id="csrf_token" value="{{csrf_token}}" v-model="csrf_token"> gives me this: <input type="hidden" id="csrf_token" value=""> -
Django Allauth very specific redirection after Facebook Social Signup
I know there are a few questions on the topic already but I have tried to implement those solutions and could not really solve my problem. I am talking about social signup with allauth here, and facebook in particular. DESIRED BEHAVIOR: after facebook signup I want user to go to my url "accounts:welcome", but when they simply login I want them to go to my LOGIN_REDIRECT_URL (which is the site's home page). After looking here and there this is the code I came up with (writing my custom adapter) settings.py: LOGIN_REDIRECT_URL = ("gamestream:home") SOCIALACCOUNT_ADAPTER = "myproject.users.adapter.MySocialAccountAdapter" adapter.py: from django.conf import settings from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from django.core.urlresolvers import reverse from django.shortcuts import redirect class MySocialAccountAdapter(DefaultSocialAccountAdapter): def save_user(self, request, sociallogin, form=None): print('OK11OK') super().save_user(request, sociallogin, form=form) return redirect(reverse('accounts:welcome')) def get_connect_redirect_url(self, request, socialaccount): print('OK22OK') assert is_authenticated(request.user) url = reverse('accounts:welcome') return url Please assume that all links/settings are good as for example the console prints out 'OK11OK' when I create myself as a user via the facebook app. The fact is that the method get_connect_redirect_url never gets triggered as I never read 'OK22OK' on the console. The user is created and I end up on the home page, which is not what I want. … -
Django-import-export before_import_row to automatically create object if it does not exist
I'm facing the current issue when using Django-import-export: class QuestionResource(resources.ModelResource): category = fields.Field( column_name='category', attribute='category', widget=ForeignKeyWidget(Category, 'category') ) class Meta: model = Question fields = ['id', 'question', 'category', 'answer',] # exclude = ('created', 'modified', 'verified', 'count', 'user_created') # PREVIOUS THINGS I TRIED: # def _post_import(model, **kwargs): # query = self.fields['category'] # category = Question.objects.get_or_create(category=query) # return category # def before_import(self, dataset, dry_run, *args, **kwargs): # query = self.fields['category'] # for q in query: # Category.objects.get_or_create(category=q) # def before_import_row(row, *args, **kwargs): # category = self.fields['category'] # Category.objects.get_or_create(category=category) def before_import_row(row, *args, **kwargs): category = row.fields['category'] Category.objects.get_or_create(category=category) As you can see I added the previous things I tried as comments. The error I receive is: python3.6/site-packages/django/db/models/query.py", line 403, in get self.model._meta.object_name questions.models.DoesNotExist: Category matching query does not exist. What am I missing? I can't seem to find any documentation on this (or there is but I don't understand it) Thanks in advance! -
Dropdown list in Django using pandas data
I am trying to generate two dropdown lists in django using a pandas dataframe. I am declaring the dataframe in the views.py file of the django project (no idea if it is the best way to do it) as I want to exploit all the functions of pandas such as unique() and all the possible selection I can do with the dataframe before sending the information to the webpage. ...views.py def index(request): dataframe=pd.read_excel("myFile.xlsx") countries = dataframe['Country'].unique() cities = dataframe['City'].unique() context = {'countries' : countries, 'cities' : cities} return render(request, 'myApp/index.html', context} while the index.html is .../myApp/index.html <select> {% for country in countries %} <option value="{{ country }}">{{ country }}</option> {% endfor %} </select> <select> {% for city in cities%} <option value="{{ city }}">{{ city }}</option> {% endfor %} </select> Now, I would like to select a 'Country' from its dropdown list and have only the cities belonging to that country in the second dropdown. Is it possible (and how can I do it)? Having in mind that the final work should be a dashboard (having also React.js and D3.js/NVD3.js so that a selection on dropdowns, search bars or plots will affect the whole webpage) is it a good approach to … -
when create a project in django, create a empty folder
I dont know why every time i create a project with this command, create an empty folder: django-admin start-project myProject These are the files that I have in my directory: What I noticed is that I do not have the django-admin.py file, is that normal? Because when I execute the command, it does not throw me any error? When I go to see the folder created previously, I find an empty folder: -
Django Model Foreign Key Casting Integer to Char
I have two fields that I am trying to give a foreign key relationship to. The field that I want to reference is a CharField and the field that will reference the other field is an IntegerField. When I try to set the foreign key, it tries to convert the CharField to an IntegerField and then overflows the IntegerField. Is it possible to cast the IntegerField to a CharField and then set the foreign key? -
Replace object id for related objects
Given models class Reference(models.Model): name = models.TextField() version = models.PositiveSmallIntegerField() ... class First(models.Model): special_reference = models.ForeignKey(Reference, related_name='first_references') ... class Second(models.Model): not_special_reference = models.ForeignKey(Reference, related_name='second_references') ... class Third(models.Model): very_special_reference = models.ForeignKey(Reference, related_name='third_references') ... ref_v1 = Reference(name="Main Reference", version=1).save() first = First(reference_id=ref_v1.id).save() second = Second(reference_id=ref_v1.id).save() third = Third(reference_id=ref_v1.id).save() I don't know how many models can relate to reference. ForeignKeys and related names can be different. Now I will create next version of reference. ref_v2 = Reference(name="Main Reference", version=2).save() I need that all created objects of First, Second and Third models related to ref_v1 change relation to ref_v2. I know, that I can get all related models of Reference through _meta like this Reference._meta.related_objects. But I can't figure out how can I dynamically get all related models and change value of ForeignKey to new one. -
PHP speed test 2 django view
Good morning, my question is this: How can I transform the following PHP codes to a django view? I'm transferring the following code [https://github.com/adolfintel/speedtest][1] to get a speed test but it's done in php. ========================================================================= Código 1 Detalle de código de php file garbage.php // Disable Compression @ini_set('zlib.output_compression', 'Off'); @ini_set('output_buffering', 'Off'); @ini_set('output_handler', ''); // Headers header('HTTP/1.1 200 OK'); // Download follows... header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=random.dat'); header('Content-Transfer-Encoding: binary'); // Never cache me header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('Cache-Control: post-check=0, pre-check=0', false); header('Pragma: no-cache'); // Generate data $data=openssl_random_pseudo_bytes(1048576); // Deliver chunks of 1048576 bytes $chunks=isset($_GET['ckSize']) ? intval($_GET['ckSize']) : 4; if(empty($chunks)){$chunks = 4;} if($chunks>100){$chunks = 100;} for($i=0;$i<$chunks;$i++){ echo $data; flush(); } ========================================================================= Código 2 Detalle de código de php file empty.php header( "HTTP/1.1 200 OK" ); header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); header("Connection: keep-alive"); -
Django form & rendering data from model
I am currently struggling with Django forms. Based on the tickets model I generate this formset where users can choose the qty of tickets they want. After they will be redirected to the checkout page. My problem is, when I use {{ form.ticket }} I get a select field but that's not what I'm looking for. I just want to print out the tickets as seen in the screenshot below. Can anyone help me on that? How it should be: How it currently looks like: views.py from django.forms import formset_factory from django.shortcuts import redirect, render from .forms import EntryModelForm from .models import Ticket from orders.models import Order, Entry # Create your views here. def choose_ticket_and_quantity(request): tickets = [] for ticket in Ticket.objects.all(): tickets.append({'ticket': ticket}) EntryFormSet = formset_factory(EntryModelForm, extra=0) formset = EntryFormSet(initial=tickets) if request.POST: o = Order.objects.create() request.session['order_id'] = o.order_id formset = EntryFormSet(request.POST, initial=tickets) if formset.is_valid(): for form in formset: if form.cleaned_data['quantity'] > 0: entry = form.save(commit=False) entry.order = o entry.save() return redirect('http://127.0.0.1:8000/checkout') return render(request, "tickets/choose_ticket_and_quantity.html", {'formset': formset}) forms.py from django import forms from orders.models import Entry class EntryModelForm(forms.ModelForm): class Meta: model=Entry fields = ['ticket', 'quantity'] choose_ticket_and_quantity.html <form method="post" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset … -
Do not use textures decorator for Django tests
Is there a decorator in Django that would allow to run the test function without applying fixtures? Something like: from django.test import TestCase class TestSomething(TestCase): fixtures = ['test_fixture.json'] def test_with_fixture(self): # test something with fixtures @do_not_use_fixtures def test_without_fixtures(self): # test something without fixtures -
Django - Loop through input fields in HTML through views
I have this markup <form action="my_view" method="POST"> {% csrf token %} <input name="1"> <input name="2"> <input name="3"> <input name="4"> <input name="5"> <button type="submit"> </form> Is there a way to loop through all the input fields in the VIEWS? View: def do_something(request): # loop through each input field # something like: # for field in fields ?? Thanks! -
How to take upvotes for the answer in Django?
I am developing website for simple question and answer forum. I want to get upvotes for an answer. models.py class Answer(models.Model): ans = models.TextField() img = models.CharField(max_length=100) created_by = models.ForeignKey(User, related_name='answer') created_on = models.DateTimeField(auto_now_add=True) ques = models.ForeignKey(Question, related_name='answer') def __str__(self): return self.ans class Upvote(models.Model): upvote = models.BooleanField(default=False) upvote_by = models.ForeignKey(User, related_name='upvote') upvoted_on = models.DateTimeField(auto_now_add=True) #ques = models.ForeignKey(Question, related_name='upvote') ans = models.ForeignKey(Answer, related_name='upvote') def __str__(self): return self.upvote_by views.py I can get upvotes for an answer like below answer = get_object_or_404(Answer, pk=1) upvotes = Upvote.objects.filter(ans=answer) How to take upvotes from answer object ? Is it possible please correct me if i am wrong. Something like below, answer.upvote_set Thanks in advance !! -
django rest framework - global default model serializer
In short, I want to have a global default serializer per model. My use case here is to create dynamic serializer- i.e creating ModelSerializer classes on the fly. class Customer(models.Model): name = models.CharField(max_length=200) code = models.CharField(max_length=200) # many more fields.. class CustomerTicket(models.Model): customer = models.ForeignKey(Customer) date = models.DateTimeField(auto_now_add=True) # more fields.. Customer will be referenced by many other models, and hence it will be serialized as a nested object. I don't want the 'code' field to appear in the output - no matter what it should always be excluded. Now I'd like to create a function: def serialize_default(model, fields, queryset): class S(serializers.ModelSerializer): class Meta: model = model fields = fields depth = 1 return S(queryset, many=True) if I serialize CustomerTicket queryset using this function, I will get all the customer fields as a nested object. I know I can override it locally, but I want to define a CustomerSerializer that will be used by default (for the nested Customer here) unless other serializer is specified as a field. How to achieve this? -
Django Fallback to model lookup from external API
I'm using Django REST framework to serve up JSON content for a website front end. On the back end, I have two Django models, Player and Match, that each reference multiple of the other. A Match contains multiple Players, and a Player contains multiple Matches. This data is originally retrieved from a third-party API. Matches and Players must be fetched separately from the API, and can only be fetched one at a time. When an object is fetched, its data is converted from the external JSON format into my Django model. At this point, the Match/Player will live forever in Django. The hard part is that I want this external fetching to be seamless. If I query for a player or match and it's in the DB, then just serve what we have there. Otherwise, I want to fetch that object from the external DB. My question is, does Django provide any convenient way of handling this? Ideally, any query along the lines of Match.objects.get(id=...) will handle this API fallback transparently (I don't mind the fact that this queyr may take significantly longer in some cases). -
Django: Actions that provide intermediate pages ... with 100k rows
I know how to write Actions that provide intermediate pages, since the docs are great: https://docs.djangoproject.com/en/2.0/ref/contrib/admin/actions/#actions-that-provide-intermediate-pages But, if my selection contains 100k rows, the pattern of the docs does not work since the URL gets too long. How to write Django Admin Actions that provide intermediate pages and can handle +100k rows? -
Django annotate returned more than one
user = get_object_or_404( (User.objects .annotate(company_name=F('usercompany__company__company_name')) .annotate(project=F('team__vacancy__name'))), email=request.GET.get('user_email') ) I got errors proj.models.MultipleObjectsReturned: get() returned more than one User -- it returned 2! How I can change .annotate(project=F('team__vacancy__name'))), that get all -
Display Django model entries as part of a form
I want to display model entries as part of a form so I can update them. What is the best way to do this? I am using crispy forms. I first filter my object, and then I want to display this object as a form, where certain model attributes are display only, with some attributes being updated. Essentially a table containing all attributes for obj that cant be modified, with 2 attributes that will be updated in the form. forms.py: class ReportSampleForm(forms.Form): def __init__(self, *args, **kwargs): super(ReportSampleForm, self).__init__(*args, **kwargs) sample = self.data.get('sample_id', False) obj = VariantAnnotationSampleRun.objects.filter(sample_run_id=sample) self.helper = FormHelper() self.fields['id'] = forms.ChoiceField( required=True, label='blah:', widget=forms.CheckboxSelectMultiple, choices=((s.id, (s.variant_annotation_id.variant_id, s.attribute1, s.attribute2)) for s in obj) ) self.helper.form_method = 'POST' This displays check boxes with variant_id, attribute1 and attribute2, but I would like Model entries 'evidence' and 'annotation' to be filled in and if the checkbox is checked and form submitted, the database gets updated for that specific model entry. models.py: class VariantAnnotationSampleRun(models.Model): variant_annotation_id = models.ForeignKey(VariantAnnotation, attribute1 = models.DecimalField(max_digits=8, decimal_places=3) attribute2 = models.IntegerField() reported = models.BooleanField(default=False) evidence = models.TextField(null=True, blank=True) annotation = models.CharField(max_length=80, null=True, blank=True) Is this possible to do without building a totally bespoke form, from my view?