Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do you print a receipt using Star TSP 650 II?
Does anyone know a beginner friendly tutorial for Star TSP 650II (using parallel port) to print something from django/python? I can't seem to figure out how it works. -
How to combine two loops in the same excel page for xlsxwriter
I'd like to add a blank line and some data after items in my model are looped. I tried it out but it cant work as expected. I think I do not know how to grab the last item and put a command to create a blank line and thereafter write the additional data. Here is what I tried. def ExportsView(request): output = io.BytesIO() workbook = xlsxwriter.Workbook(output, {'in_memory': True}) worksheet = workbook.add_worksheet('books') title = workbook.add_format({'bold': True,'font_size': 15,'align': 'center','valign': 'vcenter','border': 1}) header = workbook.add_format({'bold': True,'color': 'black','align': 'left','valign': 'top','border': 1}) boarders = workbook.add_format({'border': 1,'font_size': 8}) student_borrowings = request.session.get('student_borrowings') the_stude = Student.objects.get(school=request.user.school,student_id=student_borrowings) no_of_books = Issue.objects.filter(borrower_id__school_id=request.user.school.id,borrower_id__student_id=student_borrowings).count() all_books = Issue.objects.filter(borrower_id__school=request.user.school,borrower_id_id=the_stude) worksheet.set_landscape() worksheet.center_horizontally() worksheet.set_margins(left=0.25, right=0.25, top=0.75, bottom=0.75) worksheet.merge_range('A1:I1',"ADM: " + str(the_stude).upper() + " - CURRENTLY BORROWED BOOKS: " + ( str(no_of_books)),title) col = 0 #Begins from the first column for index, data in enumerate(all_books): row = 2 + index worksheet.write(row, col, index + 1,boarders) worksheet.write(row, col + 1, data.book_id.book_name,boarders) worksheet.write('A2', 'No', header) worksheet.write('B2', 'Name', header) #Borrowing History ever_borrowed = Issue.deleted_objects.filter(borrower_id__school=request.user.school,borrower_id_id=the_stude) if ever_borrowed.count() > 0: worksheet.merge_range("A1:I1", " ",title) worksheet.merge_range('A1:I1',"RETURNED BOOKS: " + ( str(ever_borrowed.count())),title) for index, data in enumerate(ever_borrowed): worksheet.write(row, col, data.book_id.book_name,boarders) worksheet.write(row, col + 1, data.book_id.reg_no,boarders) row += 1 worksheet.write('A2', 'Name', header) worksheet.write('B2', 'Reg No', header) … -
Trying to run Django, Redis, Celery and Supervisor on Ubuntu 18.04 but not working
Hi I have made an application where I pull data and display in real time on my website. On local, it works perfectly fine when I run the following: celery -A proj_name beat -l INFO celery -A proj_name worker -l INFO -p gevent I use gevent because I am on Windows. On the Ubuntu server, I do not think I would need that. So now on the server, I have followed the below article to the letter: https://realpython.com/asynchronous-tasks-with-django-and-celery/#running-remotely When I get to the last part: sudo supervisorctl start pichacelery it gives me the following error: bscscanapicelery: ERROR (no such file) These are my files: bscscanapi_celery.conf ; ================================== ; celery worker supervisor example ; ================================== ; the name of your supervisord program [program:bscscanapicelery] ; Set full path to celery program if using virtualenv command=/home/djangoadmin/.virtualenvs/bscscanapi/bin/celery worker -A bscscanapi --loglevel=INFO ; The directory to your Django project directory=/home/djangoadmin/stalker-nichan/bscscanapi ; If supervisord is run as the root user, switch users to this UNIX user account ; before doing any processing. user=djangoadmin ; Supervisor will start as many instances of this program as named by numprocs numprocs=1 ; Put process stdout output in this file stdout_logfile=/var/log/celery/bscscanapi_worker.log ; Put process stderr output in this file stderr_logfile=/var/log/celery/bscscanapi_worker.log … -
Django submit file form won't save to models through front-end
So the goal is to get the user to upload images inside the application, and for the images to be displayed on the screen. The problem is that the forms will not save to the models I made. I am following Django Central https://djangocentral.com/uploading-images-with-django/ for guidance for uploading my images. What I have at the moment is where the user can type inside the form for their caption and where the user can select a file for their image, but nothing happens when they click the upload button. All that happens, is that it redirects me to the homepage for some reason, but I can fix that later. The only way for the images to be displayed on the website is if I manually go into the admin panel and upload the image there. If anyone could help I would much appreciate it. view.py def profile(request): if request.method == "POST": form = User_Profile_Form(data = request.POST, files = request.FILES) if form.is_valid(): form.save() obj = form.instance return render(request, "main/profile.html", {"obj":obj}) else: form = User_Profile_Form() img = User_Profile.objects.all() return render(request,"main/profile.html", {"img":img, "form":form}) models.py class User_Profile(models.Model): caption = models.CharField(max_length = 100) image = models.ImageField(upload_to = "img/%y", blank=True) def __str__(self): return self.caption forms.py from django … -
Django: redirecting to an external URL stored in the dB
I'm building a Django application. My end goal is for the user to be able to click a link to be redirected to an external site. Here's my code: models.py class Entry(models.Model): manufacturer = models.CharField(max_length=255) source_url = models.URLField(blank=True) views.py def purchase(request, entry_id): entry = get_object_or_404(Entry, pk=entry_id) return redirect(entry.source_url) entries.html {% if user.is_authenticated %} <a href="{% url 'purchase' %}">Purchase!</a> {% endif %} urls.py urlpatterns = [ path('', views.index, name='index'), path('entries/<int:entry_id>', views.entry, name='entry'), ] The data in the database looks as follows: id manufacturer source_url 1 Mercedes https://www.mbusa.com/en/home 2 BMW https://www.bmw.com/en/index.html 3 Audi https://www.audiusa.com/us/web/en.html The error message I'm getting is: Exception Value: Reverse for 'purchase' not found. 'purchase' is not a valid view function or pattern name. As a test, I changed the following line of code: From: <a href="{% url 'purchase' %}">Go to Source!</a> To: <a href="www.google.com">Go to Source!</a> This eliminated the "reverse" error, but the URL that it created was: http://127.0.0.1:8000/entries/www.google.com Is the "reverse" error caused by the lack of a URL route for "purchase" in urls.py? If yes, how would I define this? Thanks in advance for helping this Django newbie! -
Basic Question - Django Database PostgreSQL shuts down after pgAdmin app is closed
I am an absolute beginner with Django and have been trying to learn. I am currently stuck on one thing. I have a Django app that runs with PostgresSQL. I use Amazon RDS to host my database. It works just fine. I understand that I need to have the inbound rules set to my IP address. However, when I close the pgAdmin app on my computer (mac) the database shuts down. I can't run the django app anywore with the following error: Is the server running on host "XXX.cds3kvmdaz5k.us-east-2.rds.amazonaws.com" (3.141.229.116) and accepting TCP/IP connections on port 5432? Is there any way to not have the pgAdmin app open and still run the project? I know its a dumb question, but there has to be a way consdering in production it should not run based off of one computer running an app or not. -
Django MPTT how to remove indentation from html template
I am using django MPTT model in my template and just want to remove indentation. Now it's look like this: how to remove indentation from html template? here is my html: {% load mptt_tags %} {% recursetree contact %} {{node.message}} {% if not node.is_leaf_node %} <div class="children pl-2 pl-md-5"> {{ children }} {% endif %} {% endrecursetree %} -
How to parametrize a test's django settings?
Normally when you want to override settings for a test you can do with self.settings(API_KEY=None): To run that test with API_KEY unset. I'm trying to parametrize a pytest to check that certain settings have been set: @pytest.mark.parametrize('blank_setting', [API_KEY_1, API_KEY2]) def test_improperly_configured(self, client, blank_setting): with self.settings(blank_setting=None): response = client.get(reverse('api:info')) assert response.status_code == 500 But of course it says name 'API_KEY_1' is not defined Is it possible to parametrize settings this way? -
Implement webhook in Django
I have never implemented a webhook before. I am working on a payment confirmation, where I need to know if a payment is successful and if it is the client should be redirected to payment complete site. Below is the view for the checkout page class Payment(View): def __init__(self): #Get model webshopRestaurant data for hd2900 restaurant for location id for this restaurant self.hd2900RestaurantObject = RestaurantUtils(restaurantName = restaurantName) def get(self, request, *args, **kwargs): #Check if session is still valid sessionValid = webshopUtils.checkSessionIdValidity(request = request, session_id_key = session_id_key, validPeriodInDays = self.hd2900RestaurantObject.restaurantModelData.session_valid_time) #In this case the session has expired and the user will be redirected if sessionValid is False: return redirect('hd2900_takeaway_webshop') if 'pickupForm' in request.GET: deliveryType ='pickup' elif 'deliveryForm' in request.GET: deliveryType = 'delivery' elif ('deliveryForm' not in request.GET) and ('pickupForm' not in request.GET): #Here is where I need to implement the webhook pass #Write the customer info into the data base webshopUtils.create_or_update_Order(session_id_key=session_id_key, request=request, deliveryType = deliveryType) #Calculate the total price followed by creation of paymentID from NETS if 'pickupForm' in request.GET: totalPrice = webshopUtils.get_BasketTotalPrice(request.session[session_id_key]) + self.hd2900RestaurantObject.restaurantModelData.bagFee elif 'deliveryForm' in request.GET: totalPrice = webshopUtils.get_BasketTotalPrice(request.session[session_id_key]) + self.hd2900RestaurantObject.restaurantModelData.delivery_fee + self.hd2900RestaurantObject.restaurantModelData.bagFee #Create an order reference and link that to NETS reference reference = webshopUtils.get_order_reference(request = request, … -
Project file window is yellow in pycharm
I'm working with pycharm 2019 and django, in win 10 in a project that I haven't opened in a year. The Project files window is showing up as yellow, which seems new. What does this mean and how to I get the files to appear as white. -
How to implement multichat in Django channels
I am implementing a real-time chat functionality using Django channels 3 and Django rest framework, where I have two types of users clients and admins , what I am trying to do is to create for every user a chat room in order to discuss with the admins, I tried to use multiple rooms and it doesn't work because the admin is unaware of the newly created user room , my second choice is to use room_group_name , but so far I don't really understand it, if someone can clarify or help I would be grateful . Consumer.py async def connect(self): self.user = self.scope["user"] print(self.user.is_superuser) print(self.user.is_staff) if self.user.is_superuser: self.room_name = "chat" self.room_group_name = 'admin_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() if self.user.is_client: self.room_name = "chat" self.room_group_name = 'client_%s'.format(self.user) % self.room_name admin = 'admin_%s' % self.room_name await self.channel_layer.group_add( # self.room_group_name, self.room_group_name, self.channel_name ) await self.accept() So far I can separate the two groups, but the trick is how to add admin users to the client group room ?? -
Can you limit the records count for each user Django
Can you set a database constraint to allow the users to add only a specific amount of records that have the a specific value field? Example: class Example(models.Model): CHOICES = ( ('1', '1'), ('2', '2'), ('3', '3'), ) user = models.ForeignKey(User) choice = models.Charfield(choices=CHOICES) I want to allow each user to be able to add only 4 records with choice 3, is there a current way to do it at the database level? -
I need to do a function that calculates the item prices dynamically without storing them in the database django
I need to do a function which calculates the prices of the items dynamically without storing them in the database because the prices of the items change daily, I have scratched the price of the day and I need the items to be calculated based on this price models.py class Product(models.Model): prdct_name = models.CharField(max_length=17, verbose_name=_("Article ")) prdct_category = models.ForeignKey("Category", on_delete=models.CASCADE, blank=True, null=True) prdct_description = models.TextField(verbose_name=_("Description")) prdct_img = models.ImageField(upload_to='product/',verbose_name=_("Image"), blank=True, null=True) # prdct_img prdct_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_("Prix ")) prdct_cost = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_("Prix promotionel ")) prdct_weight = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_("Poid ")) prdct_created = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name=_("Date Creation ")) prdct_genre = models.CharField(max_length=50, verbose_name=_("Genre ")) prdct_matiere = models.CharField(max_length=50, verbose_name=_("Matiere ")) prdct_titrage = models.CharField(max_length=50, verbose_name=_("titrage ")) prdct_in_stock = models.BooleanField(verbose_name=_("in_stock ")) prdct_slug = models.SlugField(blank=True, null=True) the function to scrape the price from the site def get_prixmatiere(): # get price from cpor import requests from bs4 import BeautifulSoup response = requests.get("https://www.gold.fr/cours-or-prix-de-l-or/") soup = BeautifulSoup(response.text , 'lxml') product_price = soup.find_all("td",{"class" : "price"})[0].text.replace('€', '').replace(' ', '') # calculate price prixdug = float(product_price) / 4 * 3 / 1000 * 210 - 500 prixmatiere = float(product_price) / 4 * 3 / 1000 * 210 return prixmatiere i need to get the price of the item def calc_price_item(self): self.dailyprice … -
Python convert text of SVG to PNG without Cairo
I have been working for about 20+ hours and I'm stuck. I have a Django app deployed on azure web apps. In one of my django views, I was able to successfully convert an svg to png on my local device with Cairo, however, Cairo requires homebrew to execute brew install pango. As such, Cairo is completely out of the picture to convert SVG to PNG. I also looked into using svglib and running from svglib.svglib import svg2rlg, however svg2rlg(input) requires input to be the name of a file. Because I'm using Django and I'm running a webapp, I certainly want to avoid creating files. How would one go about converting svg to png without cairo. Can I somehow input text, something like string="""<?xml version="1.0" standalone="no"?> <svg width="200" height="250" version="1.1" xmlns="http://www.w3.org/2000/svg"> <line x1="10" x2="50" y1="110" y2="150" stroke="orange" stroke-width="5"/> <polyline points="60 110 65 120 70 115 75 130 80 125 85 140 90 135 95 150 100 145" stroke="orange" fill="transparent" stroke-width="5"/> </svg>""" into svg2rlg? Can I simply download the Cairo library to the Django project folder? -
request.POST always empty
I'm trying to send data from my form to a view with ajax, but my form fields in request.POST are empty.My fields during the submission do contain the data. But when I check the contents of request.POST the form data is still empty. So the form.is_valid value is always False. How can i solve this problem? here is my form <form id="formId" method="post"> {% csrf_token %} {{form.errors}} {% for field in form %} <div class="input-group mb-3"> <span class="input-group-addon bg-white"> <i class="{% if field.html_name == 'email' %} fa fa-envelope {% else %} fa fa-user w-4 {% endif %}"> </i></span> {{field}} </div> {% endfor %} <div class="row"> <div class="col-12"> <button type="submit" id="btnRegister" class="btn btn-primary btn-block px-4">Créer le compte</button> </div> </div> </form> ajax <script> $(document).ready(function(){ $("#btnRegister").on("click",function(e){ var form = document.getElementById("formId"); function handleForm(event) { event.preventDefault(); } form.addEventListener('submit', handleForm); }); }); var serializeData = $("#formId").serialize(); var nom_agent = $("#id_nom_agent").val(); var prenom_agent = $("#id_prenom_agent").val(); var email = $("#id_email").val(); $.ajax({ dataType: 'json', url: "{% url 'add_agent' %}", type: 'post', data: { "csrfmiddlewaretoken" : "{{ csrf_token }}", 'nom_agent': nom_agent, 'nom_agent': prenom_agent, 'email': email, }, success: function(data){ console.log("ok"); }, error: function(){} }); </script> My view is the following def add_agent(request): if request.is_ajax(): if request.method=="POST": print(request.POST) form = RegisterForm(request.POST) if … -
How to receive AJAX POST data in a view Django?
So I have a button called Print Label, which on click should send some data to a view, and then my view should display that data in an html page. So far, it seems like I have been able to save the data as I can see it using the alert method using JS. However, when I POST this data using AJAX, it seems like the data is not going through as my view is not recognizing the POST call(I am getting a 404 page). url for view: path('label/', plabel, name="label.html"), Saving data on click function: $("#table").on('click','.btn-outline-primary',function(){ // get the current row var currentRow=$(this).closest("tr"); var col1=currentRow.find("td:eq(0)").html(); // get current row 1st table cell TD value var col2=currentRow.find("td:eq(1)").html(); // get current row 2nd table cell TD value var col3=currentRow.find("td:eq(2)").html(); // get current row 3rd table cell TD value var col4=currentRow.find("td:eq(3)").html(); var col5=currentRow.find("td:eq(4)").html(); var col6=currentRow.find("td:eq(5)").html(); var col7=currentRow.find("td:eq(6)").html(); var col8=currentRow.find("td:eq(7)").html(); var col9=currentRow.find("td:eq(8)").html(); var col10=currentRow.find("td:eq(9)").html(); var col11=currentRow.find("td:eq(10)").html(); var col12=currentRow.find("td:eq(11)").html(); var col13=currentRow.find("td:eq(12)").html(); var col14=currentRow.find("td:eq(13)").html(); var mydata= [col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14]; AJAX call: $.ajax({ url: "/label/", type: "POST", data:{ csrfmiddlewaretoken: '{{ csrf_token }}', mydata: mydata}, }); alert(mydata); //this is showing my data has been saved Picture … -
Get_next_by_FOO method incorrectly returns link
My problem is that I specify the get_next_by_FOO method, but the link does not work correctly. #models.py class Project(models.Model): user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE, db_index=True) name = CharField(max_length=150, db_index=True) cover = models.ImageField( upload_to="project_photos/", null=True, blank=True ) site = URLField( max_length=200) description = TextField() note = CharField( max_length=150) created_at = DateTimeField(auto_now_add=True) def next(self): return self.get_next_by_created_at() def pre(self): return self.get_previous_by_created_at() #html <a href="{{ project.next }}">Next project</a> <a href="{{ project.pre }}">Previous project</a> And it gives out the following link: http://localhost:8000/projects/8/%D0%9D%D0%BE%D0%B2%D0%B0%D1%8F%20%D1%80%D1%83%D0%B1%D1%80%D0%B8%D0%BA%D0%B0 The id of the model does not change, and the name of the next or previous model instance is appended to the end of the link -
How can I access this email attribute as self if it's a class attribute?
How am I able to print the email as self.email if it's a class attribute? Wouldn't we have to pass it to the parent class via the super function to do that? class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=100, unique=True) # Required fields date_joined = models.DateTimeField(verbose_name="date_joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last_login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email -
Is there an easy way to ignore duplicates with django models unique=TRUE?
class Reddit_Submission(models.Model): submission_id = models.CharField(max_length=32, unique=True) submission_time_stamp = models.CharField(max_length=32) submission_title = models.CharField(max_length=32) submission_score = models.CharField(max_length=32) submission_author = models.CharField(max_length=32) submission_url = models.CharField(max_length=32) I have the above code sample from my Model within my django application. My question is, Is there a easy way to ignore a "Example = model.save()" if something is duplicated within the database already? Thanks -
Django: Is there a Context passed automatically to the templates?
Is there some hidden context that is passed automatically by Django to the templates (without I write it in the views.py or settings.py)? -
How to attach and upload profile image through model in angular
I am using a model to POST data to api , model also has image field.How can i attach image data to coverImage field. Whenever i send post request it return a error that coverImage is not a file. export class NewCourseModel { instructorId:number; title:string; subtitle:string; description:string; language:string; category:string; subcategory:string; price:number; creationDate:Date; coverImage:File; promoVideo:File; } export class CreateCourseComponent implements OnInit { newCourseForm: FormGroup; newCourseModel: NewCourseModel; newSectionModel = new courseSectionModel(); newLectureModel = new courseLectureModel(); newSectionFormArray=[]; formSteps:any = 1; userID; selectedCourseImage: File = null; selectedCourseVideo: File = null; imageUrl = "/assets/images/courses/add_img.jpg"; videoUrl = "/assets/images/courses/add_video.jpg"; imageFileName = "No Image file selected"; videoFileName = "No Video file selected"; courseCategories: courseCategories[]; courseSubCategories: courseSubCategories[]; constructor(private _authService: AuthService, private _courseService: CoursesService) { this.newCourseModel = new NewCourseModel(); // this.courseCategories = new courseCategories(); // this.courseSubCategories = new courseSubCategories(); } ngOnInit(): void { this.InitializeForm(); this.getCourseCategories(); this.newSectionModel = new courseSectionModel(); this.newSectionFormArray.push(this.newSectionModel); } addSection(){ this.newSectionModel = new courseSectionModel(); this.newSectionFormArray.push(this.newSectionModel) } removeSection(index){ this.newSectionFormArray.splice(index); } InitializeForm(): any { this.newCourseForm = new FormGroup({ title: new FormControl('', [Validators.required]), subtitle: new FormControl('',[Validators.required]), description: new FormControl('',[Validators.required]), language: new FormControl('',[Validators.required]), category: new FormControl('',[Validators.required]), subcategory: new FormControl('', [Validators.required]), price: new FormControl('', [Validators.required]), // creationDate: new FormControl('', [Validators.required]), // updatedDate: new FormControl('', [Validators.required]), coverImage: new FormControl('', [Validators.required]), promoVideo: new FormControl('', [Validators.required]), … -
When I log out, I find this error "detail": "Authentication credentials were not provided."
I am using django-rest-knox, when I logout using knox_views.LogoutAllView.as_view(), it gives me this error "detail": "Authentication credentials were not provided." note: I am using a custom user model(AbstarctUser and BaseUserManager) here is serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email','birth_date','first_name','last_name') # there is a registerserializer too class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") and here's views.py class LoginView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user= serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) -
DRF Project Static Files Problem On Server
I'm trying to host the project I prepared on PythonAnywhere. Even though I run the collectstatic command, I can't get any results. When I visit the url, the design does not appear, the same is true for the Admin. When I looked, the requested address is static file instead of static_base. But static_url and static_root should have different names anyway. Do I need to add something related to this field in the urls.py file? Because I haven't seen anything like it when I read it. Settings.py import os from pathlib import Path from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication' ], } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME" : timedelta(minutes = 15) } ALLOWED_HOSTS = ["talhakoylu.pythonanywhere.com"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "rest_framework", "book", "country", "account", "school", "nested_inline", "quiz" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', … -
How to add more fields in django-allauth User model?
I want to add more fields in Django allauth user model. I created a User-Profile model in a one-to-one relation with auth-user and tried to create user-profile object in form.py. But this method is not working. Here is my code: models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) forms.py class CustomSignupForm(SignupForm): profile_picture = forms.ImageField() def signup(self, request, user): profile_picture = self.cleaned_data['profile_picture'] user.save() UserProfile.objects.create(user=user, profile_picture=profile_picture) return user -
DetailView + input button
I would like to add a button to "validate" a user towards the next step of his registration. The staff member have to "validate" the user in the user detail page. So I created a DetailView view with template with all the details of this user. But I would like to know if it is possible to write code in DetailView function to allow the user to increment his step_registration variable when I click on "validate" ? Here is my DetailView function : views.py class StudentDetailView(DetailView, LoginRequiredMixin): model = Student login_url = login student_detail.html {% block content %} <h1>Etudiant: {{ student.user.firstname }} {{ student.user.firstname }}</h1> <ul> {% if student.photo %} <li> Photo :<img src="{{ student.photo.url }}", width = 250, height = 300>"> </li> {% endif %} <li> Etat de l'inscription : {{ student.step_registration }}</li> <li> Date de naissance : {{ student.birthdate }} </li> </ul> <button class="btn btn-secondary"> Validate ! </button> {% endblock %} The step registration variable is called "step_registration", so I want to do student.step_registration += 1 when a staff member click on "validate"