Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Class missing "Meta.model" attribute but it's there?
Currently following this tutorial on youtube. and I am getting this error from the serializers.py file with the code he has finished writing at 32:24 This is the code I have written class ArticleSerializer(serializers.ModelSerializer): class Meta: model: Article fields: ['id', 'title', 'author'] If I change it to use serializers.Serializer then it works class ArticleSerializer(serializers.Serializer): title = serializers.CharField(max_length=100) author = serializers.CharField(max_length=100) email = serializers.EmailField(max_length=100) date = serializers.DateField() def create(self, validated_data): return Article.objects.create(validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.author = validated_data.get('author', instance.author) instance.email = validated_data.get('email', instance.email) instance.date = validated_data.get('date', instance.date) instance.save() return instance -
Difference between Django's ManyToManyField and ManyToManyRel
I'm new to Django and in my first project I'm working with models that are related to each other. While typing the autocomplete function of PyCharm suggested me ManyToManyField and ManyToManyRel. However, I couldn't find an answer that describes the exact differences between those classes and when to use which one. Thanks for your help. -
Migrate Issue on Heroku
I have hosted the django application in Heroku environmnet. Whenever I try to initiate migrate command its shows error " Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them." .I also checked with new database on same application eventhough same issue. Finally I have tried makemigrations its done well, but after makemigrations also having same issue. The same I have tried with another application in same heroku makemigrations and migrate working well. Please suggest why I can't migrate on previous application in heroku. -
403 forbidden when using OpenGraph Django
When I try to use opengraph to fetch the data from this website: website giving me error, it returns the following error: 403 Forbidden. You don't have permission to access this resource. Does anyone know why this happens? Thanks! My function: @receiver(pre_save, sender=Post) def url_processor(sender, instance, *args, **kwargs): if instance.url_web: title, description, image = web_preview(instance.url_web) print(title, description, image, sep="\n") instance.title = title instance.content = description path = 'blog/' + uuid.uuid4().hex + '.png' instance.image = path img_data = requests.get(image).content with open('media/' + path, 'wb') as handler: handler.write(img_data) My models.py: class Post(models.Model): title = models.CharField(max_length=200, verbose_name="Título", null=True, blank=True) content = RichTextField(verbose_name="Contenido", null=True, blank=True) published = models.DateTimeField(verbose_name="Fecha de publicación", default=now, null=True, blank=True) image = models.ImageField(verbose_name="Imagen", upload_to="blog", null=True, blank=True) author = models.ForeignKey(UserManegement, verbose_name="Autor", on_delete=models.CASCADE) categories = models.ManyToManyField(Category, verbose_name="Categorias", related_name="get_posts") url_web = models.URLField(verbose_name="URL", null=True, blank=True) created = models.DateTimeField(auto_now_add=True, verbose_name='Fecha de creacion') updated = models.DateTimeField(auto_now=True, verbose_name='Fecha de ediccion') class Meta: verbose_name = "entrada" verbose_name_plural = "entradas" ordering = ['-created'] def __str__(self): return self.title -
How to add images in a django website(bootstrap carousel)?
So I need to make a bootstrap carousel for my django based website and I can't add image the normal html way not this way. Can't figure out whats wrong with this. Thankyou. -
Django data quality monitoring: best approach to 'construct' queries based on a settings file?
I want to develop an app for automatic data quality monitoring (DQM) based on different queries: missing data outliers inconsitent data in the same models incosistent data between models missing form User should be able to 'customize' its own queries in a structured settings files (in a excel file loaded in a Django model or directly in a Django model with UI interface). DQM app should read this setting file and run queries with results stored in a model. User can edit list of query result and make correction in database in order to resolve and improve data quality. I look for Django package that could already do that but could not find any. So I would appreciate some help in conception. I have designed the settings files as below : I've read about data quality with Pandas bt nothing that cover all data quality queries mentionned above. Nevertheless, Pandas could be used to read excel settings file using dataframe. Then, I need to 'construct' query based on the setting file. I thought about 2 options: use raw: concatenate SQL orders with data read from dataframe and passed SQL order in raw() use Django queryset with unpack dictionnary to provide … -
how to pass the int of view.py to the {for loop of the django template}?
here is the code of the template I want to pass here in the slice <div class="swiper-container swiper-container2"> <div class="swiper-wrapper"> {% for category in smartphone_banners %} {% for product in category.product_detail_set.reverse|slice:"1:3:-1" %} <div class="swiper-slide py-2"> <a href="product/{{product.name}}/{{product.id}}" style="text-decoration: none;"> <img src="{{product.imageURL}}" alt="" style="width: 80%; margin: 0 auto;"> <h6 class="mt-1">{{product.name}}</h6> <p>₹{{product.price}}</p> </a> </div> {% endfor %} {% endfor %} slice:"1:3:-1" %} like this slice:"1:totalnu:-1" %} slice:"1:{{totalnu}}:-1" %} but both ways are not working here how can I pass it from the views.py for i in smartphone_banners: for pr in i.product_detail_set.reverse()[1:3:-1]: print(pr) print(totalnu) totalnu = totalnu + 1 print(totalnu) lists = [] for ifn in smartphone_banners: for prf in ifn.product_detail_set.reverse()[(totalnu - 2):totalnu:-1]: print( 'this is the fonal.', prf) value I want pass is the totalnu -
Using annotate and distinct on query set
I need following code to work together. queryset = PunchRawData.objects.filter(punch_type=IN, actual_clock_datetime__date=actual_clock_datetime).distinct('employee') trade_based = queryset.values('employee__position').annotate(emp_count=Count('employee__position')) But I get this error: NotImplementedError: annotate() + distinct(fields) is not implemented. How to resolve this? -
Is there a Django package to write ebook an show it tu user
I'm looking for an ebook package with Django (admin to write the Book + reader to show the Book, with some security like Amazon kindle to prevent easy copy). Thanks a lot if you have an idea. Gonzague -
Implementing notifications with Django Restframework
I have developed an api for mobile app which uses Django rest framework as backend. Now I want to create notification to user. Whenever new lesson is added by admin, logged in user will have a notification. Here is a lesson model class Lesson(models.Model): course = models.ForeignKey(Course, related_name='lcourse', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) image = models.ImageField(upload_to='lesson/', null=True, blank=True) def __str__(self): return self.name -
how to get 'id' from django ListView get_context_data
I would like to print out the entire list of models using Listview and display the id corresponding to each name next to it. The template doesn't require teacher.id, it needs an id for each teacher that returns to the for statement in views.py. class TeacherListView(ListView): model = Teacher context_object_name = 'teachers' template_name = 'teacher_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) for teacher in context['teachers']: context['teacher_id'] = teacher.id ---> Only the same value is output continuously in the template return context -
How to create write and read replicas,for a Django app using PostgreSQL, using automatic database routing
In order to increase the concurrency of my Django app, I would like to create read replicas of my master database. I would like to know what is the best way of implementing this. It would be great if this can be implemented using Automatic database routing in Django. -
Django: Dynamic jquery form not working when {% csrf_token %} is added
I am using a dynamic form in my django template using jquery but when I add submit button or csrf token to the form the dynamic form stops working and I can not add new fields anymore. Here is my html file <body> <form method="post"> <p> <label>Name:</label> <input type="text"> <label>Number:</label> <input type="number"> <span class="remove">Remove</span> </p> <p> <span class="add">Add fields</span> </p> </form> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> $(".add").click(function() { $("form > p:first-child").clone(true).insertBefore("form > p:last-child"); return false; }); $(".remove").click(function() { $(this).parent().remove(); }); </body> but when I insert {% csrf_token %} or the dynamic form is not working <form method="post"> {% csrf_token %} <p> <label>Name:</label> <input type="text"> <label>Number:</label> <input type="number"> <span class="remove">Remove</span> </p> <p> <span class="add">Add fields</span> </p> </form> , <form method="post"> <p> <label>Name:</label> <input type="text"> <label>Number:</label> <input type="number"> <span class="remove">Remove</span> </p> <p> <span class="add">Add fields</span> </p> <input type="submit" value="Submit"> </form> The form can no more insert/add new fields after this addition. Need help. -
What is the difference between validated_data.get() and validated_data.pop() in django rest framework?
I was writing code for updating certain fields (update API) inside the serializer class. For that, I have to get the dictionary of that object and assigned it to an object. I tried with both pop and get and when I print the results I get the same Orderdict. There is no error, but I just want to know the difference between them. My code is here. class ProductUpdateSerializer(serializers.ModelSerializer): variants = VariantSerializer(many=True) class Meta: model = Product fields = ['id','category','featured', 'top_rated','brand','collection', 'name','description', 'main_product_image','best_seller','picture', 'rating','availability','warranty','services','variants'] def update(self, instance, validated_data): #instance = super(ProductUpdateSerializer, self).update(instance,validated_data) print(instance) instance.warranty = validated_data.get('warranty', instance.warranty) instance.services = validated_data.get('services', instance.services) instance.save() # #category_logic category_data = validated_data.pop('category') print(category_data) instance.category.set(category_data) instance.save() #variants_logic variants_data = validated_data.get('variants') **# I am confused on this line.** print(variants_data) #instance.variants.set(variants_data) #variants_logic_trial for variants_data in variants_data: Variants.objects.update_or_create( id = variants_data['id'], defaults={ 'price': variants_data['price'], 'size': variants_data['size'], 'color': variants_data['color'], 'quantity': variants_data['quantity'], 'variant_availability': variants_data['variant_availability'], } ) instance.save() return instance The result I get is this after printing the variants_data. [OrderedDict([('id', 96), ('product_id', 'ABCTest'), ('price', Decimal('500.00')), ('size', 'not applicable'), ('color', 'not applicable'), ('quantity', 11088), ('variant_availability', 'av ailable')]), OrderedDict([('id', 97), ('product_id', 'ABCdsfgsdkjgTest'), ('price', Decimal('5800.00')), ('size', 'not applicable'), ('color', 'not applicable'), ('quantity', 222), ('varian t_availability', 'available')])] I get the same data when I used … -
How to solve below task?
Technical Assessment: Django app hosted on Netlify/HerokuFrontend: View 1 / page 1 :Basic bootstrap design with a form of following details: name URLPhone numberView 2:Search field which takes input for name and returns information from db if name already presentView 3:Take input of behance link like(https://www.behance.net/harisnazar04f8 this view has a button called " Get images' Once it's click , the images are displayed dynamically in this page. Backend : all submitted data needs to be stored in mysql or any db - and perform view 2 search functions -
How to add new question to chatbot using Django and chatterbot from front end?
A final year B.E project, chatbot for farmer. We have used chatterbot and Django for our project. Have admin and farmer modules. Now admin has permission to add new question. How to add the new question to the chatbot using a Django form from front-end? -
How to use redis database with django?
I am planning to store all my user activity logs( like user logged in, password changed etc)in a redis database instead of the main database used in the project. For example: class MyLogModel(models.Model): log_msg = models.CharField(..) Then I usually create the table like this MyLogModel.objects.create(log_msg='msg') My question is can I do the same with Redis? If not redis how can I optimize my database with django since over the time it will have so many data which might make the database slower. OR another option deleting the activity logs older than 1 month something like this would be better ? OR Is there any better approach for this scenario ? -
How to set the SameSite attribute of set-cookie in django version 2.0.13?
I installed yangsuite[core], deployed it and called it with an iframe <iframe width="700" height="800" src="https://10.225.61.70:7143/netconf/getyang/hangxin+travelsky-set/ietf-interfaces"> </iframe> Here is the view function code (under the directory lib/python3.8/site-packages/ysnetconf/views/rpc.py): @login_required def get_yang(request, yangset=None, modulenames=None): devices = YSDeviceProfile.list(require_feature="netconf") replay_dir = get_path('tasks_dir', user=request.user.username) return render(request, 'ysnetconf/netconf.html', { 'devices': devices, 'yangset': yangset or '', 'modulenames': modulenames or '', 'replay_dir': replay_dir }) It requires a login, I changed the code to bypass the login(There is some code logic need to access the request.user) # @login_required def get_yang(request, yangset=None, modulenames=None): devices = YSDeviceProfile.list(require_feature="netconf") from django.contrib.auth.models import User from django.contrib.auth import authenticate, login user = authenticate(username='admin', password='password') login(request, user) replay_dir = get_path('tasks_dir', user=request.user.username) return render(request, 'ysnetconf/netconf.html', { 'devices': devices, 'yangset': yangset or '', 'modulenames': modulenames or '', 'replay_dir': replay_dir }) But when I open the ifram page, a warning suggests I should specify SameSite. I found a solution, but only in django 2.2.x. Here is the mentioned solution: https://stackoverflow.com/a/64338648/7004884 I tried to use django-cookies-samesite in 2.0.13, but it didn't work. In this document (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#) None), it mentions the need to set the secure attribute, which I have done. The cookie I get looks like this Set-Cookie: sessionid=2hm53373qoou4kectdy8lv2z4aqp25y8; expires=Mon, 03-May-2021 05:57:13 GMT; HttpOnly; Max-Age=1209600; Path=/; Secure I think the reason … -
How to configure dynamic URL in Django?
I am configuring a dynamic url in my django project. I have followed the instructions provided on the net but it is not working. urls.py in app urlpatterns = [ url(r'^seci/<int:secn>', views.sect, name = 'sect'), url('sections/<str:secn>/', views.sections, name = 'sections'), ] views.py in app def sect(request,secn): print("secn:", secn) return HttpResponse("testing") def sections(request, secn): print("secn:", secn) return HttpResponse(secn) Django says, url not found. I don’t know what else to do. -
Share product from flutter apl with django api
A have a website built with python/django, and i made rest api for this project. Also i made a flutter app that uses this api. My problem is : i need a button inside a flutter app that share a link of a product, and when someone press it(the link) , it will redirect it to open the product inside the app (not webview). I will be so grateful to you guys. -
How to return custom response in django rest?
I want to know how can we return error/success custom response in Django rest instead of serializer response. For example I want to return the response in the following format { 'status':'Error', 'reson':'Reason' } whereas serializer return errors as in the following format {'username': ['This field is required.'], 'password': ['This field must be at least 8 chars'], 'email': ['This field cannot be blank'] } How to customize this error response? Please help. Thanks in advance. -
How to pass a pandas DataFrame into the context of a Django View as a CSV file?
I have a view in Django views.py to fetch the columns from the database and create a pandas dataframe which inturn gets converted as a CSV file with those columns as show below def import_data(request): if request.method == 'GET': try: from io import BytesIO as IO # for modern python except ImportError: from io import StringIO as IO # for legacy python column_names = network_asset._meta.fields column_names = [x.name for x in column_names] print(column_names) df = pd.DataFrame(columns=column_names) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=export.csv' df.to_csv(path_or_buf=response) # with other applicable parameters return response Now the problem with this is - The csv file gets downloaded as soon as the page loads. I want to pass it in as context or some such so that I will have a "download the template here" link on the web page. The user should be able to download by clicking on that. Note: I do not want to save the template as xlsx/csv in the MEDIA_ROOT and download it as the columns in the DB might change often. The sample front end page looks like this - enter image description here -
Django ModelViewSet method not allowed 405 41
class Feedback_View(viewsets.ModelViewSet): serializer_class = Feedback_Serializer parser_class = (FileUploadParser,) filter_backends = [DjangoFilterBackend , SearchFilter , OrderingFilter] def get_queryset(self): query = feedbackModel.objects.all() return query class Feedback_Serializer(serializers.ModelSerializer): class Meta: model = feedbackModel fields = "__all__" router = DefaultRouter() router.register('orggetdetails', views.org_detail_view_set, basename='orggetdetails') router.register('saveSearch', views.saved_search_view_set, basename='savedSearch') router.register('Allanguages' , views.all_language_ViewSet , basename='Alllanguages') router.register('feedback' , views.Feedback_View, basename='feedback') #urlpatterns =router.urls urlpatterns = [ path('', include(router.urls)) ] I get Error as : Method Not Allowed: /op-api/op/feedback/ [19/Apr/2021 10:38:00] "POST /op-api/op/feedback/ HTTP/1.1" 405 41 I am trying to post to http://127.0.0.1:8000/op-api/op/feedback/ with some data. It was working fine yesterday, I don't know why suddenly it starts generating an error. how Can I solve it and what could be the issue. -
I'm facing problem in Django form validation?
I'm new to Django and instead of using Django forms ,I'm using bootrap forms with user model that I have created I have to check the login details before giving access to the user dashboard . Here's the code: def login(request): if request.method=="POST": email=request.POST.get('email') password=request.POST.get('password') if email=="cool@c.com" and password=="567": return redirect('dashboard') else: context="Provide Valid Credentials" return render(request."login.html",context) It's not redirecting me to the dashboard . And also how to set cookies , sessions but I'm not using the default admin or user model for anything . I'm a website for a client plz give me suggestions based on this not as a project . -
i have a search function which render another page with search results and i have implemented pagination within this function but it shows me an error
I have a view function named named search_user and when i type something to search it shows me the results but when ever i click the next page after searching it shows me valueerror(e.g. return none instead) views.py def search_user(request): query = request.GET.get("q") context ={} if query: users = User.objects.filter(Q(username__icontains=query)) if users: page = request.GET.get('page', 1) paginator = Paginator(users, 1) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) context={'users': users} return render(request,'user/search.html',context) else: messages.warning(request,'User matching query does not exist.') return redirect('acc_req_list') template {% if users.has_other_pages %} <ul class="pagination"> {% if users.has_previous %} <li class="page-item active"> <a class="page-link" href="?page={{ users.previous_page_number }}">pre</a> </li> {% else %} <li class="page-item disabled"><span></span></li> {% endif %} {% for i in users.paginator.page_range %} {% if users.number == i %} <li class="page-item"><span style="z-index: 1; position: relative; display: block;padding: 0.5rem 0.75rem; margin-left: -1px; line-height: 1.25; color: #f7efef; background-color: #F64E60; border: 1px solid #E4E6EF;">{{ i }} <span class="sr-only" >(current)</span></span></li> {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if users.has_next %} <li class="page-item active"> <a class="page-link" href="?page={{ users.next_page_number }}">Next</a> </li> {% else %} <li class="page-item disabled"><span></span></li> {% endif %} </ul> {% endif %}