Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin, select Supplier and add multiples Product with stackedinline
models.py : class Supplier(models.Model): name = models.CharField(blank=True, max_length=50,) city = models.CharField(blank=True, max_length=50) email = models.CharField(blank=True, max_length=50) class Product(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) description = models.CharField(blank=True, max_length=100) DDT = models.FileField(upload_to="DDT/%Y/%m/%d") fattura = models.FileField(upload_to="DDT/%Y/%m/%d") admin.py class AddProductModelAdmin(admin.StackedInline): model = Product extra = 1 @admin.register(Supplier) class SupplierModelAdmin(admin.ModelAdmin): inlines = [AddProductModelAdmin] model = Supplier @admin.register(Product) class ProductModelAdmin(admin.ModelAdmin): model = Product In this way, (when i add a supplier) i can add a supplier and add multiple products. I would (when i add a product) select a supplier from menù and after add multiple product -
Django filter all assigned foreing keys
Hello I would like to ask how to filter all assigned ForeignKeys of the object. My models looks like: class Person(models.Model): name = models.CharField(max_length=250) class VirtualProject(models.Model): project_name = models.CharField(max_length=250) owner = models.ForeignKey(Person) class Hours(models.Model): hours = models.FloatField() assigned_virtual_project = ForeignKey(VirtualProject) date = models.DateField() I am sending GET request with owner and dateRange parameters and I would like to filter all virtual projects assigned to the owner (this is no issue, I can get this) AND also get all hours objects assigned to the virtual projects and sum all hours in specified date range. How I can do that? For frontend I am using React, so I am using django rest framework. What I got so far in views: class GetDataView(viewsets.ModelViewSet): serializer_class = DataSerializer def get_queryset(self): owner = self.request.query_params.get('owner') dateRange = self.request.query_params.get('dateRange') queryset = VirtualProject.objects.filter(owner=owner) return queryset -
how to display register values in another page in django?
enter image description here I want to display fullname , email and phone number from registration page how can i display this is my code def index(request): if request.method == 'POST': member = Member( fullname=request.POST.get('fullname'), companyname=request.POST.get('companyname'),Email=request.POST.get('email'),password=request.POST.get('password'),contactno=request.POST.get('contactno'),role=request.POST.get('role'),) member.save() context = {'msg': 'Registred successfuclly'} return render(request, 'web/index.html', context) return redirect('/') else: return render(request, 'web/index.html') -
Template doest not exist at /
I am new to Django. I made a folder named templates in my project and "Home.html" inside it, After running the server, I am getting error "TemplateDoesNotExist at /". My Views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post [enter image description here][1] class HomeView(ListView): model = Post template_name = 'Home.html' My Urls.py from django.urls import path,include # from . import views from .views import HomeView urlpatterns = [ # path('', views.IndexView, name='IndexView') path("", HomeView.as_view(), name='home'), ] My Settings.py """ Django settings for icoderblog project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # 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.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '7z!v$&wlvkyu8vwg@m2pv7umaedm+c3$9w%5a3m)ly(=kbp)w_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'theblog' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', … -
searching with choice text in django admin interface
I am extending user model with AbstractUser and added CharField with choices to it. code looks like this Location_choices = ( ('IN', 'India'), ('USA', 'America'), ('O', 'Other Country') ) class User(AbstractUser): location = models.CharField(choices=Location_choices, max_length=3) def __str__(self): return self.username And registered in admin.py like below class AdminUser(admin.ModelAdmin): search_fields = ('username', 'email', 'id', 'location') # Register your models here. admin.site.register(User, AdminUser) The problem is I am able to search with location choices like (IN, USA, O) But I want to search with choice text india or america How do I achieve It. Thanks in advance -
Performance considerations for serializing a related field very often
Suppose I have an API based on the Django Rest Framework. Most Django models used by the application have a reference to the User model (E.g. uploaded_by, updated_by, approvedd_by, etc.). When calling the API to retrieve instances it is often useful to not only know the ID of the user but also the name. However, an ID is often more useful when making comparisons. For example, to check whether a Task was uploaded by you or by another user. I am not sure how to tackle this kind of "pattern" where both the ID and the name representation are useful under different circumstances. I would really appreciate it if someone could explain what would be the best option for performance here. Currently I do the following: TaskSerializer(serializers.ModelSerializer): uploaded_by_name = serializers.StringRelatedField(source='uploaded_by') Meta: model = models.Task fields = '__all__' read_only_fields = ['uploaded_by_name'] While this obviously works, I was wondering whether this is the best solution when considering performance or whether there are other options that I should consider as well. My main concern here is that for almost any call (since all models have user references) the user table must be hit. Another option would be: In my current project, users call … -
How to serialize each foreign key object with different serializer class in django rest framework
So I'm wondering if it is possible to serialize each foreign key object with different serializer in django rest framework. What I mean is: I have my models like class KingdomModel(models.Model): kingdom_name = models.CharField(max_length=32) owner = models.OneToOneField(User, on_delete=models.CASCADE) faction = models.CharField(max_length=10) class CityModel(models.Model): kingdom = models.ForeignKey(KingdomModel, on_delete=models.CASCADE, related_name="cities") city_name = models.CharField(max_length=32) owner = models.ForeignKey(User, on_delete=models.CASCADE) """ ... other fields aswell """ class ArmyModel(models.Model): home_city = models.ForeignKey(CityModel, on_delete=models.CASCADE, null=True, related_name="own_troops") current_city = models.ForeignKey(CityModel, on_delete=models.CASCADE, null=True, related_name="all_troops", blank=True) status = models.CharField(max_length=32) action_done_time = models.DateTimeField(default=None, null=True, blank=True) target_city = models.ForeignKey(CityModel, on_delete=models.CASCADE, null=True, related_name="incoming_troops", default=None, blank=True) # Shared troops settlers = models.IntegerField(default=0) # Gaul troops pikemen = models.IntegerField(default=0) swordmen = models.IntegerField(default=0) riders = models.IntegerField(default=0) # Roman troops legionaries = models.IntegerField(default=0) praetorian = models.IntegerField(default=0) And I am trying to serialize the armies based on the kingdoms faction. Which works fine when talking about own_troops because they are always going to be serialized with the same serializer, like so. class CitySerializer(serializers.ModelSerializer): own_troops = serializers.SerializerMethodField() incoming_troops = serializers.SerializerMethodField() def get_own_troops(self, city_obj): if(KingdomModel.objects.get(owner=city_obj.owner).faction == "Gaul"): return GaulTroopsSerializer(instance=city_obj.own_troops, context=self.context, many=True, required=False, read_only=False).data elif(KingdomModel.objects.get(owner=city_obj.owner).faction == "Roman"): return RomanTroopsSerializer(instance=city_obj.own_troops, context=self.context, many=True, required=False, read_only=False).data class RomanTroopsSerializer(serializers.ModelSerializer): class Meta: model = ArmyModel fields = ['id', 'home_city', 'current_city', 'target_city', 'status', 'action_done_time', 'settlers', 'legionaries', 'praetorian'] … -
I have some sort of weird bug that is affecting the functionality
When I create an add and click the button, it is supposed to take me to the browse ads page, instead it is rendering the contents of browse ads page in the createad url, such that as if there is 2 browse ads page, and when I refresh the page the same post request is processed again and there we go having multiple ads that are the same. views.py: @login_required(login_url='/login') def createAd(request): if request.method == "POST": item = Ad() item.seller = request.user.username item.seller_contact = request.user.phone item.title = request.POST.get('title') item.description = request.POST.get('description') item.starting_price = request.POST.get('starting_price') item.category = request.POST.get('category') item.condition = request.POST.get('condition') try: item.save() except ValueError: return render(request, "auctions/createAd.html", { "message": "Invalid starting price" }) ad = Ad.get_all_ads() # products = Ad.objects.all() empty = False if len(ad) == 0: empty = True return render(request, "auctions/activeAds.html", { "ads": ad, "empty": empty }) #get else: return render(request, "auctions/createAd.html") urls.py: `urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("viewAd/<int:product_id>", views.viewAd, name="viewAd"), path("dashboard", views.dashboard, name="dashboard"), path("activeAds", views.activeAds, name="activeAds"), path("createAd", views.createAd, name="createAd"), path("addtofavorites/<int:product_id>", views.addtofavorites, name="addtofavorites"), path("closebid/<int:product_id>", views.closebid, name="closebid"), ]` html part: <form action="{% url 'createAd' %}" method="POST"> {% csrf_token %} <div class="form-group"> <input class="form-control" autofocus type="text" name="title" placeholder="Title" required> </div> … -
Unable to prevent modal displaying if form is not valid: problem with order sequence with ajax
I have a Django app with a form (id = form_unblind_form) with valid button (id = unblind_edit). I want to display a modal with informations from database using ajax query. And it works but there is an anormal behavior. The problem is that as modal.sow() is called in success ajax return, modal is displayed even if form is not valid and that is not a correct behavior But I can find the right algo to do that thanks for help //1. first form submission is prevented until OK button on modal is clicked $("#form_unblind_edit").submit(function (event) { if (!prevent_edit) { event.preventDefault(); } }); //2. I query database to recovered information for modal $("#unblind_edit").on("click", function (event) { var csrftoken = getCookie('csrftoken'); var patient = $("#id_pat").val(); var treatment = $("#id_unb_num").val(); $.ajax({ type: "POST", url: '/unblind/already_unblind/', data: { csrfmiddlewaretoken: csrftoken, 'patient': patient, 'treatment': treatment }, dataType: 'html', success: function (data) { $("#popup").html(data); $('#unblindconfirm').modal('show'); //<- PROBLEM HERE as modal is always displayed }, }); }); //3. If user click on OK button, form is finally submitted $("body") .on('click', '#edit_button_OK', function (event) { $('#edit_button_OK').attr("disabled", "disabled"); prevent_edit = true; $("#form_unblind_edit").submit(); }) -
how to convert <QuerySet [<Course: BME108_JUL2020>]> to 'BME108' in python?
I use django2 with python3.6 in windows 10. I want to query the sqlite database in Django. when I tried to add condition to the query, I should use the condition passed by the last query. However, the result of the last query is: <QuerySet [<Course: BME108_JUL2020>]>. The condition I need is 'BME108' How could I convert <QuerySet [<Course: BME108_JUL2020>]> to 'BME108'? -
Django Dynamic Form depending on database values
I'm pretty new to Django, and i'm struggling a bit (since 2 days) to make dynamic form depending on database. Here is my model : from django.db import models class DataElement(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class PathElement(models.Model): name = models.CharField(max_length=150) path = models.TextField() data_element = models.ManyToManyField(DataElement) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=150) path = models.TextField() path_element = models.ManyToManyField(PathElement) def __str__(self): return self.name I have a dropdown with Categories, and, when the user select the category, i want the form to have one dropdown per pathelement listing all the dataelement. Thx in advance -
Django OperationalError at new model object
I created a system with Django. My model was working until I added a new field but when I add new field it gives an error. My new field is owner_id OperationalError at /pdfs/ no such column: financial_analysis_pdf.owner_id_id How Can I fix it? models.py class Pdf(models.Model): CHOICES = [ .. ] STAT = [ ... ] id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) pdf = models.FileField(upload_to=user_directory_path) type = models.CharField(max_length=200, default='Select', choices=CHOICES) year = models.CharField(max_length=200, default='Select') created_date = models.DateTimeField(default=datetime.now()) owner_id = models.ForeignKey(Customer, on_delete=models.CASCADE) def __str__(self): return self.title pdfs.html <tbody id="myTable"> {% for pdf in pdfs %} <tr> <td><a href="/ocr" >{{ pdf.title }} </a></td> <td>{{ pdf.year }}</td> <td>{{ pdf.type }}</td> <td> <i class="fas fa-check-circle" style="color: #71ca51"></i></td> <td> <a href="{{ pdf.pdf.url }}" class="btn btn-primary btn-sm" target="_blank">Download</a> </td> <td> <form method="post" action="{% url 'pdf_delete' pdf.pk %}"> {% csrf_token %} <button class="btn btn-danger btn-sm" type="submit" onclick="return confirm('Are you sure you want to delete this analyse?');"><i class="fas fa-trash"></i></button> </form> </td> </tr> {% endfor %} </tbody> </table> views.py def pdf_list(request): pdfs = Pdf.objects.all().order_by('-year') return render(request, 'pdf_list.html', {'pdfs': pdfs}) traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/pdfs/ Django Version: 3.1.4 Python Version: 3.8.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'register', 'customer', 'financial_analysis', 'ocr', 'crispy_forms', 'ckeditor'] Installed Middleware: … -
Django how to pass a name of button to views.py from jquery dialog
how to pass a name of button to views.py from jquery dialog? i want to pass like using jquery dialog to views.py how can i do that? could you help me up? my js in html function addcontinue(){ $('.confirm-continue-message').dialog({ dialogClass:"confirm-modal", modal: true, buttons: { "save and continue": function() { $('#addform').submit().attr("name", "save_add"); }, "cancel": function() { $(this).dialog('close'); }, }, resizeable : false, draggable: false, show: { effect: "fade", duration: 200 }, hide: { effect: "fade", duration: 200 }, focus:"none", }); } my views.py class StudentAdd(FormView): model = Student template_name = 'student/list_add.html' context_object_name = 'student' form_class = AddStudent def post(self, request): form = self.form_class(request.POST, request.FILES) if form.is_valid(): student = form.save(commit=False) student.created_by = request.user student.save() messages.info(request, student.name + ' 학생을 추가하였습니다.', extra_tags='info') if "save_add" in self.request.POST: return HttpResponseRedirect(request.META.get('HTTP_REFERER')) return redirect('student_detail', pk=student.pk, school_year=student.school_year) return FormView.post(self, request) -
How to associate existsing users from django.contrib.auth with Python Social Auth (Google backend)?
I have a Django app with a standard django.contrib.auth backend and have a lot of existing users, now I want to add login via Google account using Python Social Auth. Is there any way to allow login via Google account for existing users? How should I associate it with existing users? -
Getting Django - [Errno 111] Connection refused error
when Im trying to verify user registration via email its showing [Errno 111] Connection refused error in production but works fine in localhost settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'email-smtp.ap-south-1.amazonaws.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'xxx' EMAIL_HOST_PASSWORD = 'xxx' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'xxx' views.py def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your CaringHand Account' message = render_to_string('emails/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, ('Please Confirm your email to complete registration.')) return redirect('login') return render(request, self.template_name, {'form': form}) error ConnectionRefusedError at /members/register/ [Errno 111] Connection refused please help -
Uploaded media to S3 bucket in AWS from django being routed to wrong URL
I am trying to use S3 bucket for media files in a production django project.The files are being uploaded to the bucket successfully but are not being fetched from the right url. Its trying to fetch from the domain rather than the S3 bucket URL. These are the two tutorials I am following: https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/ https://testdriven.io/blog/storing-django-static-and-media-files-on-amazon-s3/ These are my current media settings for production: AWS_STORAGE_BUCKET_NAME = 'XXXXXXXXXXXXXX' AWS_S3_REGION_NAME = 'XXXXXXX' # e.g. us-east-2 AWS_ACCESS_KEY_ID = 'XXXXXXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY = 'XXXXXXXXXXXXXXXXXX' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_STORAGE = 'solvesto.storage_backends.StaticStorage' DEFAULT_FILE_STORAGE = 'solvesto.storage_backends.MediaStorage' STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' STATIC_URL = '/static/' from django.conf import settings class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION file_overwrite = False custom_domain = False class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION The static files work absolutely fine but the media is being routed to the wrong url. -
How to connect flutter Web_socket_channel package with Django Channels?
I want to connect the web_socket_channel package of Flutter with Django channel. My application is perfectly communicating using Django Template and Redis server. I want to use flutter package so that I can use this with flutter application. Django Channel Django API is using the following route: application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter([ path('ws/chat/<str:room_name>/', consumers.ChatConsumer) ]) ), }) JS WebSocket: My Django Template is using the following url path to connect websocket: const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); Flutter: I've tried the following code with flutter to connect to Django Channel but failed. void startSocket() async { final channel = IOWebSocketChannel.connect('ws://$baseUrl/ws/chat/hello/'); channel.stream.listen( (event) { channel.sink.add('Received!'); channel.sink.close(status.goingAway); }, ); } I've seen some other peoples queries on the same topic and add the following permission to the AndroidMenifest.xml <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET"/> but flutter still it show the following errors: E/flutter ( 4901): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: WebSocketChannelException: WebSocketChannelException: SocketException: Failed host lookup: 'http' (OS Error: No address associated with hostname, errno = 7) E/flutter ( 4901): #0 new IOWebSocketChannel._withoutSocket.<anonymous closure> package:web_socket_channel/io.dart:84 E/flutter ( 4901): #1 _invokeErrorHandler (dart:async/async_error.dart:16:24) E/flutter ( 4901): #2 _HandleErrorStream._handleError (dart:async/stream_pipe.dart:282:9) E/flutter ( 4901): #3 _ForwardingStreamSubscription._handleError (dart:async/stream_pipe.dart:161:13) E/flutter ( … -
Google Account without cell Number
I am working on a bot, I want to create Gmail account with my bot but it is asking for the number and no skip option (skip number) is present there. guide me if there any way to do it any kind of help will be appreciated. thanks -
How to create Patient model with AbstractBaseUser, PermissionsMixin?
How to define Custom models more users with permissions? from django.contrib.auth.models import AbstractUser from django.db import models from django.utils import timezone from django.contrib.auth.models import User, UserManager class PatientProfile(User): #id=models.AutoField(primary_key=True) first_name = models.CharField(_('first_name'), max_length=50, blank=True) last_name = models.CharField(_('last_name'), max_length=50, blank=True) mobile = models.CharField(_('mobile'), unique=True, max_length=10, blank=False) email = models.EmailField(_('email address'), blank=True) password = models.CharField(_('password'),max_length=25,blank=False) city=models.CharField(max_length=50) address=models.CharField(max_length=150) state=models.CharField(max_length=50) pincode=models.IntegerField() blood_groups=( ('A+','A+'),('O+','O+'),('B+','B+'), ('AB+', 'AB+'),('A-','A-'),('O-','O-'),('B-','B-'),('AB-','AB-'),) blood_group=models.CharField(max_length=10,choices=blood_groups) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_verified=models.BooleanField(default=False) is_active = models.BooleanField(_('active'), default=False) is_patient = models.BooleanField(_('active'), default=False) otp = models.IntegerField(null=True, blank=True) dob=models.DateField() GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) # objects = MyUserManager() objects = UserManager() USERNAME_FIELD = 'mobile' REQUIRED_FIELDS = [] #I got this errors django.core.exceptions.FieldError: Local field 'password' in class 'PatientProfile' clashes with field of the same name from base class 'User'. -
getting a huge null list on response while trying to upload through DRF
I am getting error while trying to upload files through POSTMAN here is the error and it is 26,000+ long. Although the uploaded files are being uploaded to the directory just fine but the return response is not . Any idea how to solve this? Uploaded media my models.py from django.db import models class Photo(models.Model): image = models.ImageField(upload_to='images/') class Audio(models.Model): audio = models.FileField(upload_to='audios/') class Video(models.Model): video = models.FileField(upload_to='videos/') my serializers.py from rest_framework import serializers from .models import Photo, Audio from rest_framework import status from rest_framework.response import Response class ImageListSerializer(serializers.Serializer): image = serializers.ListField( child=serializers.FileField(max_length=100, allow_empty_file=False, use_url=True)) def create(self, validated_data): image=validated_data.pop('image') for img in image: photo=Photo.objects.create(image=img) print(photo) return photo class Meta: model = Photo fields = ('pk', 'image') class AudioListSerializer(serializers.Serializer): audio = serializers.ListField( child=serializers.FileField(max_length=100, allow_empty_file=False, use_url=True)) def create(self, validated_data): audio=validated_data.pop('audio') for aud in audio: sound=Audio.objects.create(audio=aud,**validated_data) print (sound) return sound class Meta: model = Audio fields = ('pk', 'audio') my views.py from django.shortcuts import render from rest_framework import viewsets, mixins, status from rest_framework.settings import api_settings from .models import Photo, Audio from .serializers import ImageListSerializer, AudioListSerializer from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response class PhotoViewSet(viewsets.ModelViewSet): serializer_class = ImageListSerializer parser_classes = (MultiPartParser, FormParser,) queryset = Photo.objects.all() class AudioViewSet(viewsets.ModelViewSet): serializer_class = AudioListSerializer parser_classes = … -
how can I build screen sharing an application with controlling, voice functionalities using python and webRTC [closed]
I want build screen sharing an application from the scratch. Which I need to include other functionalities like remote controlling and audio and video calling(like zoom app) using python with help of webRTC in Django framework. This is my task in this I have some restriction need not use Node JS, React JS and other libraries. -
Login redirecting to specific page based on specific group in template
I have two admin groups in django-admin[staff, student]. I want that whenever a user wants to log in, the program first checks that to which group the user belongs, then redirect each one to a particular page. index.html <form method="post" action="{% url 'users:login' %}" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name="submit" class="btn btn-primary mt-2">Log in</button> {% endbuttons %} <input type="hidden" name="next" value="{% url 'student_paper:index' %}" /> </form> -
error when query django database: ValueError: The annotation 'code' conflicts with a field on the model
I use Django2 and sqlite in windows 10 for a course management website. when I tried to query the database in view.py using query_results_3 = CourseInfo.objects.values('title', code=course_code[:5]) error occurs: ValueError: The annotation 'code' conflicts with a field on the model. model.py: class CourseInfo(TimeStampedModel): # school or center code = models.CharField(max_length=20, unique=True, db_index=True) title = models.CharField(max_length=200) school = models.ForeignKey(School, on_delete=models.SET_NULL, blank=True, null=True) postgraduate = models.BooleanField(default=False) # indicate Postgraduate course discipline = models.ForeignKey(Discipline, on_delete=models.SET_NULL, blank=True, null=True) # should not be null pattern = models.CharField(max_length=120, choices=PRESENTATION_PATTERN, blank=True, null=True, help_text="Presentation Pattern") type = models.CharField(max_length=2, choices=(('PT', 'Part-Time'), ('FT', 'Full-Time'), ('OL', 'Online'))) available = models.BooleanField(default=True) # mean Active or Retired semesters = models.ManyToManyField('Semester', through="Course") # auto have semestercourse_set def __str__(self): return "{} - {}".format(self.code, self.title) class Meta: constraints = [models.UniqueConstraint(fields=['code', 'type'], condition=models.Q(available=True), name='unique_course_type')] ordering = ['code', ] How to change my code to let the error disapear? -
How to keep Django site on? [closed]
I created my Django website and it is working fine, but when i close my command prompt the site stops working how do get rid of this problem? -
How to pass file's content as CharField in django model?
I have a model for icon, which looks like this: class Icon(models.Model): name = models.CharField(max_length=50) icon = models.FileField(upload_to='icons/', blank=True, null=True) inline_svg = models.CharField(max_length=1000, blank=True) Most of files are .svg and I want to pass into inline_svg content of corresponding file to use inline svg on front-end. How can i do that? Or maybe there is any better variants to do what I want? Also had an idea of something like this: class Icon(models.Model): def svg(self): f = open(self.icon.url) return f.read() name = models.CharField(max_length=50) icon = models.FileField(upload_to='icons/', blank=True, null=True) inline_svg = models.CharField(max_length=1000, default=svg())