Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-admin TypeError: __init__() got an unexpected keyword argument 'allow_abbrev'
I've upgraded Django to 2.1.4 (from 2.0.5) and I get the following error when I run the command line manage.py python3 manage.py createsuperuser Here is the detailed error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 314, in execute parser = CommandParser(usage='%(prog)s subcommand [options] [args]', add_help=False, allow_abbrev=False) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 48, in __init__ super().__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'allow_abbrev' I'm on Debian stretch using Python 3.5.3 and Django 2.1.4 -
sending a table from ajax to Django Rest framework
I'm trying to send a JS table to a Django Rest API View and read that parameter in the get_queryset() function Here's my ajax call : $.ajax({ type : "GET", url : fetchDataUrl, data : { table : [10,20,30,40,50], }, success : function(data){ }, error : function(data){ } }); Here's my APIView : class LivreListAPIView(generics.ListAPIView): serializer_class = BookSerializer def get_queryset(self, *args, **kwargs): table = self.request.GET.get("table",None) ... -
Reverse for 'post_list' with keyword arguments '{'pk': '2'}' not found. 1 pattern(s) tried: ['$']
I think this is very easy problem but I don't know what's wrong. I reserved the error. It says : Exception Type: NoReverseMatch Exception Value: Reverse for 'post_publish' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['\^post/\(\?P(?P[^/]+)\\d\+\)/publish/\$$'] Exception Location: C:\Users\umts\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 622 can you guys help me to solve these problems? urls.py urlpatterns = [ path('', views.post_list, name='post_list'), path('post/<int:pk>/', views.post_detail, name='post_detail'), path('post/new', views.post_new, name='post_new'), path('post/<int:pk>/edit/', views.post_edit, name='post_edit'), path(r'^drafts/$', views.post_draft_list, name='post_draft_list'), path(r'^post/(?P<pk>\d+)/publish/$', views.post_publish, name='post_publish'), path(r'^post/(?P<pk>\d+)/remove/$', views.post_remove, name='post_remove'), path(r'^post/(?P<pk>\d+)/comment/$', views.comment_add, name='comment_add'), path(r'^comment/(?P<pk>\d+)/approve/$', views.comment_approve, name='comment_approve'), path(r'^comment/(?P<pk>\d+)/remove/$', views.comment_remove, name='comment_remove'), ] I'll show only 'comment add' code views.py # comment 더하기 def comment_add(request, pk): post=get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form=CommentForm() return render(request, 'blog/post_detail.html')#, {'form':form}) post_detail.html <!--Comment 입력창--> <hr> <form action="{% url 'comment_add' pk=post.pk %}" method="POST" class="comment-form"> {% csrf_token %} <input type="text" name="text" placeholder="댓글 달기..."> </form> <!-- <form class="post-form" method="POST"> {% csrf_token %} <!--{{ form.as_p }} <button type="submit" class="save btn btn-default"> Add comment </button> <input type="text" name="content" value="Add Comment"> </form>--> You can ignore the Korean words. However, what I want to make is add comment. -
Can I change the default forms name template that Django uses?
I know that Django uses default names for it's template engine, for example if I have a Form for Comments Model, Django it's going to search for comments_form.html for render that form. But can I change that? Instead of using comments_form for the form render can I use another html as template? How can I do this using Class Based Views? -
django form Select Dropdown List using JSON
I want to create a django form Select Dropdown List using JSON url from DJANGO model(I want to create a real time Select Dropdown List). I try to follow this tutorial without success (if I use json link from tutorial then example work). in browse console I take this errors : Access to XMLHttpRequest at 'http://127.0.0.1:8000/test_data/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. f1.html:60 An error occurred fetching the JSON from http://127.0.0.1:8000/test_data/ here the code : views.py def test_json(request): response_data=serialize('json',mymodel.objects.all()) return HttpResponse(response_data,content_type='json') urls: url(r'^test_data/$', test_json, name='test_json') json link : [ { model: "log.mymodel", pk: 3, fields: { f1: "some vasa", f2: "some vadada", f3: "some vsasa", f4: "some vsasdsa", f5: "some vddsdsd", f6: "some vsds", f7: "2019-04-05T18:38:42.722Z" } }, { model: "log.mymodel", pk: 4, fields: { f1: " some v1", f2: "some v2", f3: "some v3", f4: "some v4", f5: "some v5", f6: "some v6", f7: "2019-04-07T15:10:03.991Z" } } ] html page : <!DOCTYPE html> <html> <head> <title>GeoJSON tutorial</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <select id="locality-dropdown" name="locality"> </select> <script> let dropdown = document.getElementById('locality-dropdown'); dropdown.length = 0; let defaultOption = document.createElement('option'); defaultOption.text = 'Choose State/Province'; dropdown.add(defaultOption); … -
Django REST: Files\Images Uploading
Im want to upload an image using Vue.js and Django-rest. And have few problems with it. Im trying to use put request (as in docs) and FileUploadParser for it, but getting an error: detail: "Missing filename. Request should include a Content-Disposition header with a filename parameter. If i make my header like: 'Content-type':'multipart/form-data', 'filename': 'file' Django registers request as OPTIONS, not put, so my put function not called. My serializer: class ImagesSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Images fields = ('image',) My view: class ImagesViewSet(APIView): parser_classes = (FileUploadParser,) def get(self, request): images = Images.objects.all() serializer = ImagesSerializer(images, many=True) return Response(serializer.data) def put(self, request, filename, format=None): image = request.data['image'] Images.objects.create( image=image ) return Response(status=204) My Vue.js request: import axios from 'axios'; export default { name: 'App', data(){ return { name: '', image: '', description: '', price: '', files: false, } }, methods: { onFileChange(e) { console.log('works'); var files = e.target.files || e.dataTransfer.files; if (!files.length) return; this.createImage(files[0]); }, createImage(file) { var image = new Image(); var reader = new FileReader(); var vm = this; reader.onload = (e) => { vm.image = e.target.result; }; reader.readAsDataURL(file); }, createNewProduct(){ const config = { headers: { 'Content-type':'multipart/form-data', 'filename': 'file' } } let formData = new FormData(); formData.append('image', … -
Django migrate: no migrations to apply
I just added a simple model to my Django app in models.py, I added a view, a form and a template for it as well but I don't believe this matters: class SoldKit(models.Model): number = models.CharField(max_length=100) quotation = models.CharField(max_length=100) Running ./manage.py makemigrations used to be enough but apparently since I don't know when I have to add the app name, so I run: ./manage.py makemigrations files This shows various changes, of which I am sure only the SoldKit is a true change, but OK. Output: Migrations for 'files': files/migrations/0001_initial.py - Create model Contact - Create model Document - Create model Kit - Create model Profile - Create model Project - Create model PubkeyFile - Create model Setting - Create model SoldKit Then, I was tought to run migrate, to actually perform the changes, so I type: ./manage.py migrate Result: Operations to perform: Apply all migrations: admin, auth, contenttypes, files, sessions Running migrations: No migrations to apply. Which clearly is false because I did add a model... Also, I still receive an error on the page where the model is used, namely: (1146, "Table 'databaseA.files_soldkit' doesn't exist") The only way I know is to remove and recreate the database but this … -
Django multiplechoicefield not rending on page
I'm trying to get a form that takes in a name and month and will return students with that name and month (attendance system). I'm using a MultipleChoiceField for the form but it does not render in the browser. I am also using Materialize CSS. How do I sort this issue? I'm also rendering the form fields manually. forms.py: class attendenceFinder(forms.Form): months = ((1, 'JAN'), (2, 'FEB'), (3, 'MAR'), (4, 'APR'), (5, 'MAY'), (6, 'JUN'), (7, 'JUL'), (8, 'AUG'), (9, 'SEP'), (10, 'OCT'), (11, 'NOV'), (12, 'DEC') ) name = forms.CharField() month = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=months) attendence.html: <form action="/get_attendence/", method="post"> <div class="container"> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.name.errors }} <label for="{{ form.name.id_for_label }}">Name</label> {{ form.name }} </div> <div class="fieldWrapper"> {{ form.month.errors }} <label for="{{ form.month.id_for_label }}">{{form.month}} <span>{{ form.month.label }}</span> </label> </div> <button class="waves-effect waves-light btn-large lime accent-2 black-text" type="submit" name="action">Submit <i class="material-icons right">send</i> </div> </form> The form in browser: [1} https://imgur.com/a/KYpqhn2 "the form in the browser. The name field renders fine but the Month multiple choice doesn't" -
Model ImageField and save in a specific path
This in my model: def group_based_upload_to(instance, filename): return "media/image/lavorazione/{}".format(instance.prestazione.id,) class ImmaginiLavorazioni(models.Model): immagine = models.ImageField(upload_to=group_based_upload_to) prestazione = models.ForeignKey(Listino, on_delete=models.SET_NULL, null=True, blank=True, default=None, related_name='Listino3') and my form: class ImmagineUploadForm(forms.ModelForm): class Meta: model = ImmaginiLavorazioni exclude = ('preventivo', ) I need a view to save an image in a specific path. The name of path must be the pk of foreign key. How can I do that? -
How to check if instance of model exists in django template
I have a django app with a basic model (Job). Now in my template I would like to check if an instance exists of that model or not. I want to project a text if there is nothing yet to show, otherwise I'd like to show the model attributes. Somehow like so (which obviously doesn't work): {% if job.title != "" %} {{ job.title }} {% else %} hola {% endif %} Also tried: {% for job in jobs %} {% if job.title %} {{ job.title }} {% else %} Hola {% endif %} {% endfor %} It makes sense it doesn't work because how can I loop through it or return something if it doesn't exist. Is there a simple way to even do that in a template? Or do I have to write my own function? Or what would be a way to do that? Help is of course very much appreciated -
Where do I have to put test_*.py files in Django?
I just moved tests.py file to a new directory called tests, then I added __init__.py file therein, but as I run the test python manage.py test it says ran 0 tests in 0.000s. How to solve it? I don't know how to show my files like most do, but here is an image! This app is also added in settings.py Thanks -
How do I get my Django query to only return an average and another column?
I'm using Django and Python 3.7. I have these models ... class Article(models.Model): website = models.ForeignKey(Website, on_delete=models.CASCADE, related_name='articlesite') title = models.TextField(default='', null=False) path = models.TextField(default='', null=False) url = models.TextField(default='', null=False) created_on = models.DateTimeField(db_index=True, default=datetime.now) class ArticleStat(models.Model): objects = ArticleStatManager() article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='articlestats') elapsed_time_in_seconds = models.IntegerField(default=0, null=False) hits = models.FloatField(default=0, null=False) I want to write a Django query that returns two columns of data -- an elapsed_time_in_seconds (from the ArticleStat model above) and an average of the hits for this particular interval. There are a couple of other constraints in the mix. I have no idea how to do this. I tried the below qset = ArticleStat.objects.annotate(avg_score=Avg(F("hits")), hour=(Func( Func( F("article__created_on"), function='HOUR FROM'), function='EXTRACT'))).filter( article__website=website, hour=hour) but this results in the error, "TypeError: expected string or bytes-like object". I'm confused about how to specify the "GROUP BY" part of my SQL statement, and then I'm confused about how to return the two columns of data I want, since I think the above only returns ArticleStat objects, which wouldn't include my average in there. -
Should I always trust W0613 pylint warnings in Django, especially for functions which have **kwargs as parameters?
Using Pylint on Django code, I frequently get the W0613 warning. 90% of the time the cases are relevant, when the variable is declared and not used. But sometimes I think it's not. W0613: Unused argument 'kwargs' (unused-argument) Example that triggers the warning, a view that handles the 500 error: def error_500(request, *args, **kwargs): ''' A 500 error handling view ''' data = {} return render(request, '500.html', data) In the above case if we remove **kwargs, starting by Django 2.2 (as I remember), any 500 error situation leads to an unhandled exception which turns into a crash. So I am confused if Pylint really understands all the situations that can appear or not. Should I always treat the warning as a real warning because my code lacks something, or should I know these exceptional case? I noticed that by using the special Pylint for Django this type of warning usually doesn’t appear as often (pylint-django). But this is a case where the W0613 gets triggered even with the Pylint-django plugin loaded in Pylint: @csrf_exempt def ipn(sender, **kwargs): ''' Paypal IPN listener. It gets triggered after every each payment. ''' msg = sender.POST.get('payer_email') print(msg) sys.stdin = sender return HttpResponse(msg) -
DRF Return 201 if user has not voted and 400 if voted
I need to make simple API where I am sending a form that creates a vote instance and return 201 status code, but if user have already voted it returns 400 bad request. my models looks like: class Company(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) short_name = models.CharField(max_length=24) def __str__(self): return f"{self.short_name}" class Vote(models.Model): voter = models.ForeignKey(Company, on_delete=models.CASCADE) date_voted = models.DateField(auto_now=True) def __str__(self): return f"{self.id}/{self.voter}" views.py: class VoteView(CreateAPIView): queryset = Vote.objects.all() serializer_class = TaskCreateSerializer permission_classes = (IsAuthenticated,) def perform_create(self, serializer): pass and serializers class TaskCreateSerializer(ModelSerializer): class Meta: model = Vote fields = [ ] For now it just always returns 201. I am looking for a way where I can write logic that can check if Vote instance for current user exists then return Response(data={"message":"You have already voted"}, status=status.HTTP_400_BAD_REQUEST). The simplest way. -
Pagination controls in Django Rest Framework APIView
I tried to add pagination to my custom view, and pagination works but i don't have this pagination controls to change pages like it is in default pagination styles, how I can add this controls to my view? I was looking how to solve this problem but I hardly found anything, usuallly when I found some way to add pagination to custom view then it looks like this which I have, but it's not what I want because this doesn't give possibility to change page. pagination.py class CustomPagination(PageNumberPagination): page_size = 2 page_size_query_param = 'page_size' def get_paginated_response(self, data): return Response({ 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'count': self.page.paginator.count, 'limit': self.page_size, 'result': data }) views.py class TaskIndexAPIView(APIView): def filter_queryset(self, queryset): for obj in list(self.filter_backends): queryset = obj().filter_queryset(self.request, queryset, self) return queryset filter_backends = (filters.SearchFilter,) search_fields = ('name', 'description', 'user__username') def get_queryset(self): return Task.objects.all() def get(self, request): filtered_qs = self.filter_queryset(self.get_queryset()) tasks = filtered_qs for i in tasks: if i.date <= date.today() and i.status == 'NEW': i.delayed = 'This task is delayed' i.save() else: i.delayed = '' i.save() pagination_class = CustomPagination() page = pagination_class.paginate_queryset(tasks, request) serializer = IndexSerializer(page, many=True) return Response(serializer.data) -
Django Rest doesn't find validators `template_name` if `renderer_classes` is defined on `APIView`
I have this class: class TechSolutionDetail(APIView): renderer_classes = (TemplateHTMLRenderer,) def get(self, request, solution_name=None, format=None): techSolution = get_object_or_404(TechSolution, title=djangology_unquote(solution_name), deleted=False) return Response({'solution': techSolution}, template_name='core2/solution.html') # Update a techSolution @method_decorator(login_required) def post(self, request, solution_id, format=None): techSolution = get_object_or_404(TechSolution, pk=solution_id) serializer = TechSolutionsSerializer(techSolution, data=request.data) if serializer.is_valid(): return redirect(techSolution.issue.get_view_link()) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) If I have defined renderer_classes = (TemplateHTMLRenderer,) (needed to work with get method for return custom template), when the validator on post method fail, it doesn't find the template for validators. Returned a template response with no `template_name` attribute set on either the view or response It seems that I need to define template_name= on return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) on post method, but I can't find how. -
Django: How to add multiple class-based forms in a single view?
In my models.py I have a parent class with one child and one grandchild class. The parent has a one-to-many relationship with the child and the child has a one-to-many relationship with the grandchild. I would like to create a view (preferably a class-based view as these seem easiest to implement) which includes 3 class-based forms, one for the parent, multiple for the child and multiple for grandchild. What I would like to get is a view in which I can submit a form that will create one parent with multiple children with multiple grandchildren. How would I go best about designing such a view? models.py: class Parent(models.Model): parent_propery_one = models.CharField(max_length=200) parent_propery_two = models.CharField(max_length=100) parent_propery_three = models.TextField() parent_property_four = models.URLField(max_length=300, null=True) parent_property_five = models.DateTimeField(default=timezone.now) parent_property_six = models.DateTimeField(auto_now=True) parent_property_seven = models.ForeignKey(User, on_delete=models.PROTECT) ... class Child(models.Model): child_propery_one = models.CharField(max_length=200, unique=True) child_property_two = models.ForeignKey(Vilt, default=1, verbose_name="Bierviltje", on_delete=models.PROTECT) child_property_three = models.BooleanField() ... class Grandchild(models.Model): grandchild_property_one = models.CharField(max_length=200) grandchild_property_two = models.ForeignKey(Pand, default=1, verbose_name="Pand", on_delete=models.PROTECT) grandchild_property_three = models.DecimalField(max_digits=4, decimal_places=2) grandchild_property_four = models.PositiveIntegerField() grandchild_property_five = models.DecimalField(max_digits=8, decimal_places=2) grandchild_property_six = models.DecimalField(max_digits=8, decimal_places=2, default=0) grandchild_property_seven = models.DecimalField(max_digits=8, decimal_places=2, default=0) grandchild_property_eight = models.DecimalField(max_digits=8, decimal_places=2) views.py class ParentCreateView(LoginRequiredMixin, CreateView): model = Parent template_name = 'parent/parent_form.html' fields = ['parent_property_one', 'parent_property_two', 'parent_property_three', 'parent_property_four', … -
AttributeError: type object 'UserProfile' has no attribute 'USERNAME_FIELD'
I have just started with using custom user model. and after running make migrations and migrate , I am getting this error: AttributeError: type object 'UserProfile' has no attribute 'USERNAME_FIELD' here is my account/models.py from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): REQUIRED_FIELDS = ('user',) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username and here in TaskList/models.py I am trying to use user as Foreign key: from django.utils import timezone from Account.models import UserProfile from django.contrib.auth import get_user_model class ToDoList(models.Model): title = models.CharField(max_length=120) description = models.TextField(help_text='Explain your task!', blank=True) created_date = models.DateTimeField(default=timezone.now()) due_date = models.DateTimeField(default=timezone.now()) completed = models.BooleanField(default=False) Author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) in my settings.py I have added : AUTH_USER_MODEL = 'Account.UserProfile' -
Trying to convert Excel Fuzzy logic to Python function
I currently use the following fuzzy logic command in Excel to select a value from a reference table: =IF(E49>0,VLOOKUP(E49,'Ref Table'!$D$4:$E$22,2,FALSE),"--") I am trying to write a Django/Python function that will give the value closest to the numbers provided. (Example: Score = 14.5 - Value returned is 0.021) I installed fuzzywuzzy but I am not sure the best way to implement this. Below is an example of the function so far without the Fuzzy Logic. @register.simple_tag def get_perc(score): if score is None: return '--' elif score < 18.7: return '<1' else: pct_dict = {14: 0.016, 14.7: 0.021, 15.3: 0.026, 16: 0.034, 16.7: 0.04, 17.3: 0.05, 18: 0.07, 18.7: 0.09} if score in pct_dict.keys(): return pct_dict[score] else: return '--' (Example: Score = 14.5 - Value returned is 0.021) -
I can not pass FK through the form
I can not pass FK through the form I have the table Ngocio with the field CNPJ and I have the table Photo, and the field CNPJ as FK inside the table photo. But I am not table to automatically pass this form via FK, because I want to only display the photos of the user who is linked to the CNPJ field which is an FK models.py class Negocio(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) empresa = models.CharField(max_length=50, blank=False, verbose_name="Nome da Empresa") cnpj = models.CharField(max_length=19) class Photo(models.Model): cnpj = models.ForeignKey(Negocio, on_delete=models.CASCADE) title = models.CharField(max_length=255, blank=True) file = models.FileField(upload_to='photos/') uploaded_at = models.DateTimeField(auto_now_add=True) forms.py class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ('file', 'title', 'cnpj') views.py class ProgressBarUploadView(View): def get(self, request, cnpj): photos_list = Photo.objects.all() return render(self.request, 'photos/progress_bar_upload/index.html', {'photos': photos_list}) def post(self, request): time.sleep(2) form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) index.html <div style="margin-bottom: 20px;"> <button type="button" class="btn btn-primary js-upload-photos"> <span class="glyphicon glyphicon-cloud-upload"></span> Upload photos </button> <input id="fileupload" type="file" name="file" multiple style="display: none;" data-url="{% url 'progress_bar_upload' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> </div> <table id="gallery" class="table table-bordered"> <thead> <tr> <th>Photo</th> </tr> </thead> <tbody> {% for photo … -
django forms real time choose values fields
I've created a simple django form and all work fine. My problem is the choose field andress,I would like to get dynamic values(real time from table andress) without need to refresh the page any time to get last fields changes values. How can i do this using AJAX or maybe to create a JSON url with data from table andress and form get values from json ? someone to help me ? models.py class andress(models.Model): field_1 = models.CharField(max_length=100, blank=True, null=True) field_2 = models.CharField(max_length=150, blank=True, null=True) field_3 = models.CharField(max_length=254, blank=True, null=True) class customer(models.Model): field1 = models.CharField(max_length=100, blank=True, null=True) field2 = models.CharField(max_length=254,blank=True, null=True) andress_field= models.ForeignKey('andress', blank=True) createddate = models.DateTimeField(default=timezone.now) forms.py class customerForm(forms.ModelForm): andress_field= forms.ModelChoiceField(queryset=andress.objects.all()) class Meta: model = customer fields = (_all_) views.py def add_customer(request): if request.method == "POST": form = customerForm(request.POST) if form.is_valid(): note = form.save(commit=False) note.save() return HttpResponseRedirect('/customer/success/') else: form = customerForm() return render(request, 'add_customer.html',{'form':form}) html : <form enctype="multipart/form-data" method="post" action="">{% csrf_token %} <table> {{ form }} </table> <input value="add" type="submit"/> </form> -
Django: how to fetch records only that matches the region belongs to login user?
Data: Transaction table with region field (Oracle database-Only read access). Users tables in excel with region field. (I can add this to data in another database) LDAP Authentication is used. Using views(raw SQL query is used), I am showing aggregated data of transaction table. All users are seeing same data, as there is no filter on the region. Now, I want to aggregate only those records which login user's region belongs to. How can these implemented? My approach: Create region model Implement a Foreign Key with transaction tables(Is it possible?) What is best approach to this scenario? Please explain clearly. -
Why django admin page does not have any css included?
My problem is that when I set the DEBUG in settings.py file to False and add the localhost to ALLOWED_HOSTS, then my admin page gets empty of css. I want to solve the issue and know why it happens I have tried running the collectstatic command but it does not work. -
Why can I not show my current_url with my detail_view?
I am a bit confused. I have a django app and I am trying to print out my current urls. Or better my current path of my website. I have two views which I gave the names: list_view (for listing all instances) detail_view (for showing details of my instances) On my main page I'd like to get the current path. I do that like that: {% url 'detail_jobs' as detail %} {% url 'list_jobs' as list %} {{ detail }} {{ list }} My urls are: urlpatterns = [ path('jobs', list_jobs, name="list_jobs"), path('jobs/<int:id>/', detail_view, name="detail_jobs"), ] Now the {{list}} variable gives me back my current path, whereas the detail_view is giving me back nothing. Why? I don't get that.... I also have this function, which shouldn't interfere: def get_absolute_url(self): return reverse("detail_jobs", kwargs={"id" : self.id}) Any help is appreciated, thanks!! -
TypeError at ... <django.db.models.fields.related.ForeignKey> is not JSON serializable
When I trying to GET from my django api (or POST to) browser throws this: TypeError at /api/cutarea-fca-use/ <django.db.models.fields.related.ForeignKey> is not JSON serializable So what is wrong? All looks OK. Check and compare this api with api, which works well. Check my frontside. my serializers.py: from django.shortcuts import render from rest_framework import viewsets, generics, permissions, filters, decorators from django.contrib.gis.db import models from django.contrib.gis.geos import * from django.contrib.gis.db.models.proxy import SpatialProxy from .models import * from .serializers import * class FcaUseSet(viewsets.ModelViewSet): queryset = FcaUse.objects.all() serializer_class = FcaUseSerializer permission_classes = (permissions.AllowAny,) and my models.py: from classification_list.models import* from django.contrib.gis.db import models from django.contrib.gis.geos import * from django.contrib.gis.db.models.proxy import SpatialProxy class FcaUse(models.Model): id_fca = models.ForeignKey(Fca, blank=True, null=True, on_delete=models.DO_NOTHING) fell_form = models.ForeignKey(ShapeFelling, blank=True, null=True, on_delete=models.DO_NOTHING, verbose_name='kind1') fell_type = models.ForeignKey(TypeFelling, blank=True, null=True, on_delete=models.DO_NOTHING, verbose_name='kind2') main_type = models.ForeignKey(TypesForestry, blank=True, null=True, on_delete=models.DO_NOTHING, verbose_name='kind3') sortiment = models.ForeignKey(ForestSort, blank=True, null=True, on_delete=models.DO_NOTHING, verbose_name='compos') ed_izm = models.ForeignKey(UnitMeas, blank=True, null=True, on_delete=models.DO_NOTHING, verbose_name='values') vol_drew = models.FloatField(blank=True, null=True) fca_res = models.SmallIntegerField(blank=True, null=True) vol_res = models.FloatField(blank=True, null=True) kind_id_id = models.ForeignKey(ForestKind, blank=True, on_delete=models.DO_NOTHING, verbose_name='group'), class Meta: verbose_name = 'using' verbose_name_plural = 'usings' managed = True