Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form is not valid when I add image area
I trying create a profile update section in web site. This section have a username, email and change image area. Username and email is working but "Image" does not. Only works when I try email and password but when I add the "Image" field and click the update button there is no change My views: @login_required def update_profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('home') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'accounts/update.html', context) Models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics", null=True, blank=True) def __str__(self): return f"{self.user.username} Profile" def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) 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) TEMPLATE: <div class="container my-5"> {% include 'fixed/_alert.html' %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 h2">Update Profile</legend> {{ u_form | crispy }} {{ p_form | crispy }} </fieldset> <div class="form-group"> <input class="btn btn-outline-info btn-block" type="submit" value="Update"> </div> </form> And my signal.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: … -
Python | Django
I'm a complete noob to programming and currently learning python and django. Recently, I created a python application that requires an input (string) from a user in order to provide desired output. It works perfectly however I would like to make it into a django app where I can provide a gui for inputing the string. python app downloads images to a user machine so I am not worried about the displaying of output. I've been following some tutorials on building and adding applications to django and I kind of understand how it works however I am not sure how to tackle adding an existing application and providing a gui or "input" field for the python application which I already built. Any kind of guidance will be appreciated. thanks -
How to limit the number of records in the Serializer
Hello everyone, how to limit the number of results using a serializer? In short, there is a table of comments, which can contain different types of posts. class CourseComment(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) content = models.TextField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and here related table class CourseMessage(models.Model): course_id = models.ForeignKey(Course, on_delete=models.PROTECT) author_id = models.ForeignKey(User, on_delete=models.PROTECT) text = models.TextField() # RAW Format must exclude specials chars before publish is_pinned = models.BooleanField(default=False) comments = GenericRelation('CourseComment') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I made the serializer according to the documentation https://www.django-rest-framework.org/api-guide/relations/ class CourseMessages(serializers.ModelSerializer): user = Author(source='authorid', read_only=True) files = MessageFiles(source='coursemessageattachedfile_set', many=True) message_comments = MessageComments(source='comments', many=True, read_only=True) class Meta: model = CourseMessage fields = ['text', 'updated_at', 'user', 'files', 'message_comments'] class MessageComments(serializers.RelatedField): def to_representation(self, value): ct = ContentType.objects.get_for_model(value) serializer = Comments(value, read_only=True, source='last_comments') return serializer.data class Comments(serializers.ModelSerializer): author = Author(source='user', read_only=True) class Meta: model = CourseComment fields = ['content', 'author'] Everything works well, but I would like to see first 3 comments. Maybe someone has encountered such a problem, or can advise how to do it better. I get this data for the RetrieveAPIView detail page. The first three comments are required for … -
Erro no models Django + SQL server
Oi, pessoal. Estou fazendo uns testes com django e sql server e sempre obtenho esse erro quando preciso usar nos modelos o ForeignKey. Alguém sabe o motivo? Desde já, obrigada. Imagem do Erro Código -
sending message to csgo game coordinator from django
I am using csgo python module to get the skin float value. It works perfectly in terminal. But I am having issue using it with django. I found out that it uses gevent and I dont know much about it. So I thought changing the approach as it was blocking the django server. Now I'm executing django app and csgo gamecoordinator seperately. Approach 1: Using socket for sending and receiving: csgo_gc.py import json import logging import re import socket from csgo.client import CSGOClient from csgo.enums import ECsgoGCMsg from google.protobuf.json_format import MessageToDict from steam.client import SteamClient logging.basicConfig(format='[%(asctime)s] %(levelname)s %(name)s: %(message)s', level=logging.DEBUG) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) username = '###' password = '###' client = SteamClient() client.set_credential_location('D:\\sentry') cs = CSGOClient(client) def get_params(inspect_link): param_pattern = r'^steam://rungame/730/\d{17}/\+csgo_econ_action_preview%20' \ r'(?:S(?P<param_s>.*)|M(?P<param_m>.*))A(?P<param_a>.*)D(?P<param_d>.*)$' res = re.match(param_pattern, inspect_link) if res: res = res.groupdict(default='0') for k, v in res.items(): res[k] = int(v) return res return None @client.on(client.EVENT_AUTH_CODE_REQUIRED) def auth_code_prompt(is_2fa, code_mismatch): if is_2fa: code = input("Enter 2FA Code: ") client.login(username, password, two_factor_code=code) else: code = input("Enter Email Code: ") client.login(username, password, auth_code=code) @client.on('logged_on') def start_csgo(): cs.launch() @cs.on('ready') def gc_ready(): s.bind(('127.0.0.1', 4500)) s.listen(5) while True: print('waiting for a connection') connection, client_address = s.accept() try: print('client connected:', client_address) while True: data = connection.recv(4096) if … -
Django while running the server ModuleNotFoundError: No module named 'project_name'
Error ModuleNotFoundError: No module named 'book_store' book_store is the project name in manage.py the path for settings is os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'book_store.settings') while runnung python manage.py runserver My folder hierarch book_store static templates settings.py urls.py wsgi.py manage.py -
Can not add highest bid to page in Django
I'm making a Django auction website. The problem is that I have no idea how to add highest bid to index page so that it updates every time user places a bid on another page. views.py: def index(request): index = listing.objects.filter(end_auction=False) number=len(index) return render(request, "auctions/index.html", {"list":index, "number":number}) models.py: class listing(models.Model): Title = models.CharField(max_length=50) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) Description = models.CharField(max_length=300) price = models.DecimalField(max_digits=6, null=True, decimal_places=2) image=models.ImageField( blank = True, null = True, upload_to ='') category = models.ForeignKey(category, on_delete=models.CASCADE, related_name="categories") end_auction=models.BooleanField(default=False) def __str__(self): return f"{self.Title}" class bid(models.Model): listing = models.ForeignKey(listing, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) bid = models.DecimalField(max_digits=6, null=True, decimal_places=2) def __str__(self): return f"{self.bid}, {self.listing}, {self.user}" Keep in mind that I didn't include the whole code which is rather long. If you want me to add something just let me know! Answer would be greatly appreciated! :) -
Django how to secure hidden input fields and prevent forms submitting if value changed?
I am rendering few data in hidden input. User can inspect html page and see those hidden input data. He can also change hidden input data which one kind of security risk for my website. Such as I have an hidden input where user email and name rendering like this <input type="hidden" name="name" class="form-control" placeholder="Your Name" value="Jhone" required=""> User can inspect the html and change the value then my forms submitting with new updated value. is there any way to stop submitting forms if value is changed. here is my code: #html hidden input <input type="hidden" name="name" class="form-control" placeholder="Your Name" value="Jhone" required=""> <input type="hidden" name="email" class="form-control" placeholder="Your Name" value="Jhone@gmail.com" required=""> %for y in user_profile%} <input type="hidden" name='userprofile' value="{{y.id}}"> {%endfor%} <input type="hidden" name="parent" id="parent_id" value="95"> The most import fields for me userprofile and parent. I want to prevent forms submitting if any hidden value change. froms.py class CommentFrom(forms.ModelForm): captcha = CaptchaField() class Meta: model = BlogComment fields = ['name','email','comment','parent','sno','blog','user','userprofile'] views.py if request.method == "POST": if comment_form.is_valid(): isinstance = comment_form.save(commit=False) if request.user.is_authenticated: isinstance.user = request.user elif not request.user.is_authenticated: User = get_user_model() isinstance.user = User.objects.get(username='anonymous_user') isinstance.blog = blog isinstance.save() messages.add_message(request, messages.INFO, 'Your Comment Pending for admin approval') return redirect('blog:blog-detail',slug=blog.slug) else: messages.add_message(request, messages.INFO, "your … -
Data from my Django form is not added to my database cause I cannot view it on the webpage
I am trying to build a project management system and have to add client to my database. For this I have created a form as below forms.py class AddClientForm(forms.Form): email = forms.EmailField(label="Email", max_length=50, widget=forms.EmailInput(attrs={"class":"form-control"})) password = forms.CharField(label="Password", max_length=50, widget=forms.PasswordInput(attrs={"class":"form-control"})) first_name = forms.CharField(label="First Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) last_name = forms.CharField(label="Last Name", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) username = forms.CharField(label="Username", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) phone = forms.CharField(label="Phone", max_length=15, widget=forms.TextInput(attrs={"class":"form-control"})) #For Displaying Projects try: projects = Projects.objects.all() project_list = [] for project in projects: single_project = (project.id, project.project_name) project_list.append(single_project) except: project_list = [] #For Displaying Contracts try: contracts = Contracts.objects.all() contract_list = [] for contract in contracts: single_contract = (contract.id, contract.contract_name) contract_list.append(single_contract) except: contract_list = [] project_name = forms.ChoiceField(label="Project", choices=project_list, widget=forms.Select(attrs={"class":"form-control"})) contract_id = forms.ChoiceField(label="Contract", choices=contract_list, widget=forms.Select(attrs={"class":"form-control"})) location = forms.ChoiceField(label="Location", choices=States, widget=forms.Select(attrs={"class":"form-control"})) Then i have created the following views.py def add_client(request): form = AddClientForm() context = { "form": form } return render(request, 'admintemplate/add_client_template.html', context) def add_client_save(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('add_client') else: form = AddClientForm(request.POST, request.FILES) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] phone = form.cleaned_data['phone'] location = form.cleaned_data['location'] project_id = form.cleaned_data['project_name'] contract_id = form.cleaned_data['contract_id'] try: user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=3) user.clients.location = … -
how to push notifications from Django rest framework to react Js
I am developing a booking management application. There I need to push notifications to a specific user based on an action. For example: if a seller gets an order that he/she will be notified in real time. What's the best way to do it. I have read django-fcm , django-channel , django-push-notification,etc. But I couldn't get a proper idea to do it. -
Querying using related field names
I've got two models that I'd like to perform a reverse search on. I'm wondering how to do this given the fact that one model has to fields with foreign keys to the same model. class Review(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None) class Job(models.Model): cart = models.ForeignKey(Cart, related_name="cart_one", on_delete=models.CASCADE, null=True, blank=True) unscheduled_job = models.ForeignKey(Cart, related_name="cart_two", on_delete=models.CASCADE, null=True, blank=True) employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, blank=True) My query is as follows: reviews = Review.objects.filter(cart__job__employee=employee) This query is failing due to the fact that the Job model has two foreign keys that point to the cart model. How would I fix this? Thanks! -
django token not being created when user registers
Serializers.py from rest_framework import serializers from rest_framework.authtoken.models import Token # User Related Serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = models.cUser fields = '__all__' def create(self, validated_data): user = models.cUser.objects.create_user(**validated_data) token = Token.objects.create(user=user) return user models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class cUserManager(BaseUserManager): def create_user(self, email, password, **others): email = self.normalize_email(email) user = self.model(email=email, **others) user.set_password(password) user.save() return user def create_superuser(self, email, password, **others): others.setdefault('is_staff', True) others.setdefault('is_superuser', True) return self.create_user(email, password, **others) class cUser(PermissionsMixin, AbstractBaseUser): email = models.EmailField(unique=True) username = models.CharField(max_length=128, unique=True) password = models.CharField(max_length=256, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = cUserManager() I'm creating a custom user (cUser) with the AbstractBaseUser and want to create a token every time a new user gets created (using the rest framework.authToken module) but it is not working, what can I do? -
Changing static files path to s3 buckt path django
Currently I am getting my static files like this: src="{% static 'website/images/home-slider/plantarte-espacio-4.jpg'%}" And my settings.py look like this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'website/static'), ) Now wat I want is that instead of grabbing the static files from the static foleder inside my app. It goes to my AWS S3 bucket I created and uploaded all the files to Instead of this: src="/static/website/images/home-slider/plantarte-espacio-4.jpg" Do this: src="https://plantarte-assets.s3.us-east-2.amazonaws.com/website/images/home-slider/plantarte-espacio-4.jpg" If someone could please help me I would really apreciate it. -
JavaScript Redundancy Selection Prevention and Delete Button Implementation
I am implementing a page that displays information about the option when I select the option of the product using JavaScript. My source code is attached below. If I select an option, I want to display the option information, price, and product name, and if I press del_li_btn, I want to delete that option information. However, according to my source code, only the price is deleted. What should I do to delete all the information I've posted? Also, I want to implement the option to be selected only once. If you answer my question, I'd really appreciate it. I look forward to your kind cooperation. html <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option data-price="{{value.extra_cost}}"value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> <div id="selectOptionList" style="margin-top:10px; … -
How to use <input type="datetime-local"> with django function based view
I want to make a simple html form with datetime-local input field. Django in the backend to receive and save it to the database. my template: <form method="POST"> {% csrf_token %} <input type="datetime-local" name="startingTime" class="form-control" required> </form> my models.py: class QuestionSet(models.Model): startingTime = models.DateTimeField() In views.py: def index(request): if request.method == 'POST': this_startingTime = request.POST['startingTime'] QuestionSet_obj = QuestionSet.objects.create( startingTime = this_startingTime ) QuestionSet_obj.save() return redirect('app:index') But this gives error. Maybe I need to change the format of this_startingTime . How can I fix this? -
Data is not being retrieve from Django Rest to Flutter App
I am trying to retrieve json data from django api restframework to flutter app but it shows nothing. Even retrieveRecord function in main.dart do not print text when app starts. django returning json code on http://localhost:8000/records/?format=api it also shows json without format on http://localhost:8000/records/?format=json but in flutter list views it shows nothing Main.dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_application_1/ann.dart'; import 'package:http/http.dart' as http; import 'package:http/http.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Test Phase Assignment', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Test Phase Assigment'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { Client client = http.Client(); List<AnnSystem> annSystem = []; @override void initState() { _retrieveRecord(); super.initState(); } _retrieveRecord() async { annSystem = []; List response = json.decode((await client .get(Uri.parse('http://10.0.2.2:8000/records/?format=json'))) .body); response.forEach((element) { annSystem.add(AnnSystem.fromMap(element)); }); print(response); // it does not print on terminal print("function calling"); //it does not print on terminal setState(() {}); } _addRecord() {} @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: … -
Compare different layers using Django and OpenLayers
I'm developing a GIS project with Django and Openlayers. I've created a comparison map that with a slider allow to compare two WMS. Now I would like to do something more tricky because I would to give to the user the possibility to select which WMS to compare. So in my model I've created a ForeignKey that represent a static layer and a ManyToManyField that contain the list of layers to compare with the static layer. I'm be able to create a template that give to the user the possibility to active/deactive a single layer: {% for layer in webgis_single.layers.all %} const source{{ layer.wms_layer_name|cut:"_" }} = wmsMainSource.createWMSLayer( '{{ layer.title }}', '{{ layer.wms_layer_path }}', '{{ layer.wms_layer_name }}', {% if layer.wms_layer_style == None %}null{% endif %}{% if layer.wms_layer_style != None %}'{{ layer.wms_layer_style }}'{% endif %}, {{ layer.set_max_zoom }}, {{ layer.set_min_zoom }}, {{ layer.set_zindex }}, {{ layer.set_opacity }} ); $('#{{ layer.pk }}_{{ layer.wms_layer_name }}').on('change', function() { let isChecked = $(this).is(':checked'); if (isChecked) { mapCanvas.addLayer(source{{ layer.wms_layer_name|cut:"_" }}); } else { mapCanvas.removeLayer(source{{ layer.wms_layer_name|cut:"_" }}); } }); {% endfor %} But I'm locked on the possibility to deactive the active layer when there is a list of activable layers: {% for layer in webgis_single.map_swipe_right.all %} const … -
How can i make a Query through Many-To-Many-Relationship
I want to display the trainer for a course date. A course can have several dates and a different trainer can be used on each date. A trainer can have a different role on each course date. (Instructor, helper...) How do I make the correct query? Are the models correct for this? Models: class Course_dates(models.Model): date = models.DateField() start = models.TimeField() end = models.TimeField() def __str__(self): return str(self.id) """return self.date.strftime("%d.%m.%Y")""" class Course(models.Model): course_number = models.CharField(max_length=24, blank=True) course_location = models.ForeignKey(Course_location, on_delete=models.CASCADE) course_dates = models.ManyToManyField('Course_dates', through="Course_Course_dates") def __str__(self): return self.course_number class Trainer_Course_Course_date_role(models.Model): trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE) role = models.CharField(max_length=24, blank=True) def __str__(self): return str(self.id) class Course_Course_dates(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) course_dates = models.ForeignKey(Course_dates, on_delete=models.CASCADE) trainer = models.ForeignKey(Trainer_Course_Course_date_role, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.id) class Trainer(models.Model): salutation = models.CharField(max_length=8,choices=GENDER_CHOICES) last_names = models.CharField(max_length=56) first_names = models.CharField(max_length=56) date_of_birth = models.DateField() address = models.ForeignKey(Address, on_delete=models.CASCADE) email = models.EmailField() phone = models.CharField(max_length=56, blank=True) mobile = models.CharField(max_length=56, blank=True) def __str__(self): return self.last_names View: def course(request): courses = Course.objects.all() course_list = [] for course in courses: sorted_date_list = course.course_dates.all().order_by('date') course_list.append({'course': course, 'sorted_date_list': sorted_date_list }) context = { 'course_list': course_list, } return render(request, 'kursverwaltung_tenant/course.html', context) -
Cant access a private s3 image however I can upload
I have created an s3 bucket. I have created a user and granted the access AmazonS3FullAccess. The images are uploaded correctly, however the link is not working and I get the following xml error: "The request signature we calculated does not match the signature you provided. Check your key and signing method" I am new to aws and perhaps I am doing something wrong. I want the link to be secure, e.g. with an expiration date. Settings: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'xxxxxx' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'eu-central-1' AWS_S3_SIGNATURE_VERSION = 's3v4' -
Read with pandas once and keep many csv files open or read and close each time
I am doing a project with Django in which I generate several graphs with Plotly and do operations with CSV files that I read, write and modify (also download or delete) with pandas. These files depend on the company to which the user belongs, for example, if it belongs to the TOYOTA company, the file is in data / toyota, and if it belongs to Honda, it is in data / honda. My question is which is better, to read the 50 csvs that will be used when the user logs in, or to read and close the csvs as needed. For example, in my url example.com/analysis, these functions are called: @login_required def analysis(request): data_report = pd.read_csv(f'data/{request.user.company}/test/data_report.csv', sep=';', encoding='utf-8') context = {} for column in data_report.columns: context[column] = data_report.loc[0, column] data_roles = pd.read_csv(f'data/{request.user.company}/test/data_roles.csv', sep=';', encoding='utf-8') # Here more code that doesn't matter ... graphs = [] marker = { 'color': 'rgb(0,150,209)', 'opacity': 0.5, } graphs.append( go.Scatter(x=n_users, y=n_perms, mode='markers', name='Line y1', marker=marker) ) layout = { 'xaxis_title': 'Number of users', 'yaxis_title': 'Number of permissions', 'height': 400, } plot_div = plot({'data': graphs, 'layout': layout}, output_type='div') context['plot_div'] = plot_div return render(request, 'analysis.html', context) @method_decorator(csrf_exempt) def update_pie_chart(request): if request.method == 'POST' and request.is_ajax(): selected … -
Appointment slot from uml to django
I would like to know if my django model are correct according to this class diagram : The diagram : The code : class Student(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) class Staff(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) class AppointmentSlot(models.Model): staff = models.ForeignKey('Staff', null = True, on_delete = models.CASCADE) date = models.DateField(null = True) start = models.TimeField(null=True, blank=True) end = models.TimeField(null=True, blank=True) student = models.ForeignKey('Student', null=True, on_delete=models.CASCADE) Do I have made some errors ? -
Python Why Django won't let me load a new product?
I'm in this page: Filling the details The ling is https://upload.wikimedia.org/wikipedia/commons/c/cb/Oranges_white_background.jpg When I'm pressing 'save' it gives me this: Error message Couldn't understand the issues I tried various ways to solve it like take another picture and re-run the server. From Mosh Hamedi tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=20225s at 05:42:20 -
rest_framework.permissions.IsAuthenticated is never executed
I am trying to only let execute a method to people who has signed in. I am using JSONWebTokenAuthentication This is the implementation: class vistaUsuarios(APIView): permission_classes = (IsAuthenticated,) def usuario(request): print("USUARIO ",request.user.is_authenticated) if request.method == 'GET': usuario = None id = request.GET.get("id") if id is not None: usuario = Usuario.objects.get(pk=id) usuarios_serializer = UsuarioSerializer(usuario) return JsonResponse(usuarios_serializer.data, safe=False) settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), 'NON_FIELD_ERRORS_KEY': 'global', } # JWT settings JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, 'JWT_EXPIRATION_DELTA': timedelta(days=2), } # allauth SITE_ID = 1 ACCOUNT_EMAIL_VERIFICATION = 'none' # JWT settings REST_USE_JWT = True INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'subroutinesbackapp', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth', 'rest_auth.registration' ] ... The problem is that IsAuthenticated is never executed. I have a print there, and never do. class IsAuthenticated(BasePermission): """ Allows access only to authenticated users. """ def has_permission(self, request, view): print("holaaaaaaa") return bool(request.user and request.user.is_authenticated) The method usuario from vistaUsuarios class, always execute. Even though the print print("USUARIO ",request.user.is_authenticated) shows USUARIO false because I haven't passed a valid token. How can I make the IsAuthenticated method execute? Thanks, in advance -
How to get a button in template to change a model? Django
I am trying to build an app with a like-dislike functionality such that by clicking a like button you get added to a string of users that liked and get removed from the dislike string if you were there. How can i do that? I added some of the relevent code: the button: <button type='submit'> Like </button> And the model im trying to change: title = models.CharField(max_length=30) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) auther = models.ForeignKey(User, on_delete=models.CASCADE) views_number = models.IntegerField(default=0) user_like_id = models.CharField(validators=[int_list_validator], max_length = 10000000, default = "") user_dislike_id = models.CharField(validators=[int_list_validator], max_length = 10000000, default = "") -
I am getting Key error message while trying to save my Django form. I am not able to save data from Django form to the database
I am trying to add client to my client model along with the user model using Django forms. But as of now I am getting a key error. I am not able to figure out what is wrong with this and would appreciate some help on this one. My clients model is this class Clients(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) primaryphone = models.CharField(max_length=15, unique=True) location = models.CharField(max_length=30, choices=States) project_id = models.ForeignKey(Projects, on_delete=models.DO_NOTHING, default=1) contract_id = models.ForeignKey(Contracts, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() The view for this are def add_client(request): form = AddClientForm() context = { "form": form } return render(request, 'admintemplate/add_client_template.html', context) def add_client_save(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('add_client') else: form = AddClientForm(request.POST, request.FILES) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] phone = form.cleaned_data['phone'] location = form.cleaned_data['location'] project_id = form.cleaned_data['project_id'] contract_id = form.cleaned_data['contract_id'] try: user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=3) user.clients.location = location user.client.primaryphone = phone project_obj = Projects.objects.get(id=project_id) user.clients.project_id = project_obj contract_obj = Contracts.objects.get(id=contract_id) user.clients.contract_id = contract_obj user.clients.save() messages.success(request, "Client Added Successfully!") return redirect('add_client') except: messages.error(request, "Failed to Add Client!") return redirect('add_client') else: return redirect('add_client') …