Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending values from ReactForm to Django view
I have a react form as follows: <Form role="form"> <FormGroup> <UncontrolledDropdown> <DropdownToggle caret> Select from the list Of New Tests </DropdownToggle> <DropdownMenu> <DropdownItem>2001</DropdownItem> <DropdownItem>2002</DropdownItem> <DropdownItem>2003</DropdownItem> </DropdownMenu> </UncontrolledDropdown> <br></br> <br></br> <Button color="primary">Submit</Button> </FormGroup> </Form> I have the following view in Django: class FormView(APIView): def get(self, request,*args, **kwargs): return Response({"keywords":applyFormScan(2013)}) I am trying to obtain the value 2013 from the react form.I have tried post method but it doesn't work for me. -
django form submit validation error when there are two submit buttons
in this user profile edit form i have two submit button each button appear onclick when you want to change either your name or your bio (events were handled with vuejs) so when i try to submit the form with the first submit button it submits normally but when i do it with the second one it gives an error: The User could not be changed because the data didn't validate. here is my what i have in my views.py and forms.py # forms.py class UserEditForm(UserChangeForm): class Meta: model = User fields = ('profile_pic','full_name','bio') # views.py current_user = User.objects.get(id=pk) user_edit_form = UserEditForm(instance=current_user) if request.method == "POST": user_edit_form = UserEditForm(request.POST, request.FILES, instance=current_user) if user_edit_form.is_valid: user_edit_form.save() in my template: <form name="user_edit_form" action="" method="POST" enctype="multipart/form-data">{% csrf_token %} <p v-if="!showFNinput" class="text-center text-secondary mt-3"><strong @click="showFNinput = true" id="full-name-edit" > {{current_user.full_name}} <i style="font-size: 8px" class="fas text-muted fa-pen"></i></strong></p> <div v-if="showFNinput" class="text-center" > <input class="mt-3 form-control" v-focus type="text" name="full_name" value="{{current_user.full_name}} "> <!-- First submit button --> <button class="btn btn-success mt-3 mb-2" type="submit">Save</button> </div> <p id="bio-edit" v-if="!showBioinput" class="text-muted text-center" @click="showBioinput = true" > {{ current_user.bio }} <i style="font-size: 8px" class="fas text-muted fa-pen"></i></p> <div v-if="showBioinput" class="text-center" > <textarea class="form-control" v-focus name="bio" cols="5" rows="2">{{current_user.bio}}</textarea> <!-- Second submit button --> <button class="btn … -
No such table on django website deployment on Heroku
I was previously facing issues on deploying my django app on Heroku regarding static directories.But now that I have been able to deploy my website after changing settings.py , there is a error being thrown called 'no such table'.Then I went to stackoverflow for solutions but nothing worked.I am adding my settings.py file here which also has the stackoverflow solutions.I have written a if statement for using PostgreSQL as mentioned in a stackoverflow post but that also don't work.You may see that if statement in last line.My requirements.txt is all correct , so no problem in that.Plz help me. from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^&ahv#0-lkixr5bfk&)=2%$m$y8kg%z3wt_q)-m(&#u#^xu+pu' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['django-blog-sayan.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
Compare set of model instances with their conterparts in DB | Django
I have a question reg. comparing big set of model instances with data in DB. for example I have a model with 5 fields: model Foo(models.model) fields1 = models.Integerfield() fields2 = models.Integerfield() fields3 = models.Integerfield() fields4 = models.Integerfield() fields5 = models.Integerfield() class Meta: unique_together = (‘field1, field2’) and I have 400.000 model Foo entries saved in DB. Also I have 400.000 +/- few instances in memory(in python)of the same model generated from internet CSV file (without pk set). Question is – what is the most efficient way to do following: 1)If instance in python equal to same instance id DB – keep instance in DB. 2)If instance in python not equal to instance in DB – update instance in DB. 3) If instance in python does not coincide to any instances in DB – write it to DB. 4) If no instances in python coincide to particular instance in DB – delete instance from DB. Its should be bulk operations or RAW SQL as sample size is quite big. Thank you. -
Hi, I have a problem with a django app. I want do make personalized pages for users with this url: url/user/id. But something doesn't work
I'm quite new in the programming world and that's my firs real project. Usually I solve my problems just sitting and thinking till my brain burns. But this time I'm really stacked. Maybe is easy but I really didn't find solutions urls.py from django.urls import path from . import views urlpatterns = [ path('profilo/<int:my_id>/', views.profilo, name='profilo') ] views.py def profilo(request, my_id): users = User.objects.get(id=my_id) contex = { "user": users } return render(request, 'profilo/profilo.html', contex) base.html {% load static %} <html> <head> <title>Django Boyz blog</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <div class="page-header"> {% if user.is_authenticated %} <a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a> <p class="top-menu">Ciao {{ user.username }} <small>(<a href="{% url 'logout' %}">Log out</a>)</small></p> <a href="{% url 'profilo' User.id %}" class="top-menu"><span class="glyphicon glyphicon-user"></span></a> {% if user.is_superuser %} <a href="{% url 'numeroposts' %}" class="top-menu"><span class="glyphicon glyphicon-inbox"></span></a> {% endif %} {% else %} <a href="{% url 'login' %}" class="top-menu"><span class="glyphicon glyphicon-lock"></span></a> {% endif %} <h1><a href="/">Django Boyz Blog</a></h1> </div> <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> </body> </html> The error is this: NoReverseMatch at / Reverse for 'profilo' with … -
Is there any way of redirecting user from In-app browser like Instagram to Google Chrome browser using JavaScript or Python in Android?
I'm trying to make my website redirect from Instagram to Google chrome. This is my JavaScript try to redirect url, but it is not working as I thought: if(navigator.userAgent.includes("Instagram")){ window.open('https://www.google.com/','_blank'); } And in python I've tried using webrowser.get("google-chrome").open("https://www.google.co.in/"), but both methods do not work for me! Please help! Thanks in Advance. -
Passing username (and viewing as uneditable in html) in form Django
I have a form where I would like to have a username and production line send along. The thing is that the username should be taken from current logged user (and viewed as uneditable field) but the production line should be selected via dorpdown. It works by somehow since when I click on "User" dropdown it shows only the logged user. views: def order(request): storage = PartNumber.objects.all() username = request.user.username if request.method == 'POST': order_form = OrderForm(username=username, data=request.POST) if order_form.is_valid(): order_form.save() return redirect('order') elif request.method == 'GET': order_form = OrderForm(username=username) return render(request, 'dashboard/order.html', {"form": order_form, "username": username}) forms: class OrderForm(forms.ModelForm): class Meta: model = Order fields = ('end_user_id', 'production_line_id') def __init__(self, *args, **kwargs): username = kwargs.pop('username', None) super(OrderForm, self).__init__(*args, **kwargs) self.fields['end_user_id'].queryset = User.objects.filter(username=username) models: class Order(models.Model): end_user_id = models.ForeignKey(User, on_delete=models.CASCADE) production_line_id = models.OneToOneField(ProductionLine, on_delete=models.CASCADE) date_ordered = models.DateTimeField(auto_now_add=True, null=True) date_completed = models.DateTimeField(auto_now=True, null=True) def __str__(self): return str(self.status) html: {% extends 'dashboard/main.html' %} {% load static %} {% load bootstrap %} {% block content %} <h3>Zamowienie</h3> <br> <!--{{ form|bootstrap }}--> <form role="form" action="" method="post"> {% csrf_token %} <div class="form-group"> <label>Uzytkownik </label> <!--<input class="form-control" placeholder="{{user}}" readonly>--> {{ form.end_user_id }} </div> <br> <div class="form-group"> <label>Linia produkcyjna </label> {{ form.production_line_id }} </div> <br> <div class="text-center"> … -
JavaScript add class not working on Django template
I want to use this: var btns = document.getElementsByClassName("active-btn"); // Loop through the buttons and add the active class to the current/clicked button for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); // If there's no active class if (current.length > 0) { current[0].className = current[0].className.replace(" active", ""); } console.log(this.className) this.className += " active"; }); } in my base.html to have a navbar that automatically toggles this active class. But this doesn't work the element gets the class but then the page reloads and the class is away again, I think this is because I use it in a Django template. I hope you can help me. The navbar looks like this: <nav class="top-nav"> <ul class="top-nav-list"> <li class="nav-item menu-icon drop-btn"><div class="icon menu-btn" id="menu-btn"><i class="active-btn material-icons">menu</i></div></li> {% if user.is_authenticated %} <div class="menu-items"> <li class="nav-item menu-item"><a class="active-btn dropdown-btn" onclick="logoutDropDown()">{{user}}</a></li> <div class="dropdowns" id="dropdown-item"> <li class="nav-item menu-item2 dropdown-item" ><a href="/account/profile/edit">Bearbeiten</a></li> <li class="nav-item menu-item2 dropdown-item" ><a href="/account/logout">Abmelden</a></li> </div> {% else %} <li class="nav-item menu-item"> <button onclick="openLoginPopUp()" class="active-btn">Login</button> </li> {% endif %} <li class="nav-item menu-item" id="menu-item"><a class="active-btn" href="/ingredients/my">Meine Zutaten</a></li> <li class="nav-item menu-item"><a class="active-btn" href="/recipes/my">Meine Rezepte</a></li> <li class="nav-item menu-item"> <a class="active-btn active" href="/recipes/all">Alle Rezepte</a> </li> </div> <li class="nav-item menu-item … -
Preventing multiple post requests in django
I have a view function, called new_topic: def new_topic(request): if request.method == 'POST': form = TopicForm(request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topics') else: form = TopicForm() return render(request, 'learning_logs/new_topic.html',{'form':form}) And my new_topic.html is this: {% extends 'learning_logs/base.html' %} {% block title %}Topics{% endblock title%} {% block page_header %} <h1 class="display-4">Add a new topic</h1> {% endblock page_header %} {% block content %} <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Add topic"> </form> {% endblock content %} What I want to do is that if a user clicks the Add topic twice by mistake, the page should only recieve 1 post requests, not 2. Which means that the topic the user wants to add should only be added once, not twice. How can I achieve this? -
Type Error: 'bool' object is not callable
I have a profile model and I want to just the owner of the profile can see it and update it . I'm writing my own permission for that but I have that error what should I do?? Type Error: 'bool' object is not callable #views.py class ProfileRetrieveUpdateView (generics.RetrieveUpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer permission_classes = (IsOwner,) #permissions class IsOwner(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_permission(self, request, view): return request.user and request.user.is_authenticated() def has_object_permission(self, request, view, obj): return obj.user == request.user -
Objects are twicely storing into django database when a single object is created. How to fix this unexpected behavier?
Here i am trying to create a single object with youtube data api , everything is working fine except one thing , when i create a single object it automatically create two objects one with proper details and other one is blank, as shown in pictures , before creating object after creating single object I am trying with the following code. view.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() items = json["items"] assert len(items) <= 1 if len(items): title = items[0]["snippet"]["title"] video.title = title video.save() else: title = "N/A" return super().form_valid(form) models.py class Video(models.Model): title = models.CharField(max_length=255) url = models.URLField() youtube_id = models.CharField(max_length=255) slug = models.SlugField(blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("videos:video_detail", kwargs={"slug":self.slug}) def video_pre_save_reciever(sender,instance,*args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(video_pre_save_reciever,Video) if more code is require than tell me in comment , i will update my question with that information. -
Django and synced tables
I am looking for a relatively simple implementation to get a synced table into my project. I looked into stuff like: ezTables django-datatable-view django-datatables-view to replace my django-tables2 table. So far I must say all projects seem outdated and/or not maintained. I am looking for some idea which way to head ... maybe creating the django-tables2 table from a json that gets periodically called (like here) or trying to implement datatables.net by myself (maybe like suggested here)? -
'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.