Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why private route is not accessible even after login success?
If I am logged out and try to access private route I am successfully redirected to login page, but even after login private route is not accessible to me code in App.js App.js code in PrivateRoute.js PrivateRoute.js -
Why does Django REST Framework Router break query parameter filtering?
In the Django REST Framework Tutorial quickstart, views are added to the default router: // project/urls.py router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) My project layout is project/ stuffs/ I include the stuffs application in the default router: router.register(r'stuffs', views.StuffViewSet) The stuffs/ endpoint is then nicely listed in the API Root list of endpoints: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "users": "http://localhost:8000/users/", "groups": "http://localhost:8000/groups/", "stuffs": "http://localhost:8000/stuffs/" } A Stuff object has a relationship to a owner model class and to filter for objects belonging to a certain owner, I intend to use a request such as: stuffs/?owner_id=abc In order to do so, and here is where I'm not sure if it is correct, I introduced an urls.py configuration in the stuffs app: // stuffs/urls.py urlpatterns = format_suffix_patterns([ path('stuffs/', stuffs_views.StuffList.as_view()), path('stuffs/<int:pk>/', stuffs_views.StuffDetail.as_view()), re_path(r'^stuffs/(?P<owner_id>.+)$', stuffs_views.StuffsList.as_view()) ]) using the below StuffsList class based view: class StuffList(generics.ListCreateAPIView): serializer_class = StuffSerializer def get_queryset(self): queryset = Stuff.objects.all() owner_id = self.request.query_params.get('owner_id') if owner_id is not None: queryset = queryset.filter(owner__short_id=short_id) return queryset I'm pretty sure this view is correct, because when I remove the View Set from the default router, the query works. However, when the viewset is registered in the default router, when … -
Display the ImageField in HTML with Django 3.2
Im begginer Dev, i got some trouble to understand the mechanics of ImageField. I made a model Article with an image to illustrate it, in my admin i also added the field that made possible the injection in a folder named uploads. I saw many tutorial who explain how to do it, but i have trouble to apply it. I made migrations and migrate, and it work. From my admin pannel i can put the file i want and it drag in into the "uploads" folder. Now i want to display this ImageField from the HTML. I know, urls and views need to be edited for the thing i want, but i miss understand how, after readed some tutorials i still failling. Here is my project and the related files: admin models urls html views I also thanks ppl who will help me :) -
Django:How to add field dynamically?
I want to dynamically add new input field for cylinder to a Django formset, so that when the user clicks an "add" button it runs JavaScript that adds a new input for cylinder field in IssueForm to the page but instead of adding only one field, the entire form is getting added. Expected Output:- How do I execute for this or there is any better way of doing this? Model:- class IssueCylinder(models.Model): cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE) userName=models.CharField(max_length=60,null=False) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Available': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued')) CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(issue_Date=self.issueDate) CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(issue_user=self.userName) super().save(*args,**kwargs) def __str__(self): return str(self.userName) view :- @login_required def issue(request): if not request.user.is_superuser: return redirect('index') issueformset=modelformset_factory(IssueCylinder,form=IssueForm,extra=1) if request.method=='POST': formset=issueformset(request.POST or None) insatnce=formset.save(commit=False) if formset.is_valid(): for form in formset: form.save() formset=issueformset(queryset=IssueCylinder.objects.none()) return render(request,'issue/issue_form.html',{'formset':formset}) form:- class IssueForm(forms.ModelForm): class Meta: model=IssueCylinder fields='__all__' Template:- <form id="form-container" method="POST"> {% csrf_token %} {{formset.management_form}} {% for form in formset %} <div class="row form-row spacer"> <div class="col-2"> <label>{{form.cylinder.label}}</label><br><br> <label>{{form.issueDate.label}}</label><br> <label>{{form.userName.label}}</label> <hr> </div> <div class="col-4 "> <div class="input-group " > {{form.cylinder}} <div class="input-group-append"> <button class="btn btn-success add-form-row" id="add_more">+</button> </div> </div> <div class="input-group"> <br> {{form.issueDate}} {{form.userName}} </div> </div> </div> {% endfor %} <div class="row spacer"> <div class="col-4 offset-2"> <button type="submit" class="btn btn-block btn-primary">Submit</button> </div> </div> </form> script:- <script type='text/javascript'> $(document).ready(function () { $('body').on('click', '#add_more', function … -
Import "blocktunes" could not be resolved Pylance report Missing Imports
urls.py from django.contrib import admin from django.urls import path, include from blocktunes import views #error in blocktunes urlpatterns = [ path('', include('blocktunes.urls')), path('admin/', admin.site.urls), path('', views.UserRegister_view) ] Why is it showing missing imports? settings.py INSTALLED_APPS = [ 'blocktunes.apps.blocktunesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] PLEASE HELP. Image link of structure of apps [1]: https://i.stack.imgur.com/YhPEg.png -
Django - Suggestions with building a minimal one-to-one chat app (Potentially using Web Sockets)
My next challenge is to build a minimal realtime chat application where my users of my application can send direct one-to-one messages to each other. With this being said, I have researched online in to building realtime chat apps and many of which I have seen refer to building "group" chats through using Django Channels. Secondly, I have also looked in to tutorials which provide guidance on how to build an AJAX refresh based chat app (without Web Sockets) but I thought this approach would be inefficient with the heavy strain on my server this could cause as my user base grows. I am wanting to reach out on here and ask - Is there any existing Django Libraries out there for building efficient one-to-one chat apps (Without WebSockets) or would I be better served using WebSockets? And if I was to use the WebSockets approach with Django-Channels and ASGI, are there any recommended tutorials or chat libraries which I can use to help kickstart the development of my chat app? I'm eager to learn, but I just need a little direction with understanding where my initial starting point and focus should be. As simple as what my vision is, … -
Show and modify local Json file from a web page using python
ive written a script, that stores its configuration in a local json file. The script runs in a continuous loop and loads the configuration at startup. Because i will run my script in a headless machine, i thought on writing a small web app to allow me to view and modify this json file and reload the script if a change is made Also it would be handy to show some stats and maybe the console output logs in the web page I can program in python but im totally new in web development. I did some research and flask looks to be the easiest way My idea is to load the json tree in a web page in a user friendly way, and allow you to modify the 'value' part of each 'key' in the json from a nice edit box or something. I would also need to add key value sub pairs for some given keys Then at the bottom one would have a 'reload' button that would save the updated json file into the file system and reload the script with its new configuration. Im not sure if its best to keep this two separated, one as … -
When I try to do collect static in my Django project i got Post-processing staticfiles\static\css\style.css failed
I am trying this i did not got any solution .. I said Post-processing 'staticfiles\static\css\style.css' failed! but there is no problem on my file . My this project in running on machine without any error you can check my repo here https://github.com/programmer-Quazi/personal-blog.git This is my terminal output after giving this command python manage.py collectstatic Post-processing 'staticfiles\static\css\style.css' failed! Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\faald\AppData\Roaming\Python\Python38\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\faald\AppData\Roaming\Python\Python38\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\faald\AppData\Roaming\Python\Python38\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\faald\AppData\Roaming\Python\Python38\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\faald\AppData\Roaming\Python\Python38\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 187, in handle collected = self.collect() File "C:\Users\faald\AppData\Roaming\Python\Python38\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 134, in collect raise processed whitenoise.storage.MissingFileError: The file 'staticfiles/static/img/elements/primary-check.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x000001F9F6FF3280>. The CSS file 'staticfiles\static\css\style.css' references a file which could not be found: staticfiles/static/img/elements/primary-check.png Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location. my settigns.py file is """ Django settings for djangoProject4 project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full … -
Django: reducing inventory and change model display format in admin
I'm trying to make a website where users can register an account and sign up for different courses via stripe. I buildt the system with an Order -> OrderItem -> Product (Kurs) model. Thanks to great tutorials I have been able to make most of what I want but I am still a beginner and now I'm having a hard time figuring stuff out. After signing up an account the users can view all courses that have been added to the course model and add them to a basket and procceed to checkout the orders in the basket. When stripe signals the payment_intent_succeeded all the products from that order change billing_status to 'True'. I am able to see all Orders and the OrderItem from the django admin view but now I am missing two features that I can't figure out how to add. 1. To reduce integerField "ledige_plasser" in the Product model (called Kurs in my code) model after each purchase is made. 2. To view the all the orders for a certain Kurs (product) in the django admin in a readable way. Is there any way I can setup the django admin to display all users that have signed … -
Is Heroku using Dedicated Servers
Is Heroku using Dedicated Servers? I am using Django and I want to know whether Heroku is using Dedicated servers or not, and what Django Deploy platforms use Dedicated Servers, Thanks. -
getting unicode characters as response when trying to download excel file using Django-Rest-Framework
I am working on application where I am required to download the excel files saved in the project media directory on clicking the download button using react. I have written an api for it, from the answers I found to download the file using django rest framework but postman is giving me a response that is unicode characters. Here is my DRF views: def download(self): file_name= 'reports.xlsx' file_path = (settings.MEDIA_ROOT +'/'+ file_name).replace('\\', '/') file_wrapper = FileWrapper(open(file_path,'rb')) file_mimetype = mimetypes.guess_type(file_path) response = HttpResponse(file_wrapper, content_type=file_mimetype ) response['X-Sendfile'] = file_path response['Content-Length'] = os.stat(file_path).st_size response['Content-Disposition'] = 'attachment; filename=%s' % str(file_name) return response I would really appreciate if somebody could help me resolve it. Thank you! -
How to restrict non logged in users from accessing the api data
Here are the permissions.py from rest_framework import permissions from rest_framework.permissions import BasePermission, SAFE_METHODS class ReadOnly(permissions.BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS How to modify this so only logged in users can access the data -
django-simple-captcha Don't work when DEBUG=False
I'm working on Django 2.2 and DjangoCMS 3.7.4 I'm facing a problem with django-simple-captacha I've follow the instalation guide (https://django-simple-captcha.readthedocs.io/en/latest/usage.html#installation)It's working when DEBUG=True but when Debug=False in settings.py I got a 500 on when I try to send a contact form. Here my urls.py: # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from cms.sitemaps import CMSSitemap from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.contrib.sitemaps.views import sitemap from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.static import serve from django.views.generic import TemplateView from .views import career_form, contact_form, mentions admin.autodiscover() urlpatterns = [ url(r'^mentions/$', mentions, name='mentions'), url(r'^sitemap\.xml$', sitemap, {'sitemaps': {'cmspages': CMSSitemap}}), ] urlpatterns += i18n_patterns( url(r'^captcha/', include('captcha.urls')), url(r'^admin/', admin.site.urls), # NOQA url(r'^ckeditor/', include('ckeditor_uploader.urls')), url(r'^', include('cms.urls')), url(r'^career/', include('career.urls')), url(r'^carreer_form', career_form, name='career_form'), url(r'^contact_form', contact_form, name='contact_form'), ) urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # This is only needed when using runserver. if settings.DEBUG: urlpatterns = [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), ] + staticfiles_urlpatterns() + urlpatterns My installed app in settings.py: INSTALLED_APPS = [ 'djangocms_admin_style', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.staticfiles', 'django.contrib.messages', 'ckeditor', 'ckeditor_uploader', 'djangocms_text_ckeditor', 'cms', 'menus', 'sekizai', 'treebeard', 'filer', 'easy_thumbnails', 'djangocms_column', 'djangocms_file', 'djangocms_link', 'djangocms_picture', 'djangocms_style', 'djangocms_snippet', 'djangocms_googlemap', 'djangocms_video', 'absolute', … -
Spring boot looks more boiler plate than Django
In Django to create a model we have to just do: class Sample(models.Model): sample = models.CharField(max_length=100) and later to all the operations are very easy Sample(sample="test").save(), Sample.objects.all() etc Where as in spring boot we have to first define an entity and then a repository for that entity and then do all the operations @Entity @Table(name = "sample") public class Sample { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String sample; public Sample() { } public Sample(String sample) { this.sample = sample; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSample() { return sample; } public void setSample(String name) { this.sample = sample; } @Repository public interface SampleRepository extends JpaRepository<Sample, Long> { } Then @Service public class SampleService { @Autowired private SampleRepository sampleRepository; public List<Sample> findAll() { return (List<Sample>) SampleRepository.findAll(); } } Is there any easy way like Django. Even the time to understand to this level is also a lot -
how to send user it with access jwt token in drf
Currently I'm using JWT token in django rest framework, while using login api, i just get refresh token & access token. I'm wondring if could send the user id with these tokens too(i have no idea on if it's possible or not) currently { "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYyMjk3NzY2OCwianRpIjoiYWE2ZTk0NWNiYjRjNDAxZmFiMmM2NWEzZWQ1Yzg5NDUiLCJ1c2VyX2lkIjoxfQ.a54fcfa0ZsFrfVrb1VTdRO6bXY47NOuZqO8T1I3yKCc", "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjU0NDI3MjY4LCJqdGkiOiI1ODEwNDQyZWU3ZTM0MzczYTBkNmEzMDBkYmRmYTg2MyIsInVzZXJfaWQiOjF9.d6fmMq6ddsCaCyAEbDDaE5aja04LxYZmRP8WHfpmJqs" } what i want { "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYyMjk3NzY2OCwianRpIjoiYWE2ZTk0NWNiYjRjNDAxZmFiMmM2NWEzZWQ1Yzg5NDUiLCJ1c2VyX2lkIjoxfQ.a54fcfa0ZsFrfVrb1VTdRO6bXY47NOuZqO8T1I3yKCc", "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjU0NDI3MjY4LCJqdGkiOiI1ODEwNDQyZWU3ZTM0MzczYTBkNmEzMDBkYmRmYTg2MyIsInVzZXJfaWQiOjF9.d6fmMq6ddsCaCyAEbDDaE5aja04LxYZmRP8WHfpmJqs", "userid": <id> } -
Migrate native app (android/ios) to react
I have a situation that maybe you can help and would love to hear your opinions. I have an app from a startup with android and iOS version and the backend with Django. Right now is so expensive to maintain because there’s different technologies and I was wondering if to migrate to a multi platform technology as Reactjs (PWA) and maybe use firebase as a service for backend. The app is live now (pinwins) but it’s a MBP that needs corrections and development. Its has been developed by an agencie and for the moment I can count on a junior profile on react. What do you think? Would you keep working in this one or would you migrate to a new technology with more agile development? (In this case what would be the best way?) Thanks a lot in advance, Have a nice weekend! -
hi, I want to add trainer model to django , so I start to download "tensorflow" library in command line , but it gives me errors
I use python 3.9 and i work on windows 10 what steps to let the code about machine learning execute? what libraries I need to run a classification image model in django ? I am so confused and do I need jupyter? and is django rest framework is necessary to run !! -
Is there a way to call form values into checkbox value
I want to get value of {{form.tag_af}} into the value of checkbox as show on image enter code here <div class="form-group row"> <label class="col-sm-2 col-form-label">tag_af:</label> <div class="selected col-sm-4"> {{ form.tag_af }} </div> <input type="checkbox" class="checkboxstyle" id="tagaf" value="id_tag_af" />Include in ItemName<br> What I need is the value of {{form.tag_af}} to be given to checkbox value As I want to call this checkbox value to append to a final item list In current situation instead of the value of {{form.tag_af}} id_tag_af is printed as it is -
multi-filter search in django not working
There are 3 filters namely description, categories and locations. For description, I want to search a job by a company name, job title or job description. Even if the user inputs, "company name and job title", i should retrieve a correct match not exactly but somewhat close. How do I get this? models.py class Internship(models.Model): recruiter = models.ForeignKey(Recruiter, on_delete=models.SET_NULL, null=True) internship_title = models.CharField(max_length=100) internship_mode = models.CharField(max_length=20, choices=MODE_CHOICES) industry_type = models.CharField(max_length=200) internship_desc = RichTextField() class Recruiter(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) company_name = models.CharField(max_length=100) views.py def user_search_internship(request): if request.method == "POST": internship_desc = request.POST['internship_desc'] //can be title, desc, company or a combo internship_ind = request.POST['internship_industry'] internship_loc = request.POST['internship_location'] internships = Internship.objects.all() if internship_desc != "" and internship_desc is not None: internships = internships.filter(internship_title__icontains=internship_desc) context = { } return render(request, '', context) -
"Mpesa.Paid_user" must be a "User" instance. - Repost
I would like to save to the database the currently logged-in user but I keep getting the same error AnonymousUser although the user is logged in, I am using the custom user model and I cannot find a solution anywhere, I would be grateful for any assistance. below are some snippets. views.py our_model = Mpesa.objects.create( Paid_user = request.user, MpesaReceiptNumber = mpesa_receipt_number, PhoneNumber = phone_number, Amount = amount, TransactionDate = aware_transaction_datetime, ) our_model.save() models.py class Mpesa(models.Model): Paid_user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE) MpesaReceiptNumber = models.CharField(max_length=15, blank=True, null=True) PhoneNumber = models.CharField(max_length=13, blank=True, null=True) Amount = models.IntegerField(blank=True, null=True) TransactionDate = models.DateTimeField(blank=True, null=True) Completed = models.BooleanField(default=False) -
"unresolved library" warning in pyChram working with User Filters in Django
I've made a simple user filter to add class styles to form fields. The code works well, but pyCharm shows a warning: Fliter code is: from django import template register = template.Library() @register.filter def addclass(field, css): return field.as_widget(attrs={"class": css}) Template code is: {% extends "base.html" %} {% block title %}Зарегистрироваться{% endblock %} {% block content %} {% load user_filters %} ... <div class="col-md-6"> {{ field|addclass:"form-control" }} ... And the warnings are: {% load user_filters %} and {{ field|addclass:"form-control" }} -
How to make my ManytoMany field not automatically populate
Hi so i am working on commerce from cs50 web development. I currently have a problem where when i create a new listing, my auction.watchlist (which is a manytomany field) automatically populates itself with all the users when i want it to be blank.) This is my models.py class User(AbstractUser): pass class Auction(models.Model): title = models.CharField(max_length=64) description = models.TextField() starting_bid = models.DecimalField(max_digits=10, decimal_places=2,null=True) highest_bid = models.DecimalField(max_digits=10, decimal_places=2, null=True) creator = models.ForeignKey(User, on_delete=models.PROTECT, related_name="my_listings", null=True ) created_date = models.DateTimeField(auto_now_add=True) current_winner = models.ForeignKey(User, on_delete=models.PROTECT, related_name="my_winnings", null=True) image = models.URLField() category = models.CharField(max_length=64, null=True) watchlist = models.ManyToManyField(User, related_name="my_watchlist", blank=True) This is my views.py def create_listing(request): if request.method == "POST": title = request.POST["title"] description = request.POST["description"] bid = request.POST["bid"] image = request.POST["image"] category = request.POST["category"] creator = User.objects.get(id = request.user.id) try: listing = Auction.objects.create(title = title, description = description, starting_bid = bid, highest_bid = bid, image=image, category=category, creator = creator) except IntegrityError: return render(request, "auctions/create_listing.html", { "message": "Title already taken" }) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/create_listing.html") And this is my html file create_listing.html {% extends "auctions/layout.html" %} {% block body %} <h2>Create Listing</h2> {% if message %} <div>{{ message }}</div> {% endif %} <form action="{% url 'create_listing' %}" method="post"> {% csrf_token %} <div … -
How to get the list of durations of any two elements with common field value
data = [ { "id": '24', "deleted": 'null', "date_created": "2021-06-05T10:27:19.092895Z", "action_type": "changed", "model_target": "Profile", "object_id": '1', "field_target": "is_seen", "field_value": "false", "by": 'null', "related_to": 'null', "seen_by": '[]' }, { "id": '25', "deleted": 'null', "date_created": "2021-06-05T11:27:19.092895Z", "action_type": "changed", "model_target": "Profile", "object_id": '1', "field_target": "is_seen", "field_value": "true", "by": 'null', "related_to": 'null', "seen_by": '[]' }, { "id": '26', "deleted": 'null', "date_created": "2021-06-05T12:27:19.092895Z", "action_type": "changed", "model_target": "Profile", "object_id": '2', "field_target": "is_seen", "field_value": "false", "by": 'null', "related_to": 'null', "seen_by": '[]' }, { "id": '27', "deleted": 'null', "date_created": "2021-06-05T13:27:19.092895Z", "action_type": "changed", "model_target": "Profile", "object_id": '2', "field_target": "is_seen", "field_value": "true", "by": 'null', "related_to": 'null', "seen_by": '[]' }, ] df = pd.DataFrame(data) df['date_created'] = pd.to_datetime(df['date_created']) # pivot df = df.reset_index().pivot('object_id','field_target','date_created') print(df) Error ---> 64 df = df.reset_index().pivot('object_id','field_target','date_created') ValueError: Index contains duplicate entries, cannot reshape goal summary I need to konw the duration it take to field_value to change from false to true detail I need to get the list of durations of any two elements with common (have the same) object_id between changing the field_value from false to true df['durations'] = df['true'].sub(df['false']).dt.days print(df) You don't need this explanation but just because StackOverflow requires that I need the get the date_created time difference for every two elements that have the … -
can't create API endpoint djnago
I recently started learning python then moved to django and drf and came across a question (the title of this post) in which I had to create an POST endpoint which accept address in request body and returns longitude and latitude using geocoding api by google. I tried to do it with Django rest framework but in DRR have to create a model which is serialised to give us json output but here we already have an api(geocoding) . I wanted to ask how can we create a POST endpoint when we already have an existing api that we want to use to return a response I hope this question makes sense -
The 'header_image' attribute has no file associated with it
When I create a new post with a picture, everything is ok, but if I edit it, want to, for example, change the picture or delete, then this error appears here is models.py ` from django.db import models from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='#') #new def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)])` here is views.py ` from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Post class BlogListView(ListView): model = Post template_name = 'home.html' class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' class BlogCreateView(CreateView): model = Post template_name = 'post_new.html' fields = ['title', 'author', 'body', 'header_image'] class BlogUpdateView(UpdateView): model = Post template_name = 'post_edit.html' fields = ['title', 'body', 'header_image'] class BlogDeleteView(DeleteView): model = Post template_name = 'post_delete.html' success_url = reverse_lazy('home') @property def image_url(self): """ Return self.photo.url if self.photo is not None, 'url' exist and has a value, else, return None. """ if self.image: return getattr(self.photo, 'url', None) return None` post_base.html `{% load static %} <html> <head> <title>Django blog</title> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400" rel="stylesheet"> <link href="{% static 'css/base.css' %}" rel="stylesheet"> …