Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can i print the instance of has_object_permission?
I'm trying to create REST API with django-rest-framework. My question is can I print the instance of has_object_permission method so I can see what is going on in that part. I'm trying that only the owner of an object can update and delete the object but right now anyone can delete or update anybody object. Please tell if there is other way to do besides permissions. Can we do all these with checks in serializer. If yes then please guide me that too with example. I shall be very thankful. class ObjectOwnerPermission(BasePermission): message = "This object is expired." # custom error message def has_object_permission(self, request, view, obj): if request.user.is_authenticated: return True return False if obj.author == request.user: return True return False class RetrieveUpdateProjectAPIView(generics.RetrieveUpdateAPIView,ObjectOwnerPermission): """This endpoint allows for updating a specific Project by passing in the id of the Project to update/Retrieve""" permissions_classes = [ObjectOwnerPermission] queryset = Project.objects.all() serializer_class = serializers.ProjectSerializer class DeleteProjectAPIView(generics.DestroyAPIView,ObjectOwnerPermission): """This endpoint allows for deletion of a specific Project from the database""" permissions_classes = [ObjectOwnerPermission] queryset = Project.objects.all() serializer_class = serializers.ProjectSerializer -
Question regarding Django - IIS - Postgres
I've recently built my first real web app for 'work' using Django. I'm using Postgres for my backend database. I'm also hosting my app and database on the same Windows 2019 server. IIS is the tool that I'm using to host my web app. Essentially what my issue is when I have my website live in production, my export count in the csv doesn't match my filtered records count in my search. It works sometimes but usually when the row count is smaller. The issue usually happens if the row count is in the tens of thousands (shown in screenshot). My hunch is that it's due to some network setting somewhere in IIS but i could be wrong. Everything works perfectly when I'm just running on localhost. I'm not too familiar on what database or IIS settings should be set to allow for optimal performance. I have 16 GB of ram on my server and a 8 core processor so i don't think that's the issue but i could be wrong. My database is like 8 million some rows so there is definitely a lot of data to go through. Below is code of my export_to_csv view as well. I'm … -
Django: Unique_Together
My Django form allows teachers to choose which period they would like to request a student, "Academic Period 1" or "Academic Period 2" or "Both Periods". I currently have a unique_together option working perfectly for "Academic Period 1" and "Academic Period 2" where a duplicate request is not allowed, but how do I make the option named "Both Periods" block future submissions requesting periods "Academic Period 1" and "Academic Period 2"? See my code below. In the model, these choices are options for the field "Period". MODEL class RequestAStudent(models.Model): PERIODS=( ('Academic Network 1', 'Academic Networking 1'), ('Academic Network 2', 'Academic Networking 2'), ('Both Periods', 'Both Periods'), ) MARK=( ('None', 'None'), ('Present', 'Present'), ('Tardy', 'Tardy'), ('X', 'X'), ('Absent', 'Absent'), ) student = models.ForeignKey(Student, on_delete= models.CASCADE) date_created = models.DateField(auto_now_add=True, null=True) Requesting_Teacher = models.ForeignKey(AdvisoryTeacher, on_delete= models.CASCADE) Period = models.CharField(max_length=18, null=True, choices = PERIODS) teacher = models.ForeignKey(Teacher, verbose_name='Advisory Teacher',default="None", on_delete= models.CASCADE) date_requested = models.CharField(max_length=200, verbose_name='Date for Student Request (Use format MMDDYY)', default="2021-11-04",null=True) attendance = models.CharField(verbose_name='UPDATE ATTENDANCE HERE!',max_length=18, default="None",choices = MARK) #null=True, blank=True, owner = models.IntegerField("Request Owner", blank=False, default=1) def __str__(self): return "" + str(self.student) + ", Teacher: " + str(self.owner) class Meta: unique_together = ["student", "Period", "date_requested"] -
What is the exact name of the table in database in django admin?
Which one among the following is the name that belongs to my database table? Tbl_categories tbl_categorie tbl_categories TBL_Categorie This is my class in models.py: class tbl_Categorie(models.Model): category_id = models.AutoField(primary_key=True) category_name =models.CharField(max_length=14) def __str__(self): return self.category_name This is the screenshot from my django admin: -
Python - Single thread executor already being used, would deadlock
I'm trying to create an async view that accesses the DB and returns data with two separate queries. @sync_to_async def get_tweets(request): return (Tweet.objects. annotate(full_text=Concat(F('title'), F('body'))). order_by(F('date').desc(nulls_last=True)). values('full_text', 'title', 'body', 'date', tweet_id=F('uuid'), sent_to_app=F('sent'))) @sync_to_async def get_users(request): return User.objects.filter(is_active=True).values('username', 'email', full_name=Concat(F('first_name'), F('last_name'))) @sync_to_async @csrf_exempt @async_to_sync async def async_view(request): funcs = [get_tweets, get_users] tasks = [asyncio.ensure_future(func(request)) for func in funcs] data = await asyncio.wait(tasks, return_when=FIRST_EXCEPTION) return JsonResponse({'data': data}, safe=False) when debugging the code, before the response, I get an exception for every task in tasks: RuntimeError('Single thread executor already being used, would deadlock') so I can't collect the results, I don't understand why it's happening except it originated in asgiref. I downgraded the asgiref version like said here: django RuntimeError at /admin/users/user/1/change/, Single thread executor already being used, would deadlock but it didn't help. I don't understand if it comes from something in the way I set up the async code or from exception that's being raised in one of the functions and is hidden in the traceback. -
Django adding an user as a model
im trying to make a "seller" in my "Products" model. The seller should be the user who made the product (the user who is logged in currently). How can i take the current user and use it like a foreign key but without choices? Products model: from django.db import models import uuid from user.models import User class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False) name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False) name = models.CharField(max_length=255, blank=True, null=True) image = models.ImageField(upload_to='images', blank=True, null=True) price = models.FloatField(max_length=255, blank=True, null=True) description = models.TextField(max_length=255, blank=True, null=True) category = models.ManyToManyField(Category, blank=True) seller = models.ForeignKey(User) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name User model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, Group, Permission import uuid from user.managers import UserManager class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(max_length=255, unique=True) image = models.ImageField(upload_to='images', blank=True, null=True) date_of_birth = models.DateField(null=True, blank=True) about = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) groups = models.ManyToManyField(Group, blank=True) permissions = models.ManyToManyField(Permission, blank=True) USERNAME_FIELD = 'email' … -
Django, Nginx, uWSGI sock - Internal Server Error
I created the Django project and the .ini file for uWSGI (/home/luca/uwsgi/siti/project.ini): [uwsgi] home = /home/luca/progetto/venv chdir = /home/luca/progetto/progetto wsgi-file = /home/luca/progetto/progetto/progetto/wsgi.py socket = /home/luca/uwsgi/progetto.sock vacuum = true chown-socket = luca:www-data chmod-socket = 660 If I issue the command: uwsgi /home/luca/uwsgi/siti/project.ini It work fine. To make uWSGI start automatically on boot I used systemd (/etc/systemd/system/uwsgi.service): [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown luca:www-data /run/uwsgi' ExecStart=/usr/local/bin/uwsgi --emperor /home/luca/uwsgi/siti Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target I created the configuration file for my website (/etc/nginx/sites-available/progetto): server { listen 8000; server_name [IPdelVPS]; location / { include uwsgi_params; uwsgi_pass unix:/home/luca/uwsgi/progetto.sock; } } and sudo ln -s /etc/nginx/sites-available/progetto /etc/nginx/sites-enabled I use this configuration for other websites and it works, but in this case it responds: Internal Server Error Thanks in advance to anyone who can help me. -
Is there any point in defining models.Index or models.UniqueConstraint in class Meta of a Django Model, if managed = False
I'm trying to configure Django models with a legacy database. After running inspectdb I've started going through the recommended basic clean up steps (ie rearrange models' order, make sure each model has a primary key, foreign keys 'on delete', etc.). I've decided to keep managed = False in class Meta in each model to avoid migration issues with legacy app that it may cause. In addition to the basic cleanup steps I'm wondering if it's recommended or necessary at all to add models.Index and models.UniqueConstraints to class Meta for my tables that already have these indexes and constraints defined in the database. Are these specific (class Meta) settings only needed for migrations or does Django use them to enforce constraints and for indexing at the app level in addition to what my database server (mysql 5.7) already is designed to do? -
request.session['pk'] = user.pk AttributeError: 'QuerySet' object has no attribute 'pk'
I need to get a user for account_verify to compare the input verification code with the correct login code, but I got this error also I want to show user phone number in account verify I used context for that but I think that is wrong view def account_register(request): if request.user.is_authenticated: return redirect("store:home") if request.method == "POST": registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): username = registerForm.cleaned_data["user_name"] phone_number = registerForm.cleaned_data["phone_number"] password = registerForm.cleaned_data["password"] user = User.object.filter(phone_number=phone_number) if not user.exists(): new_user = User(phone_number=phone_number) new_user.username = username new_user.phone_number = phone_number new_user.set_password(password) new_user.is_active = False new_user.save() else: return HttpResponse("this phone number already taken", status=400) request.session['pk'] = user.pk return redirect("account:account_verify") else: registerForm = RegistrationForm() return render(request, "account/authentication.html", {"form": registerForm}) def account_verify(request): form = CodeForm(request.POST or None) print(form) pk = request.session.get('pk') print(pk) if pk: user = User.object.get(pk=pk) code = user.code user_phone_number = user.phone_number code_user = f"{user.code}" if not request.POST: print(code_user) send_sms(code_user, user.phone_number) if form.is_valid(): num = form.cleaned_data.get('number') if str(code) == num: user.is_active = True user.save() login(request, user) return redirect("store:home") else: return redirect("account:register") context = { 'form': form, 'user_phone_number': user_phone_number } return render(request, "account/verify.html", context) error File "C:\Users\_rickoutis_\djx\Rex_acs32\account\views.py", line 49, in account_register request.session['pk'] = user.pk AttributeError: 'QuerySet' object has no attribute 'pk' -
Hosting Django web application on IIS error
My organization has implemented a web application in Django, and we need to host it on a Windows system. We are using Django 3.2.8 and Python 3.8.8. The Django project is currently stored here: C:\inetpub\wwwroot\CED_HRAP <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="\*" verb="*" modules="FastCGIModule" scriptProcessor="c:\python38\python.exe|c:\python38\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> <defaultDocument> <files> <clear /> <add value="Default.htm" /> <add value="Default.asp" /> <add value="index.htm" /> <add value="index.html" /> <add value="iisstart.htm" /> <add value="base.html" /> </files> </defaultDocument> <directoryBrowse enabled="false" /> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\CED_HRAP" /> <add key="WSGI_HANDLER" value="CED_HRAP.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="CED_HRAP.settings" /> </appSettings> </configuration> Our settings.py file is located at C:\inetpub\wwwroot\CED_HRAP\CED_HRAP\settings.py We are currently seeing this error message: HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory. Most likely causes: A default document is not configured for the requested URL, and directory browsing is not enabled on the server. How should we configure the default documents in the web.config file so that it links to Django's internal routing (urls.py)? Thanks. -
Python PasswordGenerator how can I code it
I'm trying to make a password generator on which you can select the length and if you want to have digits, characters or special characters inside. I'm struggeling with the code because I dont know how I can let the program choose 1 character out of every list for each length loop This is my code now alphabets = list(string.ascii_letters) digits = list(string.digits) special_characters = list("!@#$%^&*()") a_d = list(alphabets, digits) a_s = list(alphabets, special_characters) d_s = list(digits, special_characters) characters = list(string.ascii_letters + string.digits + "!@#$%^&*()") random.shuffle(characters) length = int(request.GET.get('length')) alphabets_b = bool(request.GET.get('alphabets')) digits_b = bool(request.GET.get('digits')) special_characters_b = bool(request.GET.get('special_characters')) password = [] for i in range(length): if alphabets_b == True: if digits_b == True: password.append(random.choice(a_d)) elif special_characters_b == True: password.append(random.choice(a_s)) elif digits_b == True: if special_characters_b == True: password.append(random.choice(d_s)) elif special_characters_b == True: if digits_b == True: password.append(random.choice(d_s)) I know this is really bad coding, how can I impove the code that it works. With this code the program says that I cant put 3 other lists in 1 list which makes sense but I cant think of a better way to seperate the characters. In my template I have this code: <form method="get" action="{% url 'home:passwordgenerator' %}"> <div class="fake_input"> <p … -
Django 403 error after installing a pip package with my static file server
So I have a Django website that needs to use both a pip package that introduces new static files to the admin and also a static file server from Linode (it's technically equivalent to AWS S3 buckets from everything that I've seen only cheaper for my use cases). This is the pip package, it basically adds a widget on the admin side of the Django website so that admin users can enter certain fields from a model in rich text as opposed to plain text. https://github.com/django-ckeditor/django-ckeditor And this is what I think is the relevant source code to my settings.py: import os from pathlib import Path import environ env = environ.Env() # reading .env file environ.Env.read_env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'ckeditor', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'products.apps.ProductsConfig', # ... ] CRISPY_TEMPLATE_PACK = 'bootstrap4' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, "live-static-files", "static-root") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] … -
Django migration revert: will the operations be reverted in reverse order?
I have three operations in my migration file. The first operation needs to happen first for the other 2 operations to run without issues. My understanding is that the operations will happen in order, but what if I wanna revert the migrations? Are the 3 operations reverted in reverse order, i.e., the RunPython will be reverted last? operations = [ migrations.RunPython(migrate_forward, reverse_code=migrate_backward), migrations.AlterField(...), migrations.AddField(...), ] -
How to do a join on more than two tables with Django?
I have been able to figure out how to join 2 tables with the below statement which worked perfectly for me, how I can't figure out how to do it with 3 tables. For 2 Tables trailers = TrailerLocation.objects.all().values('trailer__trailerNumber', 'trailer__trailerPlateNumber', 'trailer__trailerPlateState', 'trailer__trailerLeaseCompany', 'locationCity', 'locationState', 'locationCountry','statusCode', 'trailer__id') Now for the 3 models I want to do a join statement on, are below. Shipment class Shipment(models.Model): CARRIER_CHOICES = [ ('GW', 'Greatwide'), ('BL', 'Brian Williams'), ] dateTendered = models.DateField() loadNumber = models.CharField(max_length=50) masterBolNumber = models.CharField(max_length=50) carrier = models.CharField(max_length=100, blank=True, choices=CARRIER_CHOICES) destinationCity = models.CharField(max_length=70) destinationState = models.CharField(max_length=50) rateLineHaul = models.DecimalField(max_digits=15, decimal_places=2) rateFSC = models.DecimalField(max_digits=15, decimal_places=2) rateExtras = models.DecimalField(max_digits=15, decimal_places=2, default=0.00) rateTotal = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) loadDelivered = models.BooleanField(default=False) customCarrierRate = models.BooleanField(default=False) trailer = models.ForeignKey(Trailer, on_delete=models.PROTECT, blank=True, null=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) CarrierRate class CarrierRate(models.Model): shipment = models.OneToOneField(Shipment, on_delete=models.PROTECT, primary_key=True) rateLineHaulCarrier = models.DecimalField(max_digits=15, decimal_places=2, null=True, default=0.00) rateFSCCarrier = models.DecimalField(max_digits=15, decimal_places=2, null=True, default=0.00) rateExtrasCarrier = models.DecimalField(max_digits=15, decimal_places=2, null=True, default=0.00) rateTotalCarrier = models.DecimalField(max_digits=15, decimal_places=2, null=True, default=0.00) Shipment Margin class ShipmentMargin(models.Model): shipment = models.OneToOneField(Shipment, on_delete=models.PROTECT, primary_key=True) shipmentMargin = models.DecimalField(max_digits=15, decimal_places=2, null=True) shipmentMarginPercentage = models.DecimalField(max_digits=15, decimal_places=3, null=True) I am needing access to all fields in all 3 of the models so my eventual jinga code would … -
why wagtail TableBlock don't displed at admin panels
I have this code, want to make TableBlock at my admin panel, make migrations, migrate but it not displayed at admin panel from wagtail.contrib.table_block.blocks import TableBlock from wagtail.core.blocks import StreamBlock from wagtail.core.fields import StreamField class BaseStreamBlock(StreamBlock): table = TableBlock() class ArticlePage(Page): parent_page_types = ['home.HomePage'] subpage_types = [] content = StreamField(BaseStreamBlock(), verbose_name=_('Content'), blank=True) content_panels = [ MultiFieldPanel([ FieldPanel('title'), ]), MultiFieldPanel( [ StreamFieldPanel('content'), ] ), ] -
Detecting proxy or VPN user in Django
I want to be showing if the user request is using a VPN proxy or not in Django. I want if a user is using a VPN it shows this "Network Error: Not Connected" and if a user is not on VPN it shows this "Network Active: Connected". I have tried looking for the answers on the internet but nothing is working. Here is my views.py code: from django.shortcuts import render from django.views.generic.base import TemplateView from django.http import HttpResponse, JsonResponse import os import platform def check_ping(): hostname = "xyz.com" #hostname will be..Name under: "Connection-specific DNS Suffix" when you type "ipconfig" in cmd.. response = os.system("ping " + ("-n 1 " if platform.system().lower()=="windows" else "-c 1 ") + hostname) # and then check the response... if response == 0: pingstatus = "Network Active: Connected" else: pingstatus = "Network Error: Not Connected" return pingstatus response = check_ping() #print(response) # Create your views here. def home(request): return JsonResponse({'status':response}) -
Django and DRF-DataTables - Fixing Filtering Behavior
I am using DRF-DataTables to create a browsable table on the client side. The model I am working with contains some nullable boolean fields like so: models.py class Record(...): name = models.CharField(..., blank=True, null=True) is_active = models.BooleanField(blank=True, null=True) The table is rendered with serverside=true, however there is some unwanted behavior when trying to filter on the is_active column: filtering with "True" or "true" correctly retrieves only the records where is_active=True filtering with "False" (or any iteration where the 'F' is capitalized) correctly retrieves the records where is_active=False filtering with "false" incorrectly retrieves all records (but "fals" pulls the records where is_active=False) Furthermore - there does not seem to be anyway to filter for the records where is_active=None or name=None An idea solution would be to override the filtering logic by writing my own FilterSet, however when trying to follow the docs I run into this error: views.py class RecordGlobalFilter(...): name = GlobalCharFilter(lookup_expr='icontains') class Meta: model = Record fields = '__all__' class RecordViewSet(...): ... filter_backends = [DatatablesFilterBackend] filterset_class = RecordFilter The error: AttributeError: type object 'RecordFilter' has no attribute '_meta' -
How to require a specific field gets passed a value when saving Django model
I’m trying to track which user last updated an object: Class MyModel(models.Models): updater_id = models.ForeignKey(Users) …other fields… However, I can’t figure out how to require that updater_id be included each time my object is saved. First I tried overriding save: def save(self, updater_id, *args, **kwargs): self.updater_id = updater_id super(MyModel, self).save(*args, **kwargs) I realized however that this will break anything native to Django (i.e. MyModel.objects.create()) Next I tried grabbing it from kwargs: def save(self, *args, **kwargs): try: self.updater_id = kwargs[“update_fields”][“updater_id”] catch exception: raise Error super(MyModel, self).save(*args, **kwargs) updated_fields, however is only rarely used (i.e. default behavior for object.save() is to not use updated_fields) Then I tried adding a flag: Class MyModel(models.Models): updater_id = models.ForeignKey(Users) updater_updated_flag = models.BooleanField(default=True, editable=False) # default=True so first create/save works def update_updater_id(self, user_id): self.updater_id = user_id self.updater_updated_flag = True def save(self, *args, **kwargs): if self.updater_updated_flag: self.updater_updated_flag = False else: raise Exception("Must call update_updater_id() before calling save on this object") super(MyModel, self).save(*args, **kwargs) I figured I would ensure the updater_id is updated before save can be called. I realized, however, that this will break create_or_update(), unless I want to wrap it in a try catch and, if the object exists, get the object and call update_updater_id, which already … -
'Media' object has no attribute 'render_q'
screenshothow to fix "'Media' object has no attribute 'render_q'" appears when editing the model in the admin panel -
Update only that property not all model, django
@property def policy_escape(self): if self.date - datetime.date.today: self.status = 2 self.save() def save(self, *args, **kwargs): self.counter = counter + 1 I have this logic for policies. For every policy created I want to increase a property nnumber(this is not exact my case). I want when policy date is today date to change the status of that policy. But when I change it, the policy counter is increasing. Can someone help me to update only status without updating other properties? Thanks in advance -
Django/OpenResty validate JWT
at my Django REST application, the user receives a JWT after providing his login credentials to the API. Now I have second service, the user can download files from. In front of this second service, there should be an OpenResty proxy to validate the JWT my Django application generates after login for the user. How can I make OpenResty validate the JWT to allow a user access to the second service? My intention here is to implement kinda SSO using the JWT my Django application generates Thanks in advance -
How to filter on a foreign key that is grouped?
Model: from django.db import models class Person(models.Model): name = models.CharField(max_length=100) class Result(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) outcome = models.IntegerField() time = models.DateTimeField() Sql: select * from person as p inner join ( select person_id, max(time) as max_time, outcome from result group by person_id ) r on p.id = r.person_id where r.result in (2, 3) I'm wanting to get the all person records where the last result outcome was either a 2 or 3. I added the raw sql above to further explain. I looked at using a subquery to filter person records that have a matching result id sub_query = Result.objects.values("person_id").annotate(max_time=Max("time")) however using values strips out the other fields. Ideally I'd be able to do this in one person queryset but I don't think that is the case. -
Django: composite primary key doesn't work
The Django seems to completely ignore my use of unique_together constraint given to it and instead it treates one field as a primary key, but not the composition of two fields. In my postgres db everything works fine, but not in Django. I tried this and that, even overriding ModelForm's save method to create object manually, nothing helps. Seems like I have to create some fake id field in this table to make Django think that this is the primary key, which is not convinient. Advices needed. -
How to display data in a table from a database for a search for a Foreign Key in the same page using Ajax in a Django project?
I am quite new to programming and I have been trying to resolve this issue from the past two days and couldn't wrap my head around on how to implement it to my requirement. (It would be helpful if you could explain what you are doing with the commands in your solution.) I have a PostgreSQL database that I have imported to Django models. My models from the database. Students objects from Student table have total marks assigned to them in the ExamMarks table through two Foreign Keys( 1. Student_ID and the other Classroom_ID I want to display the rank list of a classroom in descending order of the top 5 students with respect to their total marks in the 'total' column of the ExamMarks. I want to display it on the same page as the search page of my website. I had used to redirect it to another page to display the results but I want it to display on the same page using Ajax. The below pictures show how I did it previously using another page. Image shows my search page My HTML search page file My HTML file. Here I am displaying only the top 5 Students … -
Why is my side navigation bar overlapping the text on the web pages
So I am using django to create a website but there must be a problem in my CSS and or HTML code, when I run the server the text on the pages is being covered by the sidenav bar I have. I previously had a width set for the sidenav but removed it but that didn't work either, here is the code: <html> <head> <style type="text/css"> .sidenav { height: 100%; position: fixed; z-index: 1; top: 0; left: 0; background-color: #111; overflow-x: hidden; padding-top: 20px; } .sidenav a { padding: 6px 8px 6px 16px; text-decoration: none; font-size: 25px; color: #818181; display: block; } .sidenav a:hover{ color: #f1f1f1; } .main{ margin-left: 160px; padding: 0px 10px; } </style> <title>{% block title %} My Website {% endblock %}</title> </head> <body> <div class="sidenav"> <a href="/home">Home</a> <a href="/create">Create</a> <a href="/6">View</a> </div> <div id="content", name="content"></div> {% block content %} {% endblock %} </body> </html>