Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImagesField in TabularInline in Django Admin
I have an Order model, and each order have many Images. Image Model: class Image(models.Model): order = models.ForeignKey(Order, on_delete=models.PROTECT, related_name='images') image = models.ImageField(upload_to=get_upload_path) how can i show images in TabularInline for each order in django admin? -
How to fix google console interface compute engine delete action using up request limits (compute.instances.listReferrers)
Using the webinterface of console.cloud.google.com to delete one Compute Engine VM instance triggers roughly 5 compute.instances.listReferrers requests per second for roughly 5 minutes. These spikes in api usage can be observed under "APIs & Services" -> "Metrics" (change to 1 hour, to improve visibility). I'm looking for a way to not trigger this many requests, for those can easily lock me out of the "2k requests per 100 seconds" quota. VM specs: - region us-east1 zone us-east1-b - 8vCPUs, 7.2GB memory - Ubuntu 18.04 LTS Minimal - preemtibility ON Deleting the VM instance under "Compute Engine" -> "VM instances" -> three stacked dots on the right side of the vm row -> "Delete" -> "Delete an Instane, Are you sure that you want to delte instance 'X'? (This will also delete boot disk 'X')" -> "Delete" Viewing activies in a different tab under "APIs & Services" -> "Metrics" (change to 1 hour, to improve visibility) shows a spike in activiy of compute.instances.listReferrers for several minutes afterwards. I'm located in EU if that matters for this issue. I expected to see a very short spike in activity, due to collection of resources that need to be deleted. But I didn't expect … -
web hosting for Django framework on windows
i have python back end for my websites with csv databases and have a Django framework for website i need a help regarding web hosting i want to make my website live can anyone guide me on this ? -
why does the above error occured during numpy installation
enter image description here Kindly, help me out to fix these error during numpy installation... -
How to run just one django test from file with VSCode?
I have some tests in tests.py and want to run just one of them with VSCode easily. Of course, I can do it via command line, but I think it is possible to configure VSCode to be able to do it via GUI. -
server error in my first server run in python
i just started learning python Django and as i run the server it shows me page not found. i went on to include my index page and it shows attribute error ('str' object has no attribute 'get') Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in pybop.urls, Django tried these URL patterns, in this order: admin/ products/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. AttributeError at /products/ 'str' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/products/ Django Version: 2.2 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'get' Exception Location: C:\Users\Ishaku Danladi\PycharmProjects\pydop\venv\lib\site-packages\django\middleware\clickjacking.py in process_response, line 26 Python Executable: C:\Users\Ishaku Danladi\PycharmProjects\pydop\venv\Scripts\python.exe Python Version: 3.7.2 Python Path: ['C:\\Users\\Ishaku Danladi\\PycharmProjects\\pydop', 'C:\\Users\\Ishaku ' 'Danladi\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\Ishaku Danladi\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\Ishaku Danladi\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\Ishaku Danladi\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\Users\\Ishaku Danladi\\PycharmProjects\\pydop\\venv', 'C:\\Users\\Ishaku Danladi\\PycharmProjects\\pydop\\venv\\lib\\site-packages', 'C:\\Users\\Ishaku ' 'Danladi\\PycharmProjects\\pydop\\venv\\lib\\site-packages\\setuptools-40.8.0-py3.7.egg', 'C:\\Users\\Ishaku ' 'Danladi\\PycharmProjects\\pydop\\venv\\lib\\site-packages\\pip-19.0.3-py3.7.egg'] Server time: Sun, 7 Apr 2019 17:10:12 +0000 -
How to sort QuerySet with property field Django
I have a model as class FooModel(models.Model): field_1 = models.IntegerField() field_2 = models.IntegerField() @property def field_sum(self): return self.field_1 + self.field_2 How can I sort the queryset with field_sum field? FooModel.objects.all().order_by('field_sum') is giving me error. Thanks in advance -
GET request with postman is working, but it does not work with python (HTTPSConnectionPool)
I am trying to get JSON from an API which then can be showed on a website which is built with django and the API is made with the rest_framework. I have tried both Requests and http.client but I got the same error which is: HTTPSConnectionPool(host='webpageUrl' port=443): Max retries exceeded with url: /api/donations (Caused by ConnectTimeoutError( I have tried debugging with GET requests in Postman which works fine, however when I either use the examples provided in the documentation of the Requests library or use the code snippet generated in Postman I get the aforementioned error. Furthermore, I previously had Basic Authentication which I thought were the root of the problem, I therefore turned the authentication off but it didn't work. This is the code I am currently trying: import requests def available_donations(request): assert isinstance(request,HttpRequest) response = requests.get("webpageUrl/api/donations", headers={'Content-Type':'application/json'}, timeout=5) return render( request, 'app/availableDonations.html', {'donation':response}, { 'title':'Overview of available donations' }) I expected to get an error about the rendering of the webpage, however from what I could read from different stackoverflow questions the error means that it couldn't find the webpage. Thanks in advance! -
Django keep dropdown selected language after page reload
I have a form to change languages (3 languages so far) and it works except that when the page reloads, the content changes to the new language but the selected option from the dropdown is lost (instead shows default language). How can I keep the selected language after page reload? Any help is appreciated <form action="{% url 'set_language' %}" method="POST"> {% csrf_token %} <input type="hidden" id="languageSwitcher" name="selected" value="{{ redirect_to}}"> <select name ="language" id="languageField"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages%} <option value="{{language.code}}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{language.name_local}} </option> {% endfor %} </select> <input type="submit" id ="languageSwitcher" value="Change"> </form> -
Wagtail page model: foreign key entity + multiple parameters
i'm using Wagtail CMS to create product catalogue. I created basic page type for product: <pre> class Product(Page): </pre> It has basic fields like title, description, image aso. But i need "something special": There is special part available in many variants and each product can have some of them. So I created another model, very simple by: <pre> @register_snippet class Variant(models.Model): </pre> to store all variants. Variant has name and image. There are about 200 products and 30 variants. My problem is and I don't know how to manage in Wagtail two tasks: to link Product with Variants (foreign key) with many-to-many relation to select product related variants in same page as other page entities each relations has additional parameters (2 params) which are relation specific (material and diameter) and again I haven't found how to display and manage such relations in page editor I know that Django can hadle it by inline formsets (django admin supports it out of box), but is there Wagtail-way to get this done and editable by Wagtail editor? I prefer to manage whole product in the same place, not relations separated in django-admin. Thanks for any help or advice. -
How to update image input with django forms and template
I have a django project where a user has a profile and can upload a profile picture. The models.py is: `class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=64,blank=True) profilePic = models.ImageField(blank=True, null=True, upload_to= "profile/") phoneNumber = models.CharField(max_length=12,blank=True) streetAddress = models.CharField(max_length=64,blank=True)` On my site, the user can edit his profile including the profile picture. To do so, I have a form, where the initial values are the ones initially stored. The forms.py is: class EditProfile(forms.ModelForm): def __init__(self, profile, *args, **kwargs): self.profile = profile super(EditProfile, self).__init__(*args, **kwargs) self.fields['name'] = forms.CharField(label='Name:', initial= profile.name,required=False) self.fields['phoneNumber'] = forms.CharField(label= "Phone Number:", initial= profile.phoneNumber,required=False) self.fields['streetAddress'] = forms.CharField(label='Street Address and/or Postal Code:', initial= profile.streetAddress,required=False) self.fields['profilePic'] = forms.ImageField(label='Profile Picture:', initial= profile.profilePic,required=False) class Meta: model = Profile fields = ("name", "phoneNumber","streetAddress", "profilePic") This part works great, and on my site I can see the stored values. The problem is when I try to edit them and submit the form. My views.py is: def settings(request): user= request.user if request.method == 'GET': userProfile = Profile.objects.get(user=user) f1= UserProfile(user=request.user) f2= EditProfile(profile=userProfile) return render(request, 'listings/settings.html', {'form': f1,'form2': f2}) elif request.method == 'POST': userProfile = Profile.objects.get(user=user) f1= UserProfile(user=request.user) f2= EditProfile(profile=userProfile) name= request.POST["name"] phoneNumber = request.POST["phoneNumber"] streetAddress = request.POST["streetAddress"] Profile.objects.filter(user=user).update(name= name, phoneNumber = phoneNumber, streetAddress = … -
how to create a Django form/formset with Modelchoice fields having values from different querysets
I would like to display simultaneously several modelchoicefields, each of them with data from the same model but having different querysets. To do so shall I use one formset or several forms to pass to the template? I have tried with the formset. Form: class ValueForm(forms.Form): value = forms.ModelChoiceField(queryset = ValueTable.objects.all()) View: filter_value1 = ValueTabel.objects.filter(group = 1) filter_value2 = ValueTabel.objects.filter(group = 3) TmpFormSet = formset_factory(ValueForm, extra=0) form = TmpFormSet(queryset=filter_value1,filter_value2) Here are my records in the database: ValueTable(group, value): 1, Value1 1, Value2 1, Value3 2, Value4 3, Value5 3, Value6 Group(group, attribute) 1, attribute1 2, attribute2 3, attribute1 Selecting the attribute1 on the model Group (record 1 and 3), I would display simultaneously two forms with the following choices: modelchoicefield 1: Value1 Value2 Value3 modelchoicefield 2: Value5 Value6 How can I add manually to the formset the two queryset? -
Django how to get the users who are not in many2many field?
'models.py' class StaffProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile") staff_user = models.ManyToManyField(User, null=True, blank=True, related_name="staff_user") mobile_number = models.CharField(max_length=14, validators=[RegexValidator(r'^\d{1,10}$')]) fcm_token = models.CharField(max_length=256, null=True, blank=True) manager = models.BooleanField(default=False) def __str__(self): return self.user.username 'forms.py' class ManagerSignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, label='Name') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') mobile_number = forms.CharField(max_length=14, min_length=10, ) staff_user = forms.ModelMultipleChoiceField(queryset=User.objects.filter(is_staff=False),required=True) def __init__(self, *args, **kwargs): all_user_list = User.objects.filter(is_superuser=False,is_staff=True) all_staff_profile = StaffProfile.objects.get(staff_user__in=all_user_list) super(ManagerSignUpForm, self).__init__(*args, **kwargs) # self.fields['staff_user'] = forms.ModelChoiceField(queryset=after_exclude) I want to show(Append) the Users who are not already exists in staff_user(M2M) field in entire StaffProfile model. Note: I am Extending User Model -
AJAX call to refresh values without reloading page doesn't show new values all the times
I am building an auction project and in template I am making an AJAΧ call when form submitted from template to view in order to reload the page without refreshing but something is wrong sometimes. Although call is successful, new values aren't shown all the times although altered in database. When i hit F5 new values are shown. live-auction-details.html <form id="bid" >{% csrf_token %} <input id="auction_id" type="hidden" value="{{ auction.id }}"> <button type="submit">Bid</button> </form> <script> $('#bid').on('submit', function(event){ //bid is the name of the form $.ajax({ method: 'POST', url: '{% url 'auction:live-auction-details' auction.id %}', data: { auction_id: $('#auction_id').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, success: function(data) { console.log(data); } }); }); views.py def live_auction_details(request, pk): try: auction = Auction.objects.get(id=pk, status=1) except Auction.DoesNotExist: raise Http404("auction not found") if request.method == 'POST': // update records in database if request.user.is_authenticated(): # can user bid ? if request.user.player.credits >= auction.credit_charge: player_can_bid = True # is player registered ? if AuctionPlayers.objects.filter(auction_id=auction, auction_player_id=request.user.player.id): player_is_registered = True context = { 'auction': auction, 'player_can_bid': player_can_bid, 'player_is_registered': player_is_registered, } return render(request, 'auction/live-auction-details.html', context) -
Django ordering by the sum of two fields not working
I am trying to order my users by answeredQuestion / questions I have the following model: class User(models.Model): firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) username = models.CharField(max_length=100) questions = models.IntegerField(null=True) answeredQuestions = models.IntegerField(null=True) And I am trying the following: users = User.objects.extra( select={'fieldsum': 'answeredQuestions / questions'}, order_by=('-fieldsum',) Yet, when changing out the ('-fieldsum') for just ('fieldsum'), it still produces the same result. I have also tried the following: users = User.objects.annotate(total=F('answeredQuestions') / F('questions')).order_by('total') But even using this, I always get the same result, and the Users remain ordered wrong. -
django csrf error during file upload in admin
I have a strange behaviour of the django admin (django 1.11) - on both development and production: When I upload files that are larger than about 1.5 MB I get a csrf verification error. Files smaller than that limit I can upload without any trouble. There is nothing special in the model and admin: class Literatur(models.Model): name= models.CharField(max_length=80) document = models.FileField(upload_to="docs/",null=True, blank=True) Admin.py admin.site.register(Literatur) Where can I look to resolve this issue? -
Passing Context From one view to another view
I have two views one that accepts inputs and the other for confirmation and execution of an action. My problem is that the context data from the first view seems inaccessible in the confirmation view. Here is the input view. PreprocessinputationView: def PreprocessInputationView(request, **kwargs): proj_pk = kwargs.get('pk') project = Project.objects.get(id=proj_pk) df = pd.read_csv(project.base_file) n_cols = df.keys context = {} context['df'] = df context['n_cols'] = n_cols context['project'] = project if request.method == 'POST': # try: checked_value = request.POST.getlist(u'predictors') method = ''.join(request.POST.getlist(u'method')) if checked_value and method: context['checked_value'] = checked_value context['method'] = method return render(request, 'projects/preprocess/confirm_inputation.html', context) return render(request, 'projects/preprocess/preprocess_inputation.html', context) The confirmation view goes here. ConfirmInputationView: def ConfirmInputationView(request, context): print('method:', context['method']) project = context['project'] df = pd.read_csv(project.base_file) n_cols = df.keys filename = project.base_file.name tmp = filename.split('/') filename = str(tmp[1:]) if request.method == 'POST': # try: checked_value = context['checked_value'] method = context['method'] if checked_value and (method=='mean'): df[checked_value].fillna(df[checked_value].mean()) # df.drop(columns=checked_values, inplace=True) new_df = df.to_csv(index=False) updated_file = ContentFile(new_df) updated_file.name = filename project.base_file = updated_file project.save() str_checked_value = ', '.join(checked_value) context['str_checked_value'] = str_checked_value if str_checked_value: messages.success(request, f'Inputation to column(s) {str_checked_value} successful!') return render(request, 'projects/preprocess/preprocess_inputation.html', context) The confirmation template. Confirm_inputation.html: {% extends "base.html" %} {% block page_heading %} <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800">Delete … -
unable to change validate field error message in Model serializer
I'm working on ModelSerializer I'm facing these below issues. 1) Unable to validate .validate(self, data) method as I want to return a custom validator message which is not working. model.py class BlogModel(models.Model): BLOG_STATUS = ( ('PUBLISH', 'Publish'), ('DRAFT', 'Draft'), ) blog_id = models.AutoField(primary_key=True) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blogs') title = models.CharField(max_length=255) content = models.TextField(blank=True, null=True) status = models.CharField(max_length=7, choices=BLOG_STATUS) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta(): db_table = 'blogs' verbose_name = 'Blog' verbose_name_plural = 'Blogs' def __str__(self): return self.title serializers.py import datetime from django.contrib.auth.models import User from django.utils.timezone import now from rest_framework import serializers from rest_framework.serializers import ModelSerializer,Serializer from blogs.models import BlogModel, BlogFilesModel class UserSerializer(ModelSerializer): class Meta: model = User fields = '__all__' # exclude = ['password'] class BlogFilesSerializer(ModelSerializer): count_files = serializers.IntegerField(required=False) class Meta: model = BlogFilesModel fields = ('blog_files_id', 'blog', 'path', 'created_at', 'updated_at', 'count_files') def get_path(self, obj): formatted_date = obj.created_at.strftime("%d-%m-%Y") return formatted_date class BlogSerializer(ModelSerializer): blog_files = serializers.SerializerMethodField() def get_blog_files(self, obj): info = BlogFilesSerializer(BlogFilesModel.objects.filter( blog=obj).order_by('-pk'), many=True) if info.data: for i in info.data: user_detail = User.objects.get(pk=obj.user.id) i.__setitem__('user_detail', UserSerializer(user_detail).data) if i.get('user_detail'): try: del i['user_detail']['password'] except expression as identifier: pass return info.data blog_created_at=serializers.SerializerMethodField() def get_blog_created_at(self, obj): formatted_date=obj.created_at.strftime("%d-%m-%Y") return formatted_date def validate(self, data): if data.get('title') == "": #this below error message not … -
How to send Python Object class instance via HttpResponse in Python
I am trying to send an instance of Python object class as my Response object. The Python object has some references to other function as well and the implementation looks something like this: class MyObject(object): outside_fn = outside_fn() <other implementation> I have tried sending using Django Rest Framework and using Flask framework as well, but I am unable to do it. I am showing some of the approaches what I have done below: Django: my_object = MyObject() # Try 1 response = HttpResponse(json.dumps(my_object), content_type='application/json') return response # Try 2 from django.core import serializers data_ = {'data': my_object} d = serializers.serialize('json', data_) response = HttpResponse(d, content_type='application/json') return response # Try 3 response = HttpResponse(my_object, content_type='application/octet-stream') return response Flask: from flask import Flask, jsonify data_ = {'data': my_object} return jsonify(data_) I get error message like MyObject is not serializable. How do I go about solving my problem. Thanks in advance. -
Datetime picker plugin shows date picker but not time picker
Found this great plugin, https://tempusdominus.github.io/bootstrap-4/Installing/, called django-tempus-dominus. But as the title explains the time picker is not showing. I've raised an issue on their github page - https://github.com/FlipperPA/django-tempus-dominus/issues/47 - but also wanted to check if somebody had had something similar. I have followed their simple example at - https://pypi.org/project/django-tempus-dominus/ - for the datetimepicker and it isn't working. I also tried just the time picker and it DOES work. Here is my set up - base.generic.html <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>Local Library</title>{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Include FontAwesome; required for icon display --> <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <!-- Add additional CSS in static file --> {{ form.media }} </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-10 "> {% block content %}{% endblock %} {% block pagination %}{% endblock %} {% block footer %}{% endblock %} </div> </div> </div> </body> </html> auction_form.html inherits - {% extends "base_generic.html" %} {% block content %} <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> {% endblock %} forms.py: from django import forms from django.core.exceptions import ValidationError from django.utils import timezone from django.utils.translation … -
How to valid email in view and redirect to dependency urls
I'm trying to make custom email exceptions of this dependency: https://github.com/anx-ckreuzberger/django-rest-passwordreset I've tried use redirect() and requests.post(): response = redirect(django_rest_passwordreset.urls) response = requests.post(django_rest_passwordreset.urls (try convert to url), data=request.data) #it's stupid... #urls.py url(r'^password_reset/', views.PasswordResetHandler.as_view()), #views.py class PasswordResetHandler(APIView): def post(self, request, format=None): try: if '@' not in request.data['email']: return Response({'status': 'Error', 'error': 'Invalid email address'}, status=404) if User.objects.filter(email=request.data['email']): #response = ... # redirect to 'django_rest_passwordreset.urls' return Response(some_response) return Response({'status': 'Error', 'error': 'Email not found'}, status=404) except: return Response({'status': 'Error', 'error': 'Invalid data - fileds required: email'}, status=404) I expect custom exceptions for invalid email: api/password_reset -> invalid_email, email_not_found api/password_reset/confirm -> invalid reset token, missing token, invalid_new_password How to do it in this way. Should I do it in different way? -
Return a response with a list of serializers Django REST Framework
I'm coding some backend software for a second-hand selling app using Django and DjangoRestFramework. Right now, I'm trying to send a Response object that contains a list of products, but I seem not to be able to return an actual list of products, as I'm getting an error saying ListSerializer is not JSON serializable. I've tried both using the serializer constructor like this: ProductoSerializer(products, many=True) And by creating a list of ProductoSerializer.data and then creating the Response object with that. Here's the serializers that I'm using: class UserSerializer(serializers.HyperlinkedModelSerializer): ciudad = serializers.SerializerMethodField() conectado = serializers.SerializerMethodField() class Meta: model = Usuario fields = ('uid', 'nombre', 'ciudad', 'conectado') def get_ciudad(self, obj): geolocator = Nominatim(user_agent="bookalo") location = geolocator.reverse(str(obj.latitud_registro) + ',' + str(obj.longitud_registro)) return location.raw['address']['city'] def get_conectado(self, obj): ahora = timezone.now() result = relativedelta(ahora, obj.ultima_conexion) return result.days == 0 and result.hours == 0 and result.months == 0 and result.years == 0 and result.minutes < 5 class TagSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Tag fields = ('nombre') class MultimediaSerializer(serializers.HyperlinkedModelSerializer): contenido_url = serializers.SerializerMethodField() class Meta: model = ContenidoMultimedia fields = ('contenido_url', 'orden_en_producto') def get_contenido_url(self, obj): return obj.contenido.url class MiniProductoSerializer(serializers.HyperlinkedModelSerializer): contenido_multimedia = serializers.SerializerMethodField() class Meta: model = Producto fields = ('nombre', 'precio', 'estado_venta', 'contenido_multimedia') def get_contenido_multimedia(self, obj): contenido = … -
Save Image From Class Based View
I can't Save the a Image from My Class Based View I am relatively new to Django, and I might have missed something. views.py class PostCreateView(LoginRequiredMixin,CreateView): model = Post fields = ['title', 'content','image'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) models.py class Post(models.Model): title = models.CharField(max_length = 100) content = models.TextField() created_on = models.TimeField(auto_now = True) author = models.ForeignKey(User, on_delete = models.CASCADE,) image = models.ImageField(default = 'default.jpg',upload_to = 'post_pics',) def save(self, *args, **kwargs): super().save(*args,**kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) def __str__(self): return self.title def get_absolute_url(self): return reverse('network:post_detail', kwargs={'pk':self.pk}) urls.py app_name = 'network' urlpatterns = [ path('', user_views.PostList.as_view(), name = 'homepage'), path('post/<int:pk>/', user_views.PostDetail.as_view(), name = 'post_detail'), path('post/new/', user_views.PostCreateView.as_view(), name = 'post_create'), path('post/<int:pk>/update', user_views.PostUpdateView.as_view(), name = 'post_update'), path('post/<int:pk>/delete', user_views.PostDeleteView.as_view(), name = 'post_delete'), path('register/', user_views.register, name="register"), path('login/',auth_views.LoginView.as_view(), name="login"), #we can add the template path manually in as_view() path('logout/',auth_views.LogoutView.as_view(), name="logout"), #default is registration/logout.html path('profile/<int:pk>',user_views.ProfileDetail.as_view(),name = 'profile_detail'), path('post/new/',user_views.PostCreateView.as_view(),name = 'post-create'), #<app_name>/<model>_form.html ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I expected that the Post comes with the Image I saved but actually it comes with the Default Image -
Stripe returns error: "You cannot change `legal_entity[personal_id_number]` via API if an account is verified." How to resolve?
It seems contradictory for Stripe to ask for a personal ID number (under fields_needed, or under requirements under the latest API version), and then say I can't update it because the account is verified. My webhook has been throwing errors because of this (I set up a webhook for the account.updated event as suggested by Stripe). Any solution to this? Or should I just ignore the field that's needed under fields_needed if the account is verified? -
Getting an exception raised by django.contrib.staticfiles.views.serve
I am naive in Django. Trying out a few pieces of stuff here. I was working with static files and have got stuck here. Please help me out here. I am very much confused about static_root and static_dirs. I am following an online tutorial where the static root has not been used and their project is working fine. If am trying that I facing lots of errors and exceptions. Here is my view: from django.shortcuts import render from django.http import HttpResponse def index(request): my_dict={'insert_me':"Hello I am from views.py"} return render(request,'first_app/index.html',context=my_dict) Here is my projects urls: from django.contrib import admin from django.conf.urls import url from django.conf.urls import include from first_app import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^first_app/',include('first_app.urls')), url(r'^admin/', admin.site.urls),] urlpatterns += staticfiles_urlpatterns() Here is my apps url: from django.conf.urls import url from first_app import views from django.contrib import admin urlpatterns= [ url(r'', views.index, name='index'),] and here is my setting: """ Django settings for Twenty3rdMrach project. Generated by 'django-admin startproject' using Django 2.1.2. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR …