Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store automatically csv file to oracle database in django without model?
I want to store data in csv files in an oracle database without going through the model or defining the fields to store because the fields vary from one csv to another any help please ?? -
Is there a way to debug Django urls?
I have a problem with Django urls that I cannot get to the bottom of. I have tried the recommendations given in the answers to this question, but they don't help. <project>/urls.py urlpatterns = [ ... path('duo/', include('duo.urls')), path('users/', include('users.urls')), ] duo/urls.py urlpatterns = [ ... path('', include('users.urls')), ... ] users/urls.py urlpatterns = [ path('', views.SelectPartner.as_view(), name='select-partner'), ... ] when I use the url http://192.168.1.138:8000/duo/ I get taken to the page http://192.168.1.138:8000/accounts/login/?next=/duo/ which does not exist. I cannot think what is going on here because the word accounts does not exist anywhere in the project Is there some tool that I can use to find out what is happening? -
py command not working but python command is working in cmd
I have python version 3.8.0 and the .exe is added to the path but I am trying to create a django project and need to use py -m venv command to create a virtual environment but it says py is not recognized as an internal or external command, operable program or batch file. -
Deployed Django App Not Working On Ubuntu NGinx/Gunicorn
When following this tutorial (https://rahmonov.me/posts/run-a-django-app-with-gunicorn-in-ubuntu-16-04/), everything worked for a basic website. This at least proves the firewall rules are working as expected. However, when deploying my Django web app, I'm simply receiving the message: "This site can't be reached." I've checked the Nginx error and access logs, and they don't contain anything since the 13th August when I last looked into this issue, and when the website repeatedly gave me errors about missing modules that have since been installed. Is there anywhere else I can check to see why the Django app now isn't loading via the web page? Just for peace of mind, below are all my config details. /etc/nginx/sites-available/terraformdeploy: server { listen 8000; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /opt/envs/terraformdeploy; } location / { include proxy_params; proxy_pass http://unix:/opt/envs/terraformdeploy/terraformdeploy.sock; } } I've run: sudo ln -s /etc/nginx/sites-available/terraformdeploy /etc/nginx/sites-enabled sudo nginx -t returns: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful service nginx status returns: nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Drop-In: /etc/systemd/system/nginx.service.d └─override.conf Active: active (running) since Thu 2020-08-13 15:44:44 … -
How to remove pre-populated extra forms from django admin inlines
for example, suppose I have these two models: class Comment(models.Model): content = models.TextField() post = models.ForeignKey('Post', on_delete=models.CASCADE) class Post(models.Model): content = models.TextField() and I have set Comment as Inline for Post admin, like: class CommentInline(admin.StackedInline): model = Comment extra = 3 @admin.register(Post) class PostAdmin(admin.ModelAdmin): inlines = [CommentInline] Now, I want to set initial values into the extra 3 forms of comment inlines. and I have accomplished that by CommentInline's get_formset method like: def get_formset(self, request, obj=None, **kwargs): # this list will be generated dynamically initial = [ {"content": "dynamic data 1"}, {"content": "dynamic data 2"}, {"content": "dynamic data 3"} ] formset = super().get_formset(request, obj, **kwargs) formset.__init__ = curry(formset.__init__, initial=initial) # from django.utils.functional import curry return formset now inline forms are populating by dynamic data as expected. but the problem is there are no buttons for removing the form. I can add new comments, edit initial comment, but I can't delete any comment from those pre-populated comments! my questions are: How can I remove extra inline form before saving into DB? Is my approach is ok for populating initial values? -
How do I create a Blog mdel in django2.1, So that I don't need to use tags <p>,<h3>,<b> and all, Each time write blog I have to add html tags
I have to add html tags each time when I added the blog to my website. I don't then it do not consider line change,heading and other things. Model code class Blog(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog') updated_on = models.DateTimeField(auto_now= True) body = models.CharField(max_length=150) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) def __str__(self): return self.title Admin Panel Html tag includedadmin view Published blogPublished blog Without use of html tagsadmin panel. Published blog blog published Plz let me know I it don't make sense. -
How to update your django page by looking for new data in the db?
I try to create a dashboard using django and chart.js. My modul looks like: class Sets(models.Model): time = models.DateTimeField(default=timezone.now) set1 = models.IntegerField() set2 = models.IntegerField() set3 = models.IntegerField() my views: from .function_sum import get_sets from .models import Sets def home(request, *args, **kwargs): sets = Sets.objects.all() time = [] set1 = [] set2 = [] set3 = [] time, set1, set2, set3= get_sets() data = { "sets" : sets, "time": time, "set1": set1, "set2": set2, "set3": set3 } return render(request, "pages/home.html", data) class ChartData(APIView): authentication_classes = [] permission_classes = [] sets = Sets.objects.all() time = [] set1 = [] set2 = [] set3 = [] time, set1 , set2 , set3 = get_sets() def get(self, request, format=None): data = { "time": self.time, "set1": self.set1, "set2": self.set2, "set3": self.set3 } return Response(data) get_sets is getting the current data from my Set datatable. my html file which is included in layout page: <div class="col-xl-6" url-endpoint='{% url "chart-data" %}'> <div class="card mb-5"> <div class="card-header"><i class="fas fa-chart-line mr-1"></i>Chart</div> <div class="card-body"><canvas id="SetChart" width="100%" height="40"></canvas></div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.min.js" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script> <script> var endpoint ='chart/data' var labels = [] var set1 = [] var set2 = [] var set3 = [] $.ajax({ … -
Django admin opening directly
I'm facing an issue when i'm hitting http://127.0.0.1:8000/admin/ it's not asking for login, admin page gets open directly. I've only one user i.e "root", i restarted my browser, cache/cookies clean, system restart but noting working out. I want whenever i hit http://127.0.0.1:8000/admin/ for first time in fresh browser session it should ask for login. Any idea why this is happening? -
How to fetch particular column from database using ajax in django
Here is my views.py def contact(request): number= listing_model.objects.only('phone') data=serializers.serialize('json', number) return JsonResponse( data, safe=False ) I am getting output "[{"model": "listings.listing_model", "pk": 2, "fields": {"title": "PG1", "address": "XYZ", "city": "Hyderabad", "state": "Telangana", "price": 4000, "pincode": 789654, "sqfoot": 300, "rooms": 3, "image": "images/th_SHFuSrw.jpg", "phone": 456789123}}, {"model": "listings.listing_model", "pk": 3, "fields": {"title": "PG2", "address": "DEF", "city": "TVM", "state": "KERELA", "price": 6000, "pincode": 456963, "sqfoot": 300, "rooms": 1, "image": "images/th.jpg", "phone": 123456789}}]" I don't want all these fields I just want to display phone field. Please help me. Thanks in advance. -
How to validate data with custom key fields with a serializer in django?
The format of the data looks somthing like this { "data": { "example1": { "priority": 10 }, "example2": { "priority": 10 } } } Here example1 and example 2 are the variable key names and the number of such keys and their names changes with depending on the request. Thanks in advance. -
Setting time field in django such that the stored time cannot be changed later
I have a orders model which looks like this: class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) date_ordered=models.DateTimeField(auto_now=True) complete=models.BooleanField(default=False,null=True,blank=False) and this is a specific view from my views.py: def handlerequest(request, id): order=Order.objects.get(id=id) items=order.orderitem_set.all() verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) PaytmHistory.objects.create(**response_dict) if verify: if response_dict['RESPCODE'] == '01': order.transaction_id=transaction_id order.complete=True order.save() print('order successful') Now what is happening is that whenever this is view is called the order is saved and the time updates to when the order was saved. But in future when I manually make some changes to the fields like when I update the shipping status of the order and save it then the time updates which I dont want . So is there any fix to this such that after order.complete=True order.save() The time cannot be changed -
Do I need to write the full media path in Django?
I am trying to download a file that is stored in the media folder and it seems as it only works when I am writing the full path as: file_location = '/home/user/user.pythonanywhere.com/media/' In the settings page on pythonanywhere, the 'media url' points to the same directory. So I don't really understand why I just can't write /media/ instead for the full path. Has it something to do with my settings.py file? I have these lines there: MEDIA_ROOT= os.path.join(BASE_DIR, 'media') MEDIA_URL="/media/" Do I need to have these lines at all? -
Django Rest Framework: Get Data by Field
i want to learn django. My first learning project is a django + rest framework api. i want to get a destination by its airport code. not by pk / id currently when i call /api/destination/1 i get the destination with id 1 i want something like /api/destination/PMI or /api/destination/mallorca and as response i only want to get the destination with code PMI or with name mallorca. is this possible? my files: modely.py class Destination(models.Model): name = models.CharField(max_length=50) code = models.CharField(max_length=3) country = models.CharField(max_length=50) image = models.FileField() serializers.py class DestinationSerializer(serializers.ModelSerializer): class Meta: model = Destination fields = ("id", "name", "code", "country", "image") urls.py router = DefaultRouter() router.register(r'destination', DestinationViewSet) views.py class DestinationViewSet(viewsets.ModelViewSet): serializer_class = DestinationSerializer queryset = Destination.objects.all() -
How can I pass the text which I clicked on href link from one age to another page in JS and that should be usable in django code?
This is the code written in Django. When I click the link on the displayed results of links, the text,link of href (for example Redmi Note 5 rendered in {{post.0}} in the below code)should be saved and pass that text{{pass.0}} and link{{pass.1}} to another page to get the same text and it is used as the title. How can I do it? Page1.html {% for post in product_names %} <a href="{{ post.1 }}" onclick="savefunc({{post.1}},{{post.0}})">{{ post.0 }}</p> {% endfor %} Page2.html <h1 id="h1_title"style="text-align:center;background:linear-gradient(to right,rgb(166, 204, 255),rgb(15, 242, 216));margin-left:2%;margin-right:2%;box-shadow:1px 5px 5px 1px rgb(90,150,100,210);padding:30px;font-weight:bold;">[ Here I want to get that text from page1.html ]</h2> Suggestions in both JS or in Django is accepted. Please help me. -
Category not linking with posts Django
I want to let users choose the category that they want to put their post in, I already have the dropdown menu with all the options available but is not letting me post them, is telling me to insert a list of values, I have a feeling is has something to do with the databases because in my UserPost I dont have the category part. And this is my code: models.py class Categories(models.Model): name = models.CharField(max_length=100, verbose_name='Nombre') def __str__(self): return self.name User= settings.AUTH_USER_MODEL class UserPost(models.Model): user= models.ForeignKey(User, null=False, editable=False, verbose_name='Usuario', on_delete=models.CASCADE) title= models.CharField(max_length=500, null=False) content= models.TextField(null=False) categories = models.ManyToManyField('Categories', null=True, blank=True) public = models.BooleanField(verbose_name='Privada?',default=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name='Creado el ') updated_at = models.DateTimeField(auto_now=True, verbose_name='Actualizado el ') def __str__(self): return self.title + ' | ' + str(self.author) def save(self, *args, **kwargs): super(UserPost, self).save(*args, **kwargs) forms.py from django import forms from .models import UserPost, Categories #cats=[('coding','coding')] choices= Categories.objects.all().values_list('name','name') choice_list= [] for item in choices: choice_list.append(item) class UserPostForm(forms.ModelForm): class Meta: model= UserPost fields= ["title", "content","categories","public"] widgets={ 'categories':forms.Select(choices=choice_list) } views.py #list view @login_required(login_url='login') def userposts_list_view(request): allposts= UserPost.objects.all() context= {'allposts': allposts, } return render(request, 'posts/userposts-list-view.html', context) #detail view @login_required(login_url='login') def userposts_detail_view(request, id=None): post= get_object_or_404(UserPost, id=id) context= {'post': post, } return render(request, 'posts/userposts-detail-view.html', context) #all post … -
TypeError: method() takes 1 positional argument but 2 were given if i did register api
cant do work my register_api if i have view class RegistrationUsersApi(viewsets.ModelViewSet): permission_classes = [AllowAny] def get(self, request): queryset = User.objects.all() serializer = UserSerializerView(queryset, many=True) return Response(serializer.data) def post(self, request): serializer_class = SerializerUserRegistration(data=request.data) data={} if serializer_class.is_valid(): new_user = serializer_class.save() data['response'] = 'Ура ты создал нового персонажа, героя, человека, или не создал?' data['email'] = new_user.email data['username'] = new_user.username else: serializer_class.errors return Response(data) and i have my serilizer class SerializerUserRegistration(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['username', 'email', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True} } def save(self): user = User( email=self.validated_data['email'], username=self.validated_data['username'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Password must match'}) user.set_password(password) user.save() return user and my usermodel class User(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") description = models.TextField(blank=True, null=True) location = models.CharField(max_length=30, blank=True) date_joined = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) is_organizer = models.BooleanField(default=False) info_car = models.CharField(max_length=30, blank=True, null=True) first_name = models.CharField(max_length=30, blank=True, null=True) second_name = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return self.user.username urls urlpatterns = [ path('', views.MainIndexView.as_view(), name='index'), path('registration/', views.RegistrationUsersApi, name='registration') and my root urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainapp.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path("api/accounts/", include("mainapp.urls")), ] why my register doesnt work. i was … -
Django prefetch_related not printing anything in Template
I have three models: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=130, unique=True) full_name = models.CharField(_('full name'), max_length=130, blank=True) is_staff = models.BooleanField(_('is_staff'), default=False) is_active = models.BooleanField(_('is_active'), default=True) date_joined = models.DateField(_("date_joined"), default=date.today) phone_number_verified = models.BooleanField(default=False) change_pw = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True) country_code = models.IntegerField(default='+91') two_factor_auth = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['full_name', 'phone_number', 'country_code'] class Meta: ordering = ('username',) verbose_name = _('user') verbose_name_plural = _('users') def get_short_name(self): """ Returns the display name. If full name is present then return full name as display name else return username. """ if self.full_name != '': return self.full_name else: return self.username class student_group(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) schoolCode = models.ForeignKey(school, on_delete=models.CASCADE) classVal = models.ForeignKey(studentclass, on_delete=models.CASCADE) SECTION_CHOICES = ( ("A", 'Section -A'),("B", 'Section -B'),("C", 'Section -C'),("D", 'Section -D'),) class_section = models.CharField(max_length=2,choices=SECTION_CHOICES,default="A") class studentclass(models.Model): class_id= models.CharField(primary_key=True,max_length=5) classVal =models.CharField(max_length=255, null=True, blank=True) views.py def addStudent(request): student = User.objects.filter(user_type=1) addStudentlink = True schoolval = user_school.objects.filter(username=request.user.id).values_list('schoolCode',flat=True)[0] studentclasses = studentclass.objects.all().prefetch_related('student_group_set__username') print(studentclasses) return render(request, 'dashboard/add-student.html', {'studentclasses': 'studentclasses'}) The print(studentclasses) returns <QuerySet [<studentclass: Class V>, <studentclass: Class VI>, <studentclass: Class VIII>, <studentclass: Class IX>, <studentclass: Class XII>, <studentclass: Class X>, <studentclass: Class XI>, <studentclass: Class VII>]> How should I print this in my template. How should I access my fields. I … -
i am getting error while while "zappa init'
i have installed zappa in virtual envirment and created aws account also but when i am try to command "zappa init" its showing error below (.env) D:\rough work\crud>zappa init Traceback (most recent call last): File "c:\users\dwipal shrirao\appdata\local\programs\python\python38\Lib\runpy.py", line 192, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\dwipal shrirao\appdata\local\programs\python\python38\Lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "D:\rough work\crud\.env\Scripts\zappa.exe\__main__.py", line 4, in <module> File "d:\rough work\crud\.env\lib\site-packages\zappa\cli.py", line 44, in <module> from .core import Zappa, logger, API_GATEWAY_REGIONS File "d:\rough work\crud\.env\lib\site-packages\zappa\core.py", line 33, in <module> import troposphere File "d:\rough work\crud\.env\lib\site-packages\troposphere\__init__.py", line 586, in <module> class Template(object): File "d:\rough work\crud\.env\lib\site-packages\troposphere\__init__.py", line 588, in Template 'AWSTemplateFormatVersion': (basestring, False), NameError: name 'basestring' is not defined -
The view didn't return an HttpResponse object. It returned None instead by using numpy-stl
I have a Django web application and I'm trying to make an ajax call for uploading 3D images such as .stl, .stp, etc for getting their volume info with pythonocc-core package. When the file size is less than 1 MB, I run it with a normal ajax request, when it is large, I run it as a background-task so that the process avoid timeout. my ajax request; var data = new FormData(); var img = $('#id_Volume')[0].files[0]; var img_size = (img.size / 1048576).toFixed(2); data.append('img', img); data.append('csrfmiddlewaretoken', '{{ csrf_token }}'); if (img_size <= 1){ $.ajax({ method: 'POST', url: '{% url 'data:smallUpload' %}', type: 'POST', contentType: false, processData: false, data: data, }).done(function(data) { $("#id_rectangleRemovedVolume").val(data['removed_volume']); $("#id_rectangleVolume").val(data['volume']); loader.style.display = 'none'; $("#id_Volume").val(''); }).fail(function(xhr, text, error) { console.log(text, error) }); } else { $.ajax({ method: 'POST', url: '{% url 'data:upload' %}', type: 'POST', contentType: false, processData: false, data: data, }).done(function(data) { window.location.href = "{% url 'data:uploadStatus' %}"; }).fail(function(xhr, text, error) { console.log(text, error) }); } my smallUpload view; def uploadSmallFile(request): if request.POST or None: file = request.FILES.get('img') filename = file.name key = 'media/' + filename s3_resource = boto3.resource('s3') bucket = s3_resource.Bucket('bucket') bucket.put_object(Key=key, Body=file) if filename != '': volume, removed_volume = Methods.get_volume_info(key) #do something context = {'volume': volume, … -
Pillow does not install in docker container
I have a Django app that uses Pillow. I get ERRORS: accounts.UserProfile.avatar: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". SystemCheckError: System check identified some issues: when I deploy it to aws-ec2 in a docker container. Things I've tried I have installed Pillow normally in virtual environment and frozen it to requirements.txt I downgraded and upgraded the version of Pillow I copied the dependencies from here into my Dockerfile. Following this issue I added the ENV LDFLAGS=-L/usr/lib/x86_64-linux-gnu/ to my container None of these seem to fix issue. Here's a sample of my Dockerfile Dockerfile FROM python:3.6-slim # create the appropriate directories ENV APP_HOME=/paalup_web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/static RUN mkdir $APP_HOME/mediafiles WORKDIR $APP_HOME ENV PYTHONUNBUFFERED=1 # Add unstable repo to allow us to access latest GDAL builds # Existing binutils causes a dependency conflict, correct version will be installed when GDAL gets intalled RUN echo deb http://deb.debian.org/debian testing main contrib non-free >> /etc/apt/sources.list && \ apt-get update && \ apt-get remove -y binutils && \ apt-get autoremove -y # Install GDAL dependencies RUN apt-get install -y libgdal-dev g++ --no-install-recommends && \ pip install pipenv && … -
I cant use postgresql for my new django project even though I wrote as other stack overflow answer said
I try to make the web app using postgresql. I wrote the setting and checked stackoverflow. I wrote the setting below and still get errors when i try to run the server locally. How can i fix this issue? The message is "django.db.utils.OperationalError: fe_sendauth: no password supplied" settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': "blog", "USER": os.environ.get("DB_USER"), } } -
Django Static URL loading but by adding double slashes "http://127.0.0.1:8000//static/"
I am developing a web application for the last 2 weeks. Everything was working fine. Today when I started the server to continue. The static files were not loaded and were giving a 404 error. Static Files were loading on this URL before the ERROR http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.2.1.min.js Now Static Files are loading by appending extra slash "/" after base URL. http://127.0.0.1:8000//static/assets/plugins/jquery/jquery-3.2.1.min.js Please Help! """ Django settings for phm project. Generated by 'django-admin startproject' using Django 3.1. 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 # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '$$ttyfq=l6%3x44ooo8pi6s=c))ef5zk__u%2ox6n8qwv*0@1s' # 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', #third party apps 'crispy_forms', 'debug_toolbar', #local apps 'phm', 'arrival_and_departure', ] 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', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] ROOT_URLCONF = 'phm.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates/'], … -
Django Filter in View or HTML
I am working on a basic assignments project where the teachers can add assignments and the students can submit the answers. I have saved it with models Assignments and Submissions as shown in the code below. The thing I am trying to do is that I want to show different buttons with different links when a parent has submitted the assignments. To be exact I want to show "Add submission" if a parent has not submitted and "Update Submission" when he/she has submitted already to a particular assignment. The problem I am having is that when a parent submits to a certain assignment then other parents also see "Update Assignment" if I give some filtering on the querysets. How can this be handled? Is there something we can do in html or some other filtering in views.py? Or I have to change by style of doing this. Please your support will be a great help. My models: class Assignments(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) title = models.CharField(max_length=500) description = models.TextField(blank=True, null=True) file = models.FileField(upload_to='assignments/', null=True, blank=True, verbose_name="File") date_posted = models.DateTimeField(default=timezone.now) deadline = models.DateTimeField(null=True, blank=True) def save(self, *args, **kwargs): super(Assignments, self).save(*args, **kwargs) class Meta: ordering = ['-date_posted'] def __str__(self): return (self.title … -
Changing the choices of the model in the serializer
please I need your help, I have choices in the model and make model Serializer from this model but need to modify on those choices as i use filterset in the Serializer so i need to add more options in the dropdown menu, here is the code. Serializer.py: class BlaListSerializer(serializers.ModelSerializer): STATUS_new1='new1' STATUS_new1='new2' STATUS_FOLLOWED = 'followed' STATUS_CREATED = 'created' STATUS_CHOICES = ( (STATUS_new1, _('New1')), (STATUS_new2, _('New2')), (STATUS_FOLLOWED, _('Followed')), (STATUS_CREATED, _('Created')), ) status = serializers.ChoiceField(choices=STATUS_CHOICES) class Meta: model = Bla fields = ( "id", "title", "status", ) model.py: class Bla(ProjectBaseModel, AuditLogMixin): STATUS_FOLLOWED = 'followed' STATUS_CREATED = 'created' STATUS_CHOICES = ( (STATUS_FOLLOWED, _('Followed')), (STATUS_CREATED, _('Created')), ) title = models.CharField(max_length=200, blank=True, null=True, verbose_name=_('Title')) status = models.CharField(max_length=200, blank=False, null=True, choices=STATUS_CHOICES) view.py: class MyBla(ListAPIView): serializer_class = BlaListSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['status', ] my problem is that the status isn't updated with the new options in the DRF -
Django traceback errors
I am a beginner in python, pycharm and Linux, I want to open an existing Django project. But when I use "python manage.py runserver", I am getting a series of trace-back errors which I am attaching below. I have installed all the LAMP stack i.e., Linux OS, Apache2 Web server,MariaDB and MYSQLclient with latest versions and have also tried updating the versions in requirements.txt. However, I haven't installed PhpMyAdmin yet, for time basis I would want to just use terminal for viewing my data tables. Could you please explain me about the tracebacks and what can I do to run the program. It would be of great support if you can provide me with a solution. Thank you. Keep safe and kind regards, SD. Django_Pycharm_traceback_1 Django_Pycharm_traceback_2