Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update a Model in Django right before the backend select
Before my Model in Django gets hydrated and filled with data, I want to update (alter) my model, save it back to the database and then go on the normal way. My approach (not working) as now is this: from django.db import models from MyApp import models as m class CustomManager(models.Manager): def get_queryset(self): # This is not evaluated to true although it should from my assumption: if (isinstance(self.model, m.MyObject)): # Here I want to take the internal key of # MyObject (maybe from the URL?), # Simply accessing self.model.internal_key does not work. # Then make an API call to an external server, # update my local object, save it back to db and proceed print(self.model) # Prints <class 'MyApp.models.MyObject'> Can someone point me to the right direction if this is the correct approach and how I go on? -
Why the form is invalid at FormView?
All fields are filled. But for some reason does not go into the form_valid method, but it goes into form_invalid. Why form is invalid? forms.py class CreditFilterForm(forms.Form): CURRENCY_CHOICES = ( ('KZT', _('KZT')), ('USD', _('USD')), ) PERIOD_CHOICES = ( ('1', _('One year')), ('2', _('Two')), ('3', _('Three')) ) sum = forms.CharField(widget=forms.NumberInput(attrs={'id': "sum", 'class':"forminput-text"})) currency = forms.ChoiceField(choices = CURRENCY_CHOICES, widget=forms.Select(attrs={'name': "minbeds", 'id':"currency"})) term = forms.ChoiceField(choices = PERIOD_CHOICES, widget=forms.Select(attrs={'id':"term", 'name': "minbeds"})) views.py class CreditsList(ListView): model = Credit template_name = 'credits/credit_listing.html' def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() little_form = CreditFilterForm(self.request.GET or None, prefix="little") ... class LittleForm(FormView): form_class = CreditFilterForm template <form action="{% url 'little_form' %}" method="post"> {% csrf_token %} {{ little_form.as_p }} <input type="submit" name="{{ little_form.prefix }}" value="Submit"> </form> -
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'project.routing'
i have installed django channels i have added routing.py in project root folder and added the line ASGI_APPLICATION = 'project.routing.application' but whenever i tried to run the server i get raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'scrapshut.routing' downgrading channels version to 1.5 works but i want to figure out whats the issue with channels 2 async-timeout==3.0.1 attrs==19.1.0 autobahn==19.6.2 Automat==0.7.0 certifi==2019.6.16 cffi==1.12.3 channels==2.2.0 channels-redis==2.3.3 chardet==3.0.4 constantly==15.1.0 cryptography==2.7 daphne==2.3.0 defusedxml==0.6.0 dj-database-url==0.5.0 Django==2.2.2 django-heroku==0.3.1 django-widget-tweaks==1.4.5 gunicorn==19.9.0 hiredis==1.0.0 hyperlink==19.0.0 idna==2.8 incremental==17.5.0 msgpack==0.6.1 msgpack-python==0.5.6 oauthlib==3.0.1 Pillow==6.0.0 psycopg2==2.8.3 pycparser==2.19 PyHamcrest==1.9.0 PyJWT==1.7.1 pypiwin32==223 python-decouple==3.1 python-social-auth==0.2.1 python3-openid==3.1.0 pytz==2019.1 pywin32==224 redis==2.10.6 requests==2.22.0 requests-oauthlib==1.2.0 six==1.12.0 social-auth-app-django==3.1.0 social-auth-core==3.2.0 sqlparse==0.3.0 Twisted==19.2.1 txaio==18.8.1 urllib3==1.25.3 i just want the server to recognize the routing application and start working -
how to call function django views.py without refresh page?
I write a model that user can follow/unfollow each other, but when the user tap on the button to follow or unfollow after the process, the page will be refreshed. I need a way to handle that action without refreshing page and change the text in this page. my model : class Follower(models.Model): follower = models.ForeignKey(User, related_name='followings', on_delete=models.CASCADE) following = models.ForeignKey(User, related_name='followers', on_delete=models.CASCADE) class Meta: unique_together = ('follower', 'following') def __str__(self): return u'%s follows %s' % (self.follower, self.following) my view : def follow(request, own_user_id , follow_state): """ follow function that add user who follow other user own : user that have channel page """ own = CustomUser.objects.get(pk=own_user_id) if follow_state == "followed": action = request.user.followings.get(following=own) action.delete() return redirect(f'http://127.0.0.1:8000/{own.channel_name}') else: action = Follower.objects.create(follower=request.user, following=own) action.save() return redirect(f'http://127.0.0.1:8000/{own.channel_name}') my template : {% if request.user == user_own %} <a href="{% url 'update-page' user.channel_name %}"> <button class="btn btn-light btn-flw">profile setting </button></a> {% else %} <a href="{% url 'follow-unfollow' user_own.id follow_state%}"> <button class="btn btn-light btn-flw">{{follow_state}}</button> </a> {% endif %} -
how to write query on ArrayModelField?
i am trying to query the array model field but unable to do it in my web page project_name,project_supervisor and all fields except Students which is array model fields are showing but data from array model is not showing.i want that if i want to access data from data using query year_data = students.objects.filter(batch_year__startswith='2012') then it will show all data on web page including Roll_No and Student_Name. models.py class Students(models.Model): Roll_No=models.CharField(db_column='Roll No',max_length=250) Student_Name = models.CharField(db_column='Student Name',max_length=250) class Meta: abstract = True class students(models.Model): _id = models.ObjectIdField() batch_year = models.CharField(db_column='Batch Year',max_length=250,default=True) # Field name made lowercase. Students = models.ArrayModelField(model_container=Students, ) project_name = models.CharField(max_length=250, db_column='Project Name',default=True) # Field name made lowercase. project_supervisor = models.CharField(max_length=250, db_column='Project Supervisor',default=True) # Field name made lowercase. external_supervisor = models.CharField(max_length=250,db_column='External Supervisor',default=True) # Field name made lowercase. co_supervisor = models.CharField(max_length=250,db_column='Co-Supervisor',default=True) # Field name made lowercase. project_id = models.CharField(db_column='Project Id',max_length=250,default=True) # Field name made lowercase. def __str__(self): return self.batch_year + '---' +self.project_name views.py def search(request): years = request.GET.get('text', 'Default') print('years', years) year_data = students.objects.filter(batch_year__startswith=years) -
Getting currency selection of form
it's greate to be here :) i was hopeing that smb. Is maybe able to explain to me how i can process a selection (RadioButton selection) further in my views.py. Currently I'm processing this staticaly for btc (Bitcoin) but i have to get this working for ltc, xmr etc. as currency also. How can i get the user selection of this form or in other words the selected currency the user has chosen? views.py ... if request.method == "POST": form = CurrencyBuySelectForm(request.POST) currency = form['currency'].value() # check account balance if form.is_valid: if currency == 'btc': price = dollar_to_coin(post.price_usd, 'BTC') if request.user.acc_btc_balance < price: messages.error(request,'Not enough balance to buy this message') return redirect('post', pk=post.pk) else: # generate transaction ... forms.py: WALLET_CHOICE = [ ('btc', 'BTC'), ('xmr', 'XMR'), ('ltc', 'LTC'), ... etc ] class CurrencyBuySelectForm(forms.Form): currency = forms.ChoiceField(choices=WALLET_CHOICE, widget=forms.RadioSelect()) captcha = CaptchaField() def __init__(self, *args, **kwargs): super(CurrencyBuySelectForm, self).__init__(*args, **kwargs) self.fields['currency'].label = mark_safe('') def clean(self): cleaned_data = super(CurrencyBuySelectForm, self).clean() currency = cleaned_data.get(choices=WALLET_CHOICE, widget=forms.RadioSelect()) if not currency: raise forms.ValidationError('Something went wrong') Thanks in advance -
django app structure for making a modular application
i am new to django and i wanna know if i would have 2 classes like home and booking for a booking reservation system should i make 2 apps like below : python manage.py startapp booking python manage.py startapp home or i should make an app named home for example and make a booking class inside that app ?? i want to know the standard way to do this in django because i could not find the way in documentation here is the way i do it : -
Django's get_initial() method not working as desired
I am using django's generic CreateView to build a comment system for my site. A user is allowed to do comment for a movie. Here is my Comment model- class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE) body = models.TextField() movie = models.ForeignKey(Movie, related_name="comments", on_delete=models.CASCADE) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) class Meta: ordering = ('created',) def __str__(self): return "comment by {} on {}".format(self.user.first_name, self.movie) Here is the CreateView i am using- class AddComment(LoginRequiredMixin, CreateView): form_class = CommentForm def get_initial(self): initial = super().get_initial() #for providing initial values to the form initial['user'] = self.request.user.id initial['movie'] = self.kwargs['movie_id'] return initial def get_success_url(self): movie_id = self.kwargs['movie_id'] return reverse('detail', kwargs={'pk':movie_id}) def render_to_response(self, context=None, **response_kwargs): movie_id = self.kwargs['movie_id'] return redirect(to = reverse('detail', kwargs={'pk':movie_id})) Here is the commentform - class CommentForm(forms.ModelForm): user = forms.ModelChoiceField(widget=forms.HiddenInput, queryset=get_user_model().objects.all()) movie = forms.ModelChoiceField(widget=forms.HiddenInput, queryset=Movie.objects.all()) class Meta: model = Comment fields = ('user','movie', 'body') I am trying to associate a comment to a user and a movie. I thus used get_initial() method to fill the form with initial data because user and movie were not present in the posted data. But somehow always form.is_valid() turns out to be false. I don't know where i went wrong. Please Help. -
Django REST throwing [Errno 54] Connection reset by peer and Bad Request
I am using Django REST API for my server in combination with Djoser library for authentication. The client part is written with Vue.js, and I use Axios for API requests. Now I am trying to make the server and client parts interact. I have started with authentication. My server is up on 127.0.0.1:8000. When I use Postman to request an authentication token based on username and password, I send a POST request and get a response: Then, I am trying to reproduce such a request using Vue and Axios. I have defined a component named Login and written the following there: <script> import axios from 'axios' export default { name: "Login", data() { return { login: '', password: '' } }, methods: { setLogin() { axios({ method: 'post', url: 'http://127.0.0.1:8000/auth/token/create/', body: {username: this.login, password: this.password} }) .then(function (response) { sessionStorage.setItem("auth_token", response.data.attributes.auth_token) }) .catch(function (error) { console.log(error); }); } } } And the template consists of just 2 inputs (for login and password) with v-model=login and v-model=password and a button with @click="setLogin". I have imported this component in App.js and display it here. Now when I am trying to authorize, I have several issues: 1) The page is reloaded so quickly … -
Access Consumer from View to push api-received data to User via WebSocket (Django-Channelsv2.2 & DRF)
I found myself struggling to find a way to push data to Consumer (Django Channels v.2.2) from View (APIView Django-rest-framework) or distributed task (Celery/RabbitMQ directly) I'd really appreciate any code sample that would allow me to access the consumer from View as the trigger itself is the input device, not web, so I can make API call from it, so I need the connector. Django Channels v.2.2, DjangoChannelsRestFramework, mostly all the cases described here: https://channels.readthedocs.io/en/latest/community.html as well as correlating questions @stackoverflow consumers.py class BasicConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) await self.send({ "type": "websocket.accept" }) # await self.send({ # "type": "websocket.send", # "text": "Hello world" # }) async def websocket_receive(self, event): print('receive', event) front_text = event.get('text', None) if front_text is not None: loaded_dict_data = json.loads(front_text) msg = loaded_dict_data.get('message') print(msg) user = self.scope['user'] if user.is_authenticated: username = user.username myResponse = { 'message': msg, 'username': username } await self.send({ "type": "websocket.send", "text": json.dumps(myResponse) }) async def websocket_disconnect(self, event): print('disconnect', event) @database_sync_to_async def get_thread(self, user, other_username): return Thread.objects.get_or_new(user, other_username)[0] views.py class BasicView(APIView): def post(self, request): serializer = BasicViewSerializer(data=request.data) if serializer.is_valid(): triggerConsumer(serializer.validated_data) -
How to integrate accountkit in a Python Django project?
I'm entirely new in Python or any kind of back-end development. I've created a simple project using Django & Django REST framework to feed data in a React Native application. I want to integrate Facebook Accountkit for passwordless login, didn't found any documentation or tutorial on how to do that on Django. Can anyone suggest me any example project or code snippet regarding this topic? -
Saving data form in django without editable property for admin-django
I want to save the data of a form that user submit. But I don't wanna the admin be able to edit those data at all. I tried the readonly_field stuffs, but that didn't work. my models.py: class User(models.Model): first_name = models.CharField(max_length=100) country = CountryField() my admin.py: from django.contrib import admin from .models import User admin.site.register(User) class MyAdmin(admin.ModelAdmin): readonly_fields=('first_name', 'country') -
Django Aggregation - Trying to return two values
I am trying to get the username and text of their most recent post using an aggregation function. I am trying the code below, but I don't get distinct values for the user name. conversations = Chat.objects.values('user__username','body').annotate(Max('dateofpost')) With the above it gives me all posts by that user, but what I am trying to get is the user name with the body text of the post that is the most recent one posted. Can anyone help? I have been reading online, but can't find an explanation of what to do in this situation. I can see posts on calling the aggregate / values method again, but can't get this to work. -
How change form_field name in django template?
I tried to get list of checkbox values from template. But I need to change name of form_field in loop like html-input I use forms.ModelForm -> forms.BooleanField(initial=False, required=False) forms.py is_used = forms.BooleanField(initial=False, required=False) template.html {% for object in objects %} {% bootstrap_label form.is_used %} // input type="checkbox" name="{{ object.id }} ##I need something like that {% endfor %} I haven't a list in a POST, I have only is_used=[0:on, 1:on] if i mark the first and the last too. -
how to perform django orm on Django Cassandra engine models
I have django cassandra engine and I create my model as it saied here: enter link description here here it explain I can use raw query inorder to work with my db:enter link description here does it means that I cannot use django orm (ex:model.objecs.all()) for this kinds of model? or there is some solution for it? -
I cannot add song to specific album using CreateView
I am following buckys django tutorial, he explained how to add albums but not song, i want to try adding songs to specific album but it is not working. I have added a SongCreate view to my views.py, i also created a song_form.html template for inputting song details.I have also tried the form_valid method, but it doesnt just work. My views.py class AlbumCreate(CreateView): model=Albums fields=['alb_title','alb_genre','alb_logo','alb_artist'] class SongCreate(CreateView): model = Song fields = ['song_title', 'song_format'] def form_valid(self, form): album = get_object_or_404(Albums, pk=self.kwargs['pk']) form.instance.album = album return super(SongCreate, self).form_valid(form) #My urls.py app_name ='music' urlpatterns = [ path('',views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('album/add/', views.AlbumCreate.as_view(), name='album-add'), path('album/<int:pk>/songadd/', views.SongCreate.as_view(), name='song-add'), path('album/<int:pk>/', views.AlbumUpdate.as_view(), name='album- update'), path('album/<int:pk>/delete/', views.AlbumDelete.as_view(), name='album-delete'), ] #My song_form.html template {% extends 'music/base.html' %} {% block title %}Add New Song{% endblock %} {% block body %} <div class="container-fluid"> <h4>Add the details of the Song in the given fields.</h4> <div class="row"> <div class="col-sm-12 col-md-7"> <div class="panel panel-default"> <div class="panel-body"> <form class='form-horizontal' action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'music/form-template.html' %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn- success">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> {% endblock %} When add song is clicked it directs me to a form to fill … -
add new attribut from other model to user model
i have structure model with id and name_structure and i want when i add user i affect them in one structure like username john password 1234 structure electric departement but i don't know how can i do this work in Django so please help me ? this models.py in immob appfrom django.db import models # Create your models here. class structure(models.Model): structure_code=models.CharField(max_length=1) structure_desig=models.CharField(max_length=350) class service(models.Model): structure_id=models.ForeignKey (structure,on_delete=models.CASCADE,default=0) service_desig=models.CharField(max_length=350) class immob(models.Model): immo_code=models.CharField(max_length=7) immo_desig=models.CharField(max_length=150) immo_qte=models.FloatField(default=1) immo_datemes=models.DateTimeField() immo_cptimmob=models.CharField(max_length=10) immo_dureevie=models.IntegerField(default=7) immo_numaut=models.CharField(max_length=4) immo_origine=models.CharField(max_length=1) immo_fournisseur=models.CharField(max_length=150) immo_nufact=models.CharField(max_length=20) immo_datefact=models.DateTimeField() immo_valht=models.DecimalField(max_digits=18,decimal_places=2) immo_monaie=models.CharField(max_length=3) immo_tauxcvt=models.DecimalField(max_digits=18,decimal_places=2) immo_tauxctrval=models.DecimalField (max_digits=18,decimal_places=2) immo_frais=models.DecimalField(max_digits=18,decimal_places=2) immo_coutacq=models.DecimalField(max_digits=18,decimal_places=2) immo_refcmde=models.CharField(max_length=35) immo_datecmde=models.DateField() immo_journee=models.CharField(max_length=10) immo_cptanal=models.CharField(max_length=9) immo_local=models.CharField(max_length=45) immo_mode_amort=models.CharField(max_length=1) immo_code_r=models.CharField(max_length=2) immo_val_amort=models.DecimalField (max_digits=18,decimal_places=2) immo_status=models.CharField(max_length=1) immo_code_bar=models.CharField(max_length=25) service_id=models.ForeignKey (service,on_delete=models.CASCADE,default=0) and this model of compte app (account) # Create your models here. from immob.models import structure from django.db import models from django.contrib.auth.models import User class utilisateur(models.Model): user=models.OneToOneField('auth.User', on_delete=models.CASCADE) structure=models.ForeignKey(structure,on_delete=models.CASCADE) -
How to sort Django QuerySet output by date?
I have data like this: <QuerySet [(datetime.datetime(2019, 6, 14, 20, 4, 58, 104805, tzinfo=<UTC>), UUID('b15be3c1-3f70-4ccb-af08-dba385f883a1')), (datetime.datetime(2019, 6, 12, 18, 42, 38, 675120, tzinfo=<UTC>), UUID('f2ea2ad0-f228-43d7-823a-c824a041feb2')), (datetime.datetime(2019, 6, 12, 17, 46, 38, 479890, tzinfo=<UTC>), UUID('16c66e9b-0cbf-4b6d-b848-78cf771f522c')), (datetime.datetime(2019, 6, 21, 20, 17, 15, 785171, tzinfo=<UTC>), UUID('a169afcf-267b-4212-97e5-6221595ab107')), (datetime.datetime(2019, 6, 15, 7, 33, 34, 136331, tzinfo=<UTC>), UUID('9aac6b06-6622-4587-9956-5b517aaa11e8')), (datetime.datetime(2019, 6, 18, 16, 11, 49, 134458, tzinfo=<UTC>), UUID('00271b56-9ff7-4f9d-b9c0-2592ca9436d2')), (datetime.datetime(2019, 6, 21, 21, 3, 53, 528261, tzinfo=<UTC>), UUID('df0d8905-5377-4b8d-99d9-eba644273eaa')), (datetime.datetime(2019, 6, 21, 21, 4, 6, 256957, tzinfo=<UTC>), UUID('c339d797-f37d-48ff-94a6-e6d1510e23cc')), (datetime.datetime(2019, 6, 18, 17, 10, 18, 388505, tzinfo=<UTC>), UUID('00271b56-9ff7-4f9d-b9c0-2592ca9436d2'))]> In the QuerySet i've multiple datetime instance with UUID, I created this data using 2 different model and both model have different datetime field name, so i think we can't use CHAIN. Here I want to sort according to datetime Many Thanks in advance -
breadcrumb_url - Reverse for '' not found. '' is not a valid view function or pattern name
I'm trying to do breadcrumbs by this example https://www.djangosnippets.org/snippets/1289/ but have error Reverse for '' not found. '' is not a valid view function or pattern name.I did everything just like in this example. But I'm doing something wrong. Error in this line {% breadcrumb_url 'Home' product_list %} urls.py app_name = 'shop' urlpatterns = [ url(r'^$', views.product_list, name='product_list'), url(r'^show/(?P<slug>[-\w]+)$', views.product_show, name='product_show'), url(r'^(?P<category>[-\w]+)$', views.product_list, name='lst_by_ctgry'), url(r'^(?P<category>[-\w]+)/(?P<subcategory>[-\w]+)$', views.product_list, name='lst_by_subctgry'), url(r'^(?P<category>[-\w]+)/(?P<subcategory>[-\w]+)/(?P<kind>[-\w]+)$', views.product_list, name='lst_by_knds'), ] base.html {% load breadcrumbs %} <!DOCTYPE html> <html> <head> <title>Shop</title> <meta charset="utf-8"> </head> <body> {% block breadcrumbs %} {% breadcrumb_url 'Home' product_list %} {% endblock %} <div class="container"> {% block content %} {% endblock %} </div> </body> </html> breadcrumbs.py from django import template from django.template import loader, Node, Variable from django.utils.encoding import smart_str, smart_text from django.template.defaulttags import url from django.template import VariableDoesNotExist register = template.Library() @register.tag def breadcrumb(parser, token): """ Renders the breadcrumb. Examples: {% breadcrumb "Title of breadcrumb" url_var %} {% breadcrumb context_var url_var %} {% breadcrumb "Just the title" %} {% breadcrumb just_context_var %} Parameters: -First parameter is the title of the crumb, -Second (optional) parameter is the url variable to link to, produced by url tag, i.e.: {% url person_detail object.id as person_url %} then: {% … -
Error 404 not found raises 500 when Debug set to False
I recently tried to implement a custom view for my 404 and 500 errors on my website. It works well when debug is set to True, i.e. both the custom views work well when called. But as soon as set my Debug to False only the error 500 will be raised I tried already to call them by creating a url, both of the handler404 and handler500 custom view works well. This is the view where it should raise an error 404 when badly called: def arret(request, id): view = 'search/arret.html' arret = get_object_or_404(Arret, id=id) Here you can find my 404 custom view: def arret(request, id): def handler404(request, template_name="colorlib-error-404-19/index.html"): response = render_to_response("colorlib-error-404-19/index.html") response.status_code = 404 return response it raises an error 500 when trying to find a non existing Arret. this is what is written in the terminal ``bash System check identified no issues (0 silenced). June 22, 2019 - 08:55:31 Django version 2.0, using settings 'nora.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [22/Jun/2019 08:55:32] "GET /arret/100/?q=loi HTTP/1.1" 500 1435 -
Python unsupported operand type(s) where everything is FloatField
one of my functions return the following error: unsupported operand type(s) for -: 'str' and 'float' this is the sippet im doing my math on: increased = decoded_balance["InGet"] - user.acc_cash_temp if decoded_balance["Unfulfilled"] == '0' and increased > 0: user.receiver.create(amount=increased, sender=system, type='usd') user.acc_cash_temp = decoded_balance["InGet"] user.acc_cash_balance += increased user.save() Where do i miss the field types? All mentioned fields like acc_cash_temp or acc_cash_balance are FloatField thanks and regards -
How to add label ID in Django Model Form
I am using Django modelform for label. However, I don't know how to add label ID and I find nothings on Internet. UserForm class UserForm(ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'email'] widgets = { 'first_name': forms.TextInput(attrs={'type': 'text', 'placeholder': 'First Name', 'class': 'form-control input-md'}), 'last_name': forms.TextInput(attrs={'type': 'text', 'placeholder': 'Last Name', 'class': 'form-control input-md'}), 'email': forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control input-md'}), } labels = { 'first_name': "Họ", 'last_name': "Tên", 'email': "Email", } First name label label style="margin-left: -48px; margin-right: 48px;" class="col-md-4 control-label" for="">First Name -
How to get dictionary items through javascript
I need to alert the dictionary items on page load.But so far no alert is getting displayed.Please help. data2 = {"iname": "name", "imodel": "dtls2"} return render(request, "home.html", data2) // inside home.html <script> for (var key in data2) { alert(data[key]); } </script> -
How to add custom HTML elements and images to a blog in Django?
I am trying to create a blog in Django. Most of the tutorials and examples available shows just retrieving some content from the database and displaying it dynamically on the predefined HTML structure. After looking at some solution I found something called flatpages in Django which provide the facility to write HTML. But its recommended to use it for About Us and Contact Us kind of pages. Should I use this? I want to do it as I can write my own HTML data for each blog and add some images so that the structure of HTML should not be similar in each blog. For example, In the case of WordPress, it allows the user to completely write each part of the blog except the heading part and the structure of HTML is not constant always. I want such functionality. Please help. -
Object not iterable in Django Rest API foreign key serializers
I am new in DRF! Trying to serialize my models even with foreign key. I want to the end-point should display data in foreign key related data. but i got an error and that is TypeError: 'Author' object is not iterable These are my serializer classes from rest_framework import serializers from . models import Author, Article, Category class AuthorSerializers(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' class CategorySerializers(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class ArticleSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(many=True) category = serializers.StringRelatedField(many=True) class Meta: model = Article fields = '__all__' and these are my models from django.db import models from django.contrib.auth.models import User class Author(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) detail = models.TextField() def __str__(self): return self.name.username class Category(models.Model): name = models.CharField(max_length=100) class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') title = models.CharField(max_length=200) body = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) and these are my views: class ArticleListCreateGet(ListAPIView, CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer class ArticleSingle(RetrieveAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer lookup_field = 'pk' # This is delete/update method class ArticleDeleteUpdate(DestroyAPIView, UpdateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer lookup_field = 'pk' and these are my url path('api/v1/article', views.ArticleListCreateGet.as_view(), name='article'), path('api/v1/article/<int:pk>/detail', views.ArticleSingle.as_view(), name='article-single'), path('api/v1/article/<int:pk>', views.ArticleDeleteUpdate.as_view(), name='article-delete-update'),