Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'
I am using DRF for django post method,i want to be able to refer images as a manytomanyfield but i am getting an error.Here is the code: class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') images = models.ManyToManyField('Article',symmetrical=False,through='ArticleImages',related_name='fodssfsdmaers', blank=True,) class ArticleImages(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.ImageField(upload_to='images',null=True,blank=True) articlea = models.ForeignKey(Article, on_delete=models.CASCADE,null=True,blank=True) How can i solve it? -
RichTextUploadingField not reflecting to models
So I have been following the step by step from this website to integrating-ckeditor-in-django but it is not reading/ reflecting in my models.py Here is the step by step that I have followed: Step 1: pip install django-ckeditor Step 2: INSTALLED_APPS = [ 'ckeditor', 'ckeditor_uploader', ..................] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CRISPY_TEMPLATE_PACK = 'bootstrap4' #... SITE_ID = 1 #################################### ## CKEDITOR CONFIGURATION ## #################################### CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } ################################### Step 3: in the main projects folder urls.py: path('ckeditor/', include('ckeditor_uploader.urls')), in the models.py from ckeditor_uploader.fields import RichTextField, RichTextUploadingField class ModelClass: ## content = models.TextField() content = RichTextUploadingField() It is getting an error when migrating ImportError: cannot import name 'RichTextField' from 'ckeditor_uploader.fields' (C:\Users\User\Desktop\Project\venv\lib\site-packages\ckeditor_uploader\fields.py) What am I missing? -
Why I Get NoReverseMatch at Error // Reverse for 'post-detail' with arguments '('',)' not found
I could not find the cause of the error. Urls.py: path('', views.post_list, name="post_list"), path('<str:url_sistem>/', views.post_detail, name='post-detail'), Views.py: def post_detail(request, url_sistem): posts = get_object_or_404(Post, url_sistem=url_sistem) return render(request, 'blog/post_detail.html', {'posts':posts}) A href link: <a href="{% url 'post-detail' post.url_sistem %}" style="color:black;"> -
How to I make a serializer from a model which has defined object (from another model)?
Im new to Django REST framework, but getting the hang of it. Im trying to make a serializer from the Profile Model but i dont know how to pass (def followers and following) into the serializer This is the Profile Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=245, null=True) image = models.ImageField(default='default.png', upload_to='profile_pics') interests = models.ManyToManyField(Category, related_name='interests_user') stripe_customer_id = models.CharField(max_length=50, blank=True, null=True) one_click_purchasing = models.BooleanField(default=False) is_vendor = models.BooleanField(default=False) # vendor bvn = models.CharField(max_length=10, null=True, blank=True) description = models.TextField(null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) company = models.CharField(max_length=100, null=True, blank=True) follow_user = models.ManyToManyField('users.Follow') def __str__(self): return f'{self.user.username} Profile' @property def followers(self): return Follow.objects.filter(follow_user=self.user).count() @property def following(self): return Follow.objects.filter(user=self.user).count() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super().save() 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) class Follow(models.Model): user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE) follow_user = models.ForeignKey(User, related_name='follow_user', on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) old_instance = models.ForeignKey('Follow', blank=True, null=True, on_delete=models.CASCADE, editable=False) def save(self, *args, **kwargs): if self.pk is not None: self.old_instance = Follow.objects.get(pk=self.pk) super().save(*args,**kwargs) def __str__(self): return f"For: {self.user} // id: {self.id}" -
How do I use a POST method to communicate with an external API in Django?
I received help from my instructor to figure out the GET command. I am struggling with the POST command. -View- from django.shortcuts import render from django.shortcuts import redirect from django.contrib import messages import json import requests from ast import literal_eval from django.shortcuts import redirect from rest_framework.views import APIView from rest_framework.response import Response def add_question(request): if request.method == 'POST': url = 'http://localhost:3000/questions/' payload = {'content':request.POST.get("content"), 'category':request.POST.get("category")} res = requests.post(url, data = (payload)) print(res) return Response(res.json()) Part of my problem is that most of the previously published advice on this topic is over 3 years old. I don't think the 'rest_framework' module is used much for this purpose anymore. It's hard to tell. Right now the error I am getting is: "raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) "POST /add_question HTTP/1.1" 500 92794" The GET method that worked for me was this: def home(request): if request.method == 'GET': print('home') api_request = requests.get("http://localhost:3000/questions/")#.json() try: print( 'api_request='+str(api_request)) q = literal_eval(api_request.content.decode('utf8')) print('q=', q, type(q)) print( q['data']) json_obj = json.dumps(q['data']) print('json_obj=', json_obj, type(json_obj)) #api = json.loads(api_request.content) api = json.loads(json_obj) except Exception as e: print( 'Exception e='+str(e)) api = "Error..." else: if request.method == 'POST': post_request = requests.post("http://localhost:3000/questions/") … -
How to Create Multiple Model Objects in Django
I have a model called coupon with a foreign realation to Course model. I need to create multiple coupons with coupon model. Let's say if the count is 50 then it should save 50 coupons in the database. Can I achieve that using bulk_create() method and how to do that. Also I'm using Django Rest Framework class Coupon(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True) expire_date = models.DateTimeField(verbose_name="expire_date", default=now()) Thank you! -
Asking for primarykeyrelatedfield after passing it also
Models.py class Event(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) host = models.ForeignKey( Profile, related_name="host", on_delete=models.CASCADE ) name = models.CharField( verbose_name='Event Name', max_length=200 ) seats = models.IntegerField(default=0) price = models.IntegerField(default=0) audience = models.ManyToManyField( Profile, related_name="audience" ) discription = models.TextField( verbose_name='About the event', null=True, blank=True ) time_start = models.DateTimeField(verbose_name='Time of starting of event') time_end = models.DateTimeField(verbose_name='Time of ending of event') address1 = models.CharField( "Address line 1", max_length=1024, ) address2 = models.CharField( "Address line 2", max_length=1024, null=True, blank=True ) zip_code = models.CharField( "ZIP / Postal code", max_length=12, ) city = models.CharField( "City", max_length=1024, ) country = models.CharField( "Country", max_length=3, ) views.py class PostEvent(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def post(self, request): instance = Event(host=request.user) instance = EventSerializer(instance, data=request.data) #after using shell, i can tell this line is creating problem i guess if instance.is_valid(): event = instance.save() return Response(event.data, status=status.HTTP_201_CREATED) else: return Response(instance.errors, status=status.HTTP_400_BAD_REQUEST) In views.py I am clearly passing instance with host in it, and other data from request. So they should combine and there should be host with a uuid, but its not passing through is_valid(), and giving the error below. serializers.py class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = '__all__' Error / can't figure out why { "host": … -
How do I stop my css from overlapping in django?
So while rendering I'm having problem as my two of my elements are overlapping. Image : https://imgur.com/0HDbWqo here's the relevant code : <style type="text/css"> .box{ position: absolute; left: 50px; width: calc(80% - 100px); border: 1px solid black; border-radius: 10px; padding: 5px; text-align: center; } {{ post.title}} by {{ post.author.username }} | Posted on {{ post.created }} {{ post.body|safe }} <form method="POST"> <div class="form-group"> {% csrf_token %}{{ form.as_p }} <button class="btn btn-secondary"> submit comment </button> </div> </form> I just can't seem to figure out how do I make the Post body and the Form element separate. -
How to pass api key in Vue.js Header?. i was used DRF pagination url
** methods: { getPostData() { axios .get("http://192.168.43.126:8000/api/?page=" + this.currentPage, { headers: { "Cache-Control": "no-cache", "content-type": "application/json", "x-api-key": "IBctIWwi.xxxxxxxxxxxxxxx", }, })** -
Regex for searching or to filter queryset in django
I am trying to filter the queryset by options that are sent through the URL. Like the following: http://127.0.0.1:8000/<int:pk>/year=2020&director=ChristopherNolan&production=warnerbros/ where the order does not matter. It should be valid even if the user retrieves using: http://127.0.0.1:8000/<int:pk>/director=ChristopherNolan&year=2020&production=warnerbros/ or just http://127.0.0.1:8000/<int:pk>/director=ChristopherNolan/ Is there any way to write regex to do this and retrive the fields in args and/or kwargs. -
Can not send POST request with CSRF token
From django view, trying to send POST request like this: import requests from django.middleware import csrf def send_view(request): post_url = 'http://some_url' # Set destination URL here post_fields = {'a': 'aaa2', 'b': 'bbb2'} # Set POST fields here header_data = {'csrfmiddlewaretoken': csrf.get_token(request)} r = requests.post(post_url, data=post_fields, headers=header_data ) print(r.status_code, r.reason) This shows error: 403 Forbidden (CSRF cookie not set.): What is my mistake? -
Django models DateTimeField and Celery problem
I am desperate. This is my Models Class: class Timer(models.Model): headline = models.CharField(max_length=255, default='') vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() bought_from = models.ManyToManyField(VigneteSeller, blank=True) start_alert = models.DateTimeField() start_notifying_me = models.IntegerField(default=20) def save(self): d = timedelta(days=self.start_notifying_me) if not self.id: self.start_alert = self.end_date - d super(Timer, self).save() def starter(self): now_date = models.DateTimeField(default=now, editable=False) if self.start_alert == now_date: return True def __str__(self): return self.headline I have this field (start_alert) and I want when (start_alert) is the same as "datetime.now()" to trigger some action in this case "task" from second file,or if there is any chance to start the function starter. The main problem is that everything works, but it is triggered by request from my view.py file I have file in my Django project which is in project/vehiclesinfo/celery/tasks.py. from celery.utils.log import get_task_logger from time import sleep from .inform_using_mail import send_mail_to from ..models import Timer from celery.schedules import crontab from celery.decorators import task sleeplogger = get_task_logger(__name__) trigger = Timer().starter() @task(name="my_first_task") def my_first_task(duration): subject = 'Ready to fly to Mars' message = 'My task done successfully' receivers = 'maymail@gmail.com' is_task_completed = False error = 'Error' try: if trigger: is_task_completed = True except Exception as err: error= str(err) logger.error(error) if is_task_completed: send_mail_to(subject,message,receivers) … -
Django : Display static images in production
I'm hosting an API made with Django on Heroku. I'm trying to upload an image from the django administration page to the "images" folder located in the "static" folder (/static/images/name.png). After uploading my image, when I try to display it (url.herokuapp.com/images/name.jpg), I get a not found page. My code is working well when I'm running in local. This is my code : settings.py : # URL prefix for static files STATIC_URL = '/static/' # Absolute path to the directory in which static files should be collected STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Use for template STATIC_TMP = os.path.join(BASE_DIR, 'static') os.makedirs(STATIC_TMP, exist_ok=True) os.makedirs(STATIC_ROOT, exist_ok=True) MEDIA_URL = "/images/" # Additional locations for static files STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/images') ] MEDIA_ROOT = os.path.join(BASE_DIR, "static/images") urls.py : from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('v1/', include('store.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py : class Shop(models.Model): name = models.CharField(max_length=255) logo = models.ImageField(verbose_name="Logo") path = models.URLField() email = models.EmailField() phone = models.TextField() def __str__(self): return self.name Thanks by advance for your help. -
Virtual Environment Transfer
Currently I have learnt Django and have made many projects. So, I wanted to deploy my projects on heroku but I have not made my projects in virtual Environment. So, they are not able to get deploy So, my question is how to can I transfer my projects to virtual environment. Or I have to make all projects again in virtual Environment? -
How to fix a MultiValueDictKeyError
I am trying to get the time spent on each page in a Django project using Javascript. I keep getting an error so I am trying to fix it the error: MultiValueDictKeyError at /backendurl/ 'timeSpent' Highlighted line of error in views.py: timeSpent = request.POST['timeSpent'] Here is the javascript in template: <script> $(document).ready(function() { var startDate = new Date(); $(window).unload(function() { var endDate = new Date(); $.ajax({ type: POST, url: "backendurl", // be mindful of url names data: { 'timeSpent': endDate - startDate || 'none' // defaults to a string }, success: function(response) { // unpack response: status = response.status } }) </script> Here is the views.py: def my_view_function(request): timeSpent = request.POST['timeSpent'] response = json.dumps({ 'timeSpent' : timeSpent, }) return HttpResponse(response) Here is the url.py path('backendurl/', views.my_view_function, name='backendurl'), -
Django NoReverseMatch Reverse for 'new_proc' with arguments '(1,)' not found
Could anyone explain what is wrong here? view: class ProcessCreate(View): def get(self,request, appId, procId): context = {'appId': appId, 'subpage':1, 'procId': procId} return render(request, 'analysis/diagram.html', context) url: path('applications/<int:appId>/processes/<int:procId>/', login_required(login_url='/analysis/login')(process.ProcessCreate.as_view()), name="new_proc") html: href="{% url 'analysis:new_proc' row.id %} " Thanks for your help -
django-elasticsearch-dsl NestedFiled not working for ManyToManyField
I have successfully been able to declare, map, and populate all model fields to Elasticsearch Index except the Price field on the BookPrice model which is using through attribute. If I remove the Price field from the document then it works fine. However, I had successfully been able to build the Index in the past, but I think I made some changes and I lost the code integrity, and it's not working now. I tried all possible combinations I found on help forums and official documents, but with no luck. I am currently using Elasticsearch == 7.8.0 elasticsearch-dsl == 7.2.1 django-elasticsearch-dsl == 7.1.1 models.py class Publisher(models.Model): publisher_name = models.CharField(max_length=50) class BookType(models.Model): book_type = models.CharField(max_length=20) # Hard Cover, Soft Cover, Kindle Edition, Digital PDF etc. class Book(models.Model): book_title = models.TextField() book_types = models.ManyToManyField(BookType, through='BookPrice', through_fields=('book', 'book_type')) class BookPrice(models.Model): book_type = models.ForeignKey(Booktype, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) price = models.DecimalField(max_digits=7, decimal_places=2) documents.py @registry.register_document class BookDocument(Document): book_title = fields.TextField( attr='book_title', fields={ 'suggest': fields.CompletionField(), }) publisher = fields.ObjectField(properties={ 'publisher_name': fields.TextField(), }) book_types = fields.NestedField(properties={ 'id': fields.IntegerField(), 'book_type': fields.TextField(), 'price': fields.FloatField() }) class Index: name = 'books' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Report fields = [ 'id', 'slug', 'published_date', 'pages', … -
Elastic Beanstalk environment's health severe: Following services are not running: release
I deployed a Django application to Elastic Beanstalk (EB) Amazon Linux 2 Python 3.7 platform and everything seems to be working fine. However, the health of the environment is severe and I can't figure out why. The only information EB gives me is the following: Overall status: Degraded - Impaired services on all instances. (there is only one instance running) Instance status: Severe - Following services are not running: release. I found no information about what the "release" service is. From the full logs, the only errors I'm seeing are the following: daemon.log: F, [2020-11-07T04:03:03.891398 #5022] FATAL -- : /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/launcher.rb:432:in `block in setup_signals': SIGTERM (SignalException) from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/single.rb:117:in `join' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/single.rb:117:in `run' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/launcher.rb:172:in `run' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/cli.rb:80:in `run' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/healthd-1.0.6/bin/healthd:112:in `block in <top (required)>' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/healthd-1.0.6/bin/healthd:19:in `chdir' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/healthd-1.0.6/bin/healthd:19:in `<top (required)>' from /opt/elasticbeanstalk/lib/ruby/bin/healthd:23:in `load' from /opt/elasticbeanstalk/lib/ruby/bin/healthd:23:in `<main>' From what I've read here this SignalException is thrown to shut down a process, so I assume it's normal. There is no other error in any of the other logs. Turning the enhanced health check off would be the easy "solution" as stated here but I would like to keep them on. Any help is very much appreciated. -
Can I use XSLT with XML in Django
I have been trying to render an XML page in Django After Passing after going to link i get a blank page and my line is commented out automatically enter image description here -
Django Inconsistent Login Behavior
I have an app in Django wherein the user logs in and is redirected to a page. I have changed the redirect url for both login and logout in settings.py to ensure redirection happens. LOGIN_REDIRECT_URL='/' LOGOUT_REDIRECT_URL='/' Below is a small snippet from the server post log-in. Notice the two POST behaviour. The first one works accurately with 302 as the response code. If you notice the next POST, it is response code 200. This 200 response code keeps occurring multiple times before I am able to login with response code 302 (that is, login works as expected). Here is another image that shows the behavior: I am baffled by this behavior. Can someone help me understand why this is happening? Thank you! -
KeyError at /videos/compose/ 'items'
here i am working with youtube api and trying get youtube video titlt with json response but getting KeyError at /videos/compose/ 'items' can you guys tell me what is wrong here , i have printed video_id that is correct but getting error on retrieving title if a video. views.py class VideoCreateView(CreateView): model = Video form_class = VideoForm template_name = "videos/video_form.html" def form_valid(self, form): video = Video() video.url = form.cleaned_data['url'] parse = urllib.parse.urlparse(video.url) video_id = urllib.parse.parse_qs(parse.query).get('v') if video_id: video.youtube_id =video_id[0] response = requests.get(f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet&id={video_id[0]}&key=[{ YOUTUBE_API_KEY }]') json = response.json() title = json["items"][0]["snippet"]["title"] video.title = title video.save() return super().form_valid(form) urls.py app_name = 'videos' urlpatterns = [ path('compose/',views.VideoCreateView.as_view(),name='new'), path('video/<str:slug>/',views.VideoDetailView.as_view(),name='video_detail'), ] if more code is require than tell me in a comment session , i will update my question with that information. -
Django hangs when i call js file from static folder
I use a template with parallax image and navigation bar in it. I've added news ticker like this: jQuery News Ticker: .remove() dom effect I use same code from link to animate my ticker: var leftMargin, scrollSpeed; var playScroll = true; scrollSpeed = 5; leftMargin = 0; function autoPlay() { if (playScroll) { $('.news-ticker-display').animate({ marginLeft: --leftMargin }, scrollSpeed, "linear", function () { var $first = $('.news-ticker-display li:first'); var width = $first.outerWidth(); if (leftMargin < -width) { $first.clone().appendTo('.news-ticker-display ul'); leftMargin = leftMargin + width; $first.remove(); $(this).css({marginLeft: --leftMargin}); } autoPlay(); }); } } autoPlay(); When i add it directly to the template it works fine. However when i try to call it from static <script src='{% static "scripts/textnews.js" %}'></script> my page starts to freeze. It doesn't happen every time. What is more frequency of freezes decrease after log out. -
django + javascript: issue with adding modelformset row
I have a template that renders a modelformset and I am trying to dynamically add rows to the formset upon the click of a button. Being a javascript ignorant, I am stucked on the following javascript problem: new_sale.html:331 Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. this is what my template looks like: <form method="POST" class="form-validate" id="formset"> {% csrf_token %} {{ formset.management_form }} <table id="formset" class="sale-form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> </div> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle row1 row2 %}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> <div id="emptyform_wrapper" style="display:none"> <table class='no_error'> {{ form }} </table> </div> </div> <br> <br> </form> <button class="btn btn-success" id="add-more">Add</button> <button id="Download"class="btn btn-primary" type="submit" form="formset">Save</button> </section> </div> </div> <footer class="footer"> <div class="footer__block block no-margin-bottom"> … -
Is it best if i use django-oscar for building a multi-vedor site?
I've been working with django for sometime now and i'm thinking about launching an ecommerce platform in my city as a startup. The thing is i can't decide whether to build it from scratch or should i use a preexisting framework like oscar... which is the best way to go if i want a multivendor site which is tailored to my specific idea? -
What is the autofocus field in Django PasswordChangeForm?
I'm looking through the Django documentation and found this line of code I don't get, specifically the autofocus part class PasswordChangeForm(SetPasswordForm): """ A form that lets a user change their password by entering their old password. """ error_messages = { **SetPasswordForm.error_messages, 'password_incorrect': _("Your old password was entered incorrectly. Please enter it again."), } old_password = forms.CharField( label=_("Old password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'current-password', 'autofocus': True}), ) field_order = ['old_password', 'new_password1', 'new_password2'] def clean_old_password(self): """ Validate that the old_password field is correct. """ old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise ValidationError( self.error_messages['password_incorrect'], code='password_incorrect', ) return old_password in the widget=forms.PasswordInput(attrs={'autocomplete': 'current-password', 'autofocus': True}) part, I don't get what the autofocus field is and what it does when it says it's True. What is the purpose of this??