Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending message and notification using Django channels
I am trying to implement a messaging system with live notification so that when a user is chatting with userA and userB messages the user it will update the chat messages live and it will update the user's contact list. I have two consumers, one is ChatConsumer, and another one is the UserChatNotificationConsumer which the latter is a connection for each user and server to a notification to them. And every user channel has a unique id (channel name). inside my ChatConsumer, I have a new_message() function which sends a new message from one user to another user in a private chat. After creating a message object in the new_message() function, I have two methods one which sends the message and another which sends the notification: def new_message(self, data): #create the message and other stuff. await self.send_chat_message_notification_user2(content) await self.send_chat_message(content) And my method for sending a notification to user is: async def send_chat_message_notification_user2(self, message): layer = get_channel_layer() await selg.channel_layer.group_send( self.user2_notification_layer, { 'type':'chat_message', 'message':message } ) Which self.user2_notification_layer is a string id of the second user in the chat notification channel. My issue is that the sockets are being connected successfully and I can see the CONNECT and HANDSHAKE process. however, after … -
need help using django-include-by-ajax
so i tried to use django-include-by-ajax to load the page's main content first and then load the sidebar and navigation stuff when it's ready. i followed the instructions here: https://github.com/archatas/django-include-by-ajax but it didn't work, the page dosen't load until everything is ready (which takes some time because of multiple APIs) and the side bar dosen't even work template: {% extends 'base.html' %} {% load static %} {% load include_by_ajax_tags %} {% block content %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="{% static 'app_name\css\style.css' %}"> {% include_by_ajax "app_name/templates/sidebar.html" %} <div id="content" class="p-4 p-md-5 pt-5"> <div class="row"> <div class="col-1" id="col1"> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"> {% if pages.has_previous %} <a class="page-link" href="?page={{ pages.next_page_number }}" aria-label="Next"> <span aria-hidden="true"><img src="{% static 'app_name/images/back.png' %}" width="50" height="50"></span></a> {% endif %} </li> </ul> </nav> </div> <div class="col-1" id="col2"> {% for url in urllist %} <img src='{{ url }}' width="800" height="800"/> {% endfor %} </div> <div class="col-1" id="col3"> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item"> {% if pages.has_next %} <a class="page-link" href="?page={{ pages.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true"><img src="{% static 'app_name/images/forward.png' %}" width="50" height="50"></span></a> {% endif %} </li> </ul> </nav> </div> </div> </div> <script src="{% static … -
Django - "Foreign key constraint is incorrectly formed"
I'm trying to add a new model to my database, but every time i create it, i get the following error: "Foreign key constraint is incorrectly formed" This happens both if i try from MySQL and Django. Here are my models: class MainApiKeys(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) key_name = models.CharField(max_length=20) public_key = models.CharField(max_length=100, blank=True, null=True) secret = models.CharField(max_length=100, blank=True, null=True) def save(self): # ALL the signature super(MainApiKeys, self).save() class Selected_key(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) used = models.ForeignKey(MainApiKeys, on_delete=models.DO_NOTHING) def save(self): # ALL the signature super(Selected_key, self).save() If i create the same table from MySQL i'll still get the error CREATE TABLE main_selected_key( user_id INT NOT NULL, used INT NOT NULL, FOREIGN KEY (user_id) REFERENCES auth_user(id) ON DELETE CASCADE, FOREIGN KEY (used) REFERENCES main_api_keys(id) ON DELETE CASCADE) The problem is not with the Foreign Key to User, i'm sure it's the second second key because if i remove that one my code will run just fine. What am i doing wrong here? -
Error django " MultiValueDictKeyError at /employeeUpdate/ 'id' " affter I edit data
Error django " MultiValueDictKeyError at /employeeUpdate/ 'id' " affter I edit data. Here my code in views.py def employeeUpdate(request): id = request.POST['id'] emp_username = request.POST['emp_username'] emp_password = request.POST['emp_password'] emp_identification_code = request.POST['emp_identification_code'] content = employee.objects.get(pk = id) content.emp_username = emp_username content.emp_password = emp_password content.emp_identification_code = emp_identification_code if(employee.objects.filter(emp_username=emp_username)): messages.success(request, 'Username already exists') return redirect("/employeeUpdate") elif(employee.objects.filter(emp_identification_code=emp_identification_code)): messages.success(request, 'Identification already exists') return redirect("/employeeUpdate") else: content.save() messages.success(request, 'Update already !!!') return redirect("/employeeBoard") -
Django Models How to
So I'm new to Django and I'm trying to develop a timecard. Employees need to allocate their time to a client's project whether billable or unbillable. They would have to log in, choose to which clients project they worked on, enter time worked and log out. -
form missing 1 required positional argument: 'request'
i have used same code for forms in previous apps but this time it doesnt seem to work, migrations have been done and i have been at this for a day and cant find a good solution of why this form isnt working. def gst_form(request): if request.method == 'POST': form = gst_form(request.POST) if form.is_valid(): form.save() return redirect("/") else: return HttpResponse("Details Invalid") else: form = gst_form() context= {'form':form} return render(request, 'main/form.html', context) -
Why does Django accept email addresses as valid URLs and how can they be rejected?
To my surprise, the following lines pass for a value that is an email address, such as test@example.org: url = 'test@example.org' URLValidator()(url) field = URLField() field.clean(url) Where I would have expected a ValidationError to be raised. Why are email addresses considered valid URLs? And what can I do to accept only domain-like strings other than making my own regex? -
Django displaying images from media file instead of database
How do I display images from media file instead of database? Specifically I want it to load images uploaded by users from media_cdn. I feel like only the views.py require changes but I'm not sure if other areas should be changed as well. Here are my Django codes settings.py STATIC_URL = '/static/' STATICFILES_DIRS =[os.path.join(BASE_DIR,"static")] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media_cdn') views.py def imgdownload(request): allimages = ImagefieldModel.objects.all() return render(request, 'main/show.html',{'images': allimages}) urls.py urlpatterns = [ .... .... path("show/", views.imgdownload, name="imgdownload"), .... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class ImagefieldModel(models.Model): title = models.CharField(max_length = 200) img = models.ImageField(upload_to = "media") class Meta: db_table = "imageupload" show.html {% extends "main/header.html" %} {% load static %} {% block content %} <head> <title>Django Display Images</title> </head> <body> <div class="container"> <table class="table table-striped"> <thead> <tr> <th>Title</th> <th>Image</th> </tr> </thead> <tbody> {% for img in images %} <tr> <td>{{img.title}}</td> <td><img src="/{{ BASIC_DIR }}/{{img.img}}" width="120"/></td> </tr> {% endfor %} </tbody> </table> </div> </body> {% endblock %} Any help is much appreciated. -
How to solve page not found error in Django?
I have a list of multiple projects on my page, and each project have a contact use button, if a user click on contact us page then it will open a popup form, and I am doing this using Ajax. But whenever i click on the button it displays page not found in Network(After debug). Please let me know How I can solve thsi issue. Here is my urls.py file... re_path('ajax/datadis/<int:pk>/$', views.dataview, name='dataview'), here is my views.py file... def dataview(request, id): template_name = 'page/ajax/popup.html' return render(request, template_name) here is my index.html file code... <ul class="product-rating"> <button title="Enquire for {{i.name}}" id="id_{{i.id}}" class="btn btn-primary btn-sm" onclick="projectDetail({{i.id}})" data-url="{% url 'appname:projectview' i.id %}">Contact Us</button> </ul> here is my Ajax Code...Which open the Popup Form... </script> function projectDetail(id){ var html = ''; var modalDiv = $("#modalData"); $.ajax({ url: "{% url 'appname:dataview' %}"+id, type:"GET", dataType:"HTML", success: function(res) { modalDiv.html(res); $("#exampleModal").modal("show"); } }); } </script> here is my popup model code... <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" id="modalData"> <p>{{i.name}}</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> … -
React Native Apollo + Django: Network Request Failed
I'm very new to programming and couldn't understand how my react native expo app isn't fetching data from my Django server (which is running). How can I resolve this? I've got graphene-django running at the back. Here's my App.js Network Error: Network Request Failed PS. I definitely need more practice on this. Thanks for the help. import React, { Component } from 'react' import { StyleSheet, Text, View } from 'react-native' import { ApolloClient, HttpLink, InMemoryCache } from 'apollo-boost' import { ApolloProvider, gql, useQuery } from '@apollo/client' const client = new ApolloClient({ link: new HttpLink({ uri: 'http://(local-ip-address):8000/graphql' }), cache: new InMemoryCache(), }) const todoQuery = gql` query fetchTodo { todos { rank title content } } `; const TodoComponent = () => { const { loading, error, data } = useQuery(todoQuery); if (loading) return "Loading..."; if (error) return `Error! ${error.message}`; return ( <ul> {data.todos.title.map((title) => ( <li>{title}</li> ))} </ul> ); }; export default class App extends Component { render() { return ( <ApolloProvider client={client}> <View style={styles.container}> <Text style={styles.welcome}>Welcome to React Native!</Text> <Text> <TodoComponent style={styles.welcome}/> </Text> </View> </ApolloProvider> ) } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: … -
Errno 5 Input/output error linked with context_processor
I try to deploy my django app My home page is OK but when I try to loggin, I got an error as mentionned by django debugtoolbar, error is link with variable I declare in my context_processor but, I did not change this files and it works on preprod server moreover, there is a "s" variable in local vars I did not understand and don't where is declare I suspect a "CTRL+s" that did not apply but??? I look for in context_processor and could not find it where this variable can come from to be referenced in local vars djangodebugtoolbar? def data_context_processor(request): site_selectionne = None liste_abreviations_sites = '' language = None pays = [] user_site = [] user_site_type = [] sites = [] user_allowed_to_randomize = False allowed_to_randomize = False user_can_randomize = False can_randomize = False stock_alert = {} stock_confort = {} patients = [] # patients randomized that can be re-allocated # liste des abréviation des sites issue du models Site sous forme de chaine de caractères # pour utilisation dans fonction JS (transmis via data-site dans l'élément navbar-brand du menu _nav.html) for s in Site.objects.all().order_by('sit_ide'): liste_abreviations_sites = liste_abreviations_sites+','+s.sit_abr if request.user.is_authenticated: # site de l'utilisateur connecté user_site = Site.objects.get(profile__user = … -
User directory path for AbstractBaseUser inheritance
I want to upload the avatar to user.id/filename. But I have a problem with this, when I run the migrate Command, I get the following error Problem -
Creating multiple types users in django rest framework, got an unexpected keyword argument 'last_login'
I am trying to learn Django, and I am creating various cases just to exercise and hopefully learn something new. Suppose that I am trying to create different users and assign different permissions latter, but first lets try to create them first. I was researching last night and it is a common problem and many differnt implementations. Most common that I have seen is with student, teacher, admin. My case is similar, but instead of teacher it is Staff as staff member. Staff inherits from User, which itself inherits from AbstractBaseUser. Below is my code for each class, model and serializer. User mode: class User(AbstractBaseUser): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(db_index=True, unique=True) username = models.CharField(max_length=40, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name','username'] objects = UserManager() ## And user manager: class UserManager(BaseUserManager): def get_by_natural_key(self, email): return self.get(email=email) Model: class Staff(User): qualification = models.CharField(db_index=True, max_length=255) department = models.CharField(db_index=True, max_length=10) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'department','username'] objects = StaffManager() def __str__(self): return self.first_name Staff Model Manager: class StaffManager(BaseUserManager): def create_staff(self, first_name, last_name, email, qualification, department, password=None): if email is None: raise TypeError('Users must have an email address.') staff = Staff(first_name=first_name, last_name=last_name, … -
How to automatically link the users table to another table once a user gets registered in django
I am trying to create an e-commerce website, in which I have used the functionality of the Django authentication to allow users to register and login. However, in the registration form, I take the information from 2 tables at once, like this... In my models.py... class Profile (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobileNumber = models.CharField(max_length=13) address = models.ForeignKey(Shipping, on_delete=models.DO_NOTHING, default=False) guest = models.BooleanField(default=False) class Shipping(models.Model): addressLine1 = models.CharField(max_length=100) addressLine2 = models.CharField(max_length=100) city = models.CharField(max_length=40) postalCode = models.CharField(max_length=5) landmark = models.CharField(blank=True, max_length=80) And my forms.py... from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile from store.models import Shipping class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() mobile_number = forms.CharField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'mobile_number', 'email', 'password1', 'password2'] class AddressRegisterForm(forms.ModelForm): class Meta: model = Shipping fields = ['addressLine1', 'addressLine2', 'city', 'postalCode', 'landmark'] And finally my signals.py... from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() My information get stored in the relevant tables, however there seems to be no effect on the … -
How to return multiple dataframes as JsonResponse in Django?
I have 2 dataframes. I have to send these two dataframes in json format whenever the django API is called. c = a.to_json(orient='records') d = b.to_json(orient='records') return JsonResponse(json.loads(c,d),safe = False) a and b are dataframes I'm getting error when I'm executing the above code. How to send the 2 separate dataframes in json format. -
Django: Javascript is not being imported to global functions
I'm developed a webapp using Django and all works fine. Now I wanted to add a Webseit Tour guide and im using https://github.com/iamdanfox/anno.js. Now to my problem: I downloaded all the files i need and added the files to my static files. I'm importing the js files in my HTML as follows: home.html / Local <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script src="{% static 'main/js/tour/anno.js' %} type="text/javascript""></script> <script src="{% static 'main/js/tour/jquery.scrollintoview.js' %}" type="text/javascript"></script> The javascript files are unedited and saved in the static files that are written using jquery: https://github.com/iamdanfox/anno.js/blob/gh-pages/dist/anno.js https://github.com/iamdanfox/anno.js/blob/gh-pages/bower_components/scrollintoview/jquery.scrollintoview.js If I'm on my Local machine then my file is imported and everything works as expected. But if I upload it to my production server the file (anno.js) is not loaded (well atleast the function Anno is not imported to the global env). Im using Google Appengine to host the webapp. home.html /production <script src="https://storage.googleapis.com/pa_static/dev/main/js/tour/anno.83c63efc17a2.js" type="text/javascript""></script> <script src="https://storage.googleapis.com/pa_static/dev/main/js/tour/jquery.scrollintoview.42cd3e5eb217.js" type="text/javascript"></script> As STATICFILE_STORAGE im using a custom class, that inherates from ManifestStaticFilesStorage STATICFILES_STORAGE = 'web.storage.ForgivingManifestStaticFilesStorage' Any Idea why this is? Im really clueless on even where to start looking for the error. Thank you very much in advance! -
How to handle this in high concurrency in Django?
I have some code like this: bargain_count = BargainLog.objects.filter(bargain_start_log=bargain_start_log).count() # calculate `bargain_money` according to current `bargain_count` BargainLog.objects.create(bargain_start_log=bargain_start_log, bargain_money=bargain_money) But in case of high concurrency, I would get the same value of bargain_count, and then I would not get bargain_money as expected. So, it there any approach I can bundle the count() and create() in atom. -
models.E006 in abstract parent model - Django 3.1
I have an abstract model and a few other classes that inherit from it. # models.py class Parameter(models.Model): data = integer = models.IntegerField(blank=True, null=True) class Meta: abstract = True class Temperature(Parameter): received_timestamp = models.DateTimeField(default=datetime.now, blank=True) class Ph(Parameter): received_timestamp = models.DateTimeField(default=datetime.now, blank=True) although my Parameter class is abstract, I get models.E006 error in `makemigrations script. graphs.Temperature.data: (models.E006) The field 'data' clashes with the field 'data' from model 'graphs.temperature'. graphs.Ph.data: (models.E006) The field 'data' clashes with the field 'data' from model 'graphs.ph'. based on Abstract base classes and this question, if I inherit from an abstract base class, there should be no conflict in the name of the fields of various child classes with their parent (because it's abstract). any ideas? -
Django app deployment in AWS Beanstalk - Error after deployment
I have a django app deployed to AWS beanstalk. The first version was fine after following the official documentation: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html when I deploy, I get this error on the terminal and my eb status health is Red. I follow all the instructions but don't know what is the problem. and the 502 Bad Gateway occure in my page. 2020/12/17 15:03:40.884211 [ERROR] An error occurred during execution of command [app-deploy] - [StageApplication]. Stop running the command. Error: chown /var/app/staging/unifolio-src/bin/python: no such file or directory could Anybody kindly help me? -
automatically add a new models to admin page
i have a calculator app, inside it i have a Transaction , Family_group , Family_member models see pic below. i want everytime i try to make a new Transaction there will be a default 1 Family_group and Family_member added automatically, without me starting one each time. is there any way to do it ? -
Django + ReactJS. The Httponly cookie is not saved in the browser at React side. I also gave {withcredentials : true} at both side
I use django rest_framework_simplejwt to generate JWT token and set in browsable cookie with Httponly flag. At the Django side it work perfectly but at react side it not work perfectly. Read many answers related to this question like this and this but not solved my problem yet. Please help me Where am I wrong. DJANGO SIDE views.py from rest_framework_simplejwt.views import TokenObtainPairView from django.conf import settings from rest_framework import status from rest_framework_simplejwt.exceptions import TokenError,\ InvalidToken from rest_framework.response import Response class MyTokenObtainPairView(TokenObtainPairView): def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) except TokenError as e: raise InvalidToken(e.args[0]) # set access token in browser with Httponly cookie. res = Response(serializer.validated_data, status=status.HTTP_200_OK) access_token = serializer.validated_data['access'] res.set_cookie("access_token", access_token, max_age=settings.SIMPLE_JWT.get('ACCESS_TOKEN_LIFETIME').total_seconds(),samesite='Lax',secure=False, httponly=True) return res authentication.py from rest_framework_simplejwt.authentication import JWTAuthentication from django.conf import settings class CookieHandlerJWTAuthentication(JWTAuthentication): def authenticate(self, request): # If cookie contains access token, put it inside authorization header access_token = request.COOKIES.get('access_token') if(access_token): request.META['HTTP_AUTHORIZATION'] = '{header_type} {access_token}'.format( header_type=settings.SIMPLE_JWT['AUTH_HEADER_TYPES'][0], access_token=access_token) return super().authenticate(request) urls.py from .views import MyTokenObtainPairView urlpatterns = [ ...... path('auth/', include('djoser.urls')), # path('auth/', include('djoser.urls.jwt')), path('auth/api/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), ] settings.py CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', 'http://127.0.0.1:8000' ) Work perfectly(Token set in cookie with Httponly.): REACTJS SIDE Login.js axios.defaults.withCredentials = true const Login = … -
Django search vector - no match on exact keyword
I have an application where customer can search for products by name, brand etc. the problem is if you write the exact name or the exact brand name will result in no match, if you write the half of the name or the id will return a match view def home(request): active_product = Product.objects.all().filter(show=True).order_by('-score', '-brand_name') #Paginator paginator = Paginator(active_product, 20) page = request.GET.get("page") active_product = paginator.get_page(page) #Filterd by search searchProduct = request.GET.get("do_search") if searchProduct: active_product = Product.objects.annotate(search=SearchVector('name', 'id', 'sex','brand_name'),).filter(search__icontains=searchProduct) return render(request, 'index.html', {'productObject': active_product}) Model: class Brand(models.Model): name = models.CharField(unique=True, max_length=30, blank=False,null=True) def __str__(self): return self.name class Product(models.Model): genderChoice = (('W','Female'),('M','Male'),('U','Unisex')) id = models.BigIntegerField(primary_key=True, null=False) brand_name = models.ForeignKey(Brand, to_field='name', on_delete=models.CASCADE, related_name='brand_name', default='Brand Name') name = models.CharField(max_length=300, blank=False,null=False) sex = models.CharField(max_length=7,choices=genderChoice, default='U') p_type = models.CharField(max_length=50, blank=True,null=True) image_link = models.CharField(max_length=500, blank=True,null=True) stock_price = models.DecimalField(max_digits=10,decimal_places=2, default=999.00) show = models.BooleanField(default=False) in_stock = models.BooleanField(default=False) created = models.DateField(auto_now_add=True) volume= models.CharField(max_length=50, blank=True,null=True) score = models.IntegerField(default=1) price = models.DecimalField(max_digits=100, default=999.00, decimal_places=2) def __str__(self): template = '{0.name} {0.brand_name} {0.volume} {0.price}' return template.format(self) html: <form class="my-2 my-lg-0" action="{% url 'home'%}" method="GET"> <div class="input-group mb-3"> <input type="search" class="form-control border-dark" placeholder="search" aria-label="Search" aria-describedby="button-addon2" name="do_search"> <button class="ml-1 btn btn-outline-dark" type="submit" id="button-addon2">Search</button> -
Error building my web application using Docker
I am a newbie using Docker, I have completed my web application in Django, and I want to containerize it using Docker. I have gone through a particular tutorial where an existing web application was dockerized successfully but when I tried the same method, I got an error which says Failed to execute script docker-compose error logs Building web Traceback (most recent call last): File "compose\cli\main.py", line 67, in main File "compose\cli\main.py", line 126, in perform_command File "compose\cli\main.py", line 302, in build File "compose\project.py", line 468, in build File "compose\project.py", line 450, in build_service File "compose\service.py", line 1147, in build compose.service.BuildError: (<Service: web>, {'message': 'dockerfile parse error line 1: FROM requires either one or three arguments'}) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "docker-compose", line 3, in <module> File "compose\cli\main.py", line 78, in main TypeError: can only concatenate str (not "dict") to str [11920] Failed to execute script docker-compose Dockerfile FROM python: 3 ENV: PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 -
Django author Form not saving to database
models.py class Blog(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.CharField(max_length=100, unique=True) post_pic = models.ImageField(upload_to ='media/post_pics/', default =None ) body = models.TextField() posted = models.DateTimeField(db_index=True, auto_now_add=True) #author = must be logged in, populate from login details forms.py class postForm(forms.Form): title = forms.CharField(max_length=100) slug = forms.CharField(max_length=100) post_pic = forms.ImageField() body = forms.CharField(widget=SummernoteWidget()) views.py def write_detail(request): template_name = 'blog/write.html' if request.method == 'POST': post_form = postForm(request.POST) if post_form.is_valid(): new_post = Blog(title=title,slug=slug,post_pic=post_pic,body=body) new_post.save() return HttpResponseRedirect(blog.get_absolute_url()) else: post_form = postForm() return render(request, template_name, {'post_form': post_form}) write.html {% extends 'blog/base.html' %} {% load static %} {% block back-img %}'{% static 'blog/assets/img/intro.jpg' %}'{% endblock back-img %} {% block titdes %}Write{% endblock titdes %} {% block title %}Write{% endblock title %} {% block pagedes %}A django powered community blog{% endblock pagedes %} {% block body%} <form method = "POST"> {{ post_form.as_p }} {% csrf_token %} <button type="submit" class="btn btn-primary">Publish</button> </form> {% endblock %} I have set up this form so that authors can write articles to the blog without accessing the admin panel and I believe it should work but it isn't saving to the database. I have tried to work on the views over and over but don't know what else to do. Please don't delete my … -
PKCE Parameters for Snapchat
I'm attempting to write a django-allauth Provider for Snapchat and I'm stuck at a road block. Snapchat requires PKCE parameters. I first changed the AUTH_PARAMS. 'AUTH_PARAMS': { 'code_challenge': 'state', 'code_challenge_method': "S256" } This has only resulted in invalid responses from the Snapchat API upon Access_Token Request, after I have the code response. This error the first error I got. {'error': 'invalid_request', 'error_description': 'Invalid code_verifier length.', 'state': ''} After overriding the SocialLogin.stash_state I receive this error. {'error': 'invalid_grant', 'error_description': 'Invalid code_verifier.', 'state': ''} From what I can dig through the code of all auth I can't find anything in the codebase on the PKCE parameters or base64 Url SHA256 encoding. I'm willing to implement the solution but I'm stuck finding where to subclass the state parameters then match it after. There are some issues around the Snapchat Docs with this as well. https://gist.github.com/CisarJosh/778485dc31d9f268da0339f715ab86fd This is a gist with some of my attempt.