Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
create multiple objects at the same time
I have this view that creates a form with groups and exercises. How can I do to be able to create more groups and exercises in the template? views.py @login_required def creaScheda(request): if request.method == "POST": form = CreaSchedaForm(request.POST) if form.is_valid(): schedaName = form.cleaned_data['nome_scheda'] scheda = form.save(commit = False) scheda.utente = request.user scheda.save() gruppi = DatiGruppi( giorni_settimana = form.cleaned_data['giorni_settimana'], dati_gruppo = form.cleaned_data['dati_gruppo'], gruppi_scheda = Schede.objects.get(nome_scheda = schedaName) ) gruppi.save() esercizi = DatiEsercizi( serie = form.cleaned_data['serie'], ripetizione = form.cleaned_data['ripetizione'], peso = form.cleaned_data['peso'], gruppo_single = DatiGruppi.objects.get(gruppi_scheda = scheda.id), dati_esercizio = form.cleaned_data['dati_esercizio'] ) esercizi.save() return redirect('/backoffice') else: form = CreaSchedaForm() context = {"form": form} return render(request, "crea_scheda.html", context) -
How to create nested dictionary from two related models in Django?
I want to create dictionary format like ; { "2021": [ { "name": "John Doe", "date": "01.01.2021", "items": "item1" } ], "2020": [ { "name": "Jane Doe", "date": None, "items": "item2" }, { "name": "Jack Doe", "date": None, "items": "item3" } ], "2019": [ { "Name": "James Doe", "date": None, "items": ["item1", "item2", "item3", "item4"] }, ] } ] I have two models; class Persons(models.Model): name= models.CharField(max_length=200) date= models.DateTimeField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class PersonItems(models.Model): person= models.ForeignKey(Persons, on_delete=models.CASCADE, related_name='urls') items= models.URLField() created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now_add=True) I should get data from these models. I am very confused and I can not do it properly. The code I've tried; data = [{ (persons.date).strftime('%Y'): [{ "name": per.name, "date": (per.date).strftime('%m/%d/%Y'), "items": per.urls.filter(person=per) } for per in Persons.objects.filter(date__year=(person.date).strftime('%Y'))] } for person in Persons.objects.all().order_by('-date') ] But I can not group by year in outer dictionary. Thanks in advance! -
How to run custom validation code on each Django REST endpoint?
I am new to using Django so I would like to come up to speed as fast as possible. Right now I'm figuring out a way to run custom code before any API calls are executed, so as to validate the parameters being sent. I'm building a blockchain application, and I don't necessarily trust the address being sent by the frontend. Therefore, I want to run some custom code to check the parameters being sent against a signed version of them, just to make sure that they are indeed being sent by the owner of a specific blockchain address (since no one else would have the private keys). Let's say I'm planning to have this function: def validateArgs(signature, kwargs): # hashes the kwargs in a tightly packed manner, use ecrecover to validate signer's address And I want every API endpoint to call this first before executing any code. Or better yet, have some sort of session token being generated by Django once at the start, and then authenticate using that. Is there a clean way to do this in Django? Thank you! -
Angular frontend not getting data from Django backend on Docker container
I have an app which uses Angular(with Nginx), Django and MySQL. Each of these are containerized separately on AWS Ubuntu instance. I have been able to connect from Django container to Mysql container and do migrations for Django. Neither the login page is getting populated with data, nor I am able to login using credentails stored in the database. Without docker, everthing works fine though if I install it on an ubuntu system. These are the Dockerfiles and docker-compose.yml for your reference. Dockerfile for frontend: # stage 1 -- download node image and build the frontend image FROM node:12 as node WORKDIR /app COPY frontend/package.json ./ RUN npm install -g @angular/cli RUN npm install COPY frontend/. . RUN ng build # stage 2 FROM nginx:alpine COPY --from=node /app/dist /usr/share/nginx/html COPY frontend/nginx.conf /etc/nginx/conf.d/default.conf Dockerfile for backend: FROM python:3.8 # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /web COPY backend/requirement.txt ./ # copy project COPY backend/. . RUN apt-get update RUN apt-get --assume-yes install gcc RUN apt-get install -y default-libmysqlclient-dev RUN pip3 install -r requirement.txt docker-compose.yml version: "3.9" services: db: image: mysql:5.7.21 restart: always command: --default-authentication-plugin=mysql_native_password ports: - "3306:3306" environment: - MYSQL_DATABASE=database - MYSQL_USER=root - MYSQL_PASSWORD=root - MYSQL_ROOT_PASSWORD=root volumes: … -
Django class base, forms.py, show diffrent forms dependent on if you are creating or updating
I have a forms.py that show a dropdown when creating. But I would like it to be a hidden field when updating. Is it possible to make forms.py show 2 diffrent views depending on you are creating or updating? asset = forms.ModelChoiceField(required=False, queryset=Asset.objects.filter(Q(is_loaned=False) & Q(may_be_loaned=True)), label="Asset", widget=forms.Select(attrs={'class': 'form-control'})) forms.py class Loan_assetForm(forms.ModelForm): loaner_name = forms.CharField(label="", max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Loaner name'})) location = forms.ModelChoiceField(queryset=Locations.objects.all(), label="Asset loaned form", widget=forms.Select(attrs={'class': 'form-control'})) loaner_address = forms.CharField(label="", max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Loaners address'})) loaner_telephone_number = forms.CharField(label="", max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Loaner telephone number'})) loaner_email = forms.EmailField(label="", max_length=100, widget=forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'Loaners email'})) loaner_quicklink = forms.URLField(label="", max_length=100, required=False, widget=forms.URLInput( attrs={'class': 'form-control', 'placeholder': 'Quicklink'})) loaner_type = forms.ModelChoiceField(queryset=Loaner_type.objects.all(), label="Loaner type", widget=forms.Select(attrs={'class': 'form-control'})) asset = forms.ModelChoiceField(required=False, queryset=Asset.objects.filter(Q(is_loaned=False) & Q(may_be_loaned=True)), label="Asset", widget=forms.Select(attrs={'class': 'form-control'})) loan_date = forms.DateField(required=False, label="Loan date", widget=forms.widgets.DateTimeInput(format=('%Y-%m-%d'), attrs={'class': 'form-control', "type": "date"})) return_date = forms.DateField(required=False, label="Return Date", widget=forms.widgets.DateTimeInput(format=('%Y-%m-%d'), attrs={'class': 'form-control', "type": "date"})) returned = forms.BooleanField(label="Has asset benn returned", initial=False, required=False) notes = forms.CharField(required=False, label="Note", max_length=448, widget=TinyMCE(attrs={'cols': 80, 'rows':50,'class': 'form-control'})) class Meta: model = models.Loan_asset fields = [ "loaner_name", "location", "loaner_address", "loaner_quicklink", "loaner_telephone_number", "loaner_email", "loaner_type", "asset", "loan_date", "return_date", "returned", "notes", ] -
change SQL query to Django
I have a web app, backend using Django. I want to change the following SQL query to Django ORM command: SELECT distinct t.id, t.title as Textbook, GROUP_CONCAT(concat(ci.discipline_code, ci.code, " (" , ci.type , ")") SEPARATOR ', ') as CourseCode FROM TMS_UAT.bms_material m, TMS_UAT.bms_title t, TMS_UAT.bms_course c, TMS_UAT.bms_courseinfo ci where t.id = m.book_id and c.id = m.course_id and ci.id = c.id and isbn != 'NA' GROUP BY t.id; How to change the SQL to Django command? -
How to update fields of related model in one query using Django ORM or SQL?
I want to update model fields and fields of related model in one query in Django: Link.objects.filter(alpha=True).update( alpha=False, target__backup_of_original_start=F('target__original_start'), target__backup_of_original_end=F('target__original_end'), target__original_start=F('target__start'), target__original_end=F('target__end'), ) In this question I see that it is impossible using update. Is it possible to overcome this restriction using Django ORM or at least plain SQL? And how? -
Django Postgresql test database issue
I am pretty new to django and have an issue with the db. I tried to test a few things and got the following error: Creating test database for alias 'default'... .... RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. warnings.warn( Got an error creating the test database: permission denied to create database I also have pg4admin connected to it. Do you have any idea how to resolve this? Thanks in advance -
Django _Categorize products
I want to show specific categories of items on a single page. Each category has a subheading and specific categories in the group. Whenever i run the enve, everything is good but each subcategories output all the products, even the ones in other categories. How can i rectify this. def waterProducts(request): category = request.POST.get('category') if category == None: products = Product.objects.order_by('-price').filter(is_published=True) else: products = Product.objects.filter(categoryname=category) categories = Category.objects.all() context = { 'products': products, 'categories': categories } return render(request, "products/WaterProductPage.html", context) Above is my view.py files where i confirm if there is any category. <main style="background-image: url(images/waterrocks.jfif)"> <section class="body-section"> <div class="all-products"> <!--Water coolers--> {%for category in categories%} <section class="main-products cooler"> <div class="upper-bar"> <div> <h2>{{category.name}}</h2> </div> <div class="sortby"> <span>Sort By: <select class="sort"> <option value="highest">Highest Price</option> <option value="lowest">Lowest Price</option> </select></span> </div> </div> <hr /> <!--Single Products-wrap--> <div class="specific-product-wrap specific-product-wrap-cooler"> {%if products%} {%for product in products%} <a href="{%url 'product' product.pk%}"> <div class="specific-single-product"> <div class="product-image center"> <img class="product-image-shape" src="{{product.image.url}}" alt="adamol Distilled" /> </div> <div class="produc-descriptions"> <h4 class="specific-product-title">{{product.title}}</h4> <p class="one-line-description"></p> <p class="price">Ksh.{{product.price}}</p> <button type="button" class="AddToCart">Add To Cart</button> </div> </div>` </a> {%endfor%} {%else%} <p>No Product Lol</p> {%endif%} </div> </section> {%endfor%} The above is my html template where i output each category with related product. class Category(models.Model): name … -
why do I get error 500 when I fetch javascript?
I have a Django project and I want to update the model using the javascript fetch method put to update the value from true => false and vice versa. however, I get error 500 inbox.js:63 PUT http://127.0.0.1:8000/add-like/14 500 (Internal Server Error) and I cant figure out why. Ps. I am a beginner. views.py : @csrf_exempt @login_required def Like_post(request, id): if request.method == 'PUT': user = User.objects.get(username=request.user) post_id = post.objects.get(pk=id) if post_likes.objects.filter(like_user = user , liked_post=post_id): remove = post_likes.objects.get(like_user=user, liked_post=post_id).delete() remove.save() else : add = post_likes.objects.create(like_user=user, liked_post=post_id) add.save() all_likes_on_a_post = post_likes.liked_post.all().count() return JsonResponse({'like_count': all_likes_on_a_post, "message": "successfull.", "status": 201}) else: like_post = post.objects.filter(pk=id) array = [one.serialize() for one in like_post] return JsonResponse(array, safe=False) js file: fetch(`load_posts`) .then(response => response.json()) .then(page_obj => { // Print emails console.log(page_obj); page_obj.forEach(Post => show_post(Post)); }); function show_post(Post){ let postsWrapper = document.createElement('div'); postsWrapper.className = "post-wrapper"; let postHeader = document.createElement('div'); postHeader.className = "post-header" let creator = document.createElement('p') creator.innerHTML = `@${Post.creator}` creator.style.display = "inline" let pubdate = document.createElement('p') pubdate.innerHTML = Post.pub_date pubdate.style.display = "inline" pubdate.style.marginLeft = "40px" postHeader.append(creator) postHeader.append(pubdate) postsWrapper.append(postHeader) let postContent = document.createElement('div'); postContent.className = "post-content" postContent.innerHTML = Post.content postContent.style.marginTop = "20px" postsWrapper.append(postContent) let postFooter = document.createElement('div'); let likeButton = document.createElement('i') if (Post.is_liked == true) { likeButton.className = "fas … -
To output <p>tags using template tags
How can I use the template tag to create a "p-tag only for products that do not have product_code in the option table"? {% for option in option_object %} {{option.product_code}} {% if option.product_code == None %}} <p> hello </p> {% endif %} {% endfor %} I wrote it this way, but it doesn't work. Other than the above, we have tried the same way as {% if not product.product_code == option.product_code %} but it has not been resolved. How can you only "print p tags on products without options"? Models.py class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() detail = models.TextField() target_price = models.IntegerField() start_date = models.DateField() due_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['product_code'] index_together = [['product_code', 'slug']] def __str__(self): return self.name def get_absolute_url(self): return reverse('zeronine:product_detail', args=[self.product_code, self.slug]) class Option(models.Model): option_code = models.AutoField(primary_key=True) name = models.CharField(max_length=32) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') def __str__(self): return self.name class Meta: ordering = ['option_code'] class Value(models.Model): value_code = models.AutoField(primary_key=True) option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code', null=True) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code', null=True) name = models.CharField(max_length=32, null=True) … -
Show fields passing through a ManyToMany field django admin
I'm working on a project developed in Python 2.7 and Django 1.11. I'm trying to show in admin page two fields passing through a ManyToMany field. Here the models: class ModelZero(Model): # some fields mtm_field = models.ManyToManyField(to="ModelOne", through="ModelTwo") class ModelOne(Model): # some fields field_1_1 = models.CharField(unique=True, max_length=200) field_1_2 = models.BooleanField(default=True) class ModelTwo(Model): # some fields field_2_1 = models.ForeignKey('ModelOne', on_delete=models.CASCADE) field_2_2 = models.BooleanField(default=True) In the ModelZero admin page I want to show some fields from the ModelZero itself plus field_2_1 and field_2_2 from ModelTwo. More in detail, the field_2_1 should be present using a custom widget. Please note that ModelZeroAdmin is an inline ones. Here the admin page: class ModelZeroAdmin(DynamicRawIDMixin, admin.TabularInline): model = ModelZero fields = ('some', 'fields', 'field_2_2') form = forms.ModelZeroForm def field_2_2(self, obj): return obj.mtm_field.through.field_2_2 Here the form: class ModelZeroForm(ModelForm): class Meta: widgets = { "mtm_field.through.field_2_1": dal.autocomplete.ModelSelect2Multiple( url="my-autocomplete-url" ) } In this way i have two errors: it's not possible add custom fields (field_2_2) in the fields tuple custom widget is not showed Is there a way to achive this goal using this models structure? -
How to fetch the data for the current hour in Django
I am trying to fetch data from a django model while filtering its DateField() to the current date and current hour. models.py class Log(models.Model): DATE = models.DateTimeField() TYPE = models.CharField(max_length=32,primary_key=True) class Meta: db_table='LOG' indexes=[ models.Index(fields=['DATE','TYPE']) ] views.py obj=Log.objects.filter() How can I define my filter in such a way that it returns the data of current hour only? -
Django adding new fields to external DB's model
I am trying to integrate some tables from an Oracle DB, which is not a part of my Django project. That DB has 2 tables of interest to me, with the first one having 90% of information, and the 2nd one having the remaining 10%. I have written 2 models for these tables, which go something like this: class MoreRelevantModel(models.Model): FIELD_1 = models.IntegerField(primary_key=True, db_column="PK_COL_NAME") FIELD_2 = models.CharField(max_length=40, blank=True, db_column="CHAR_VALUE_COL_NAME") FIELD_3 = models.BooleanField(default=False, db_column="BOOL_VALUE_COL_NAME") class Meta: managed = False db_table = '"SomeOracleSchema"."SomeOracleTableName"' class LessRelevantModel(models.Model): FIELD_1 = models.IntegerField(primary_key=True, db_column="PK_COL_NAME") FIELD_2 = models.CharField(max_length=40, blank=True, db_column="CHAR_VALUE_RELATED_TO_MoreRelevantModel_COL_NAME") FIELD_3 = models.BooleanField(default=False, db_column="BOOL_VALUE_COL_NAME") class Meta: managed = False db_table = '"SomeOracleSchema"."SomeOracleTableName"' I would like to completely omit the need to call LessRelevantModel model in my business logic, and instead I want to just call MoreRelevantModel, and have it auto-pull from its corresponding LessRelevantModel entry FIELD_3 value. I came up with the idea to write it as such: class MoreRelevantModel(models.Model): FIELD_1 = models.IntegerField(primary_key=True, db_column="PK_COL_NAME") FIELD_2 = models.CharField(max_length=40, blank=True, db_column="CHAR_VALUE_COL_NAME") FIELD_3 = models.BooleanField(default=False, db_column="BOOL_VALUE_COL_NAME") class Meta: managed = False db_table = '"SomeOracleSchema"."SomeOracleTableName"' @cached_property def _LESS_RELEVANT_ENTRY(self): matching_entry = LessRelevantModel.objects.filter(FIELD_2=self.FIELD_2) return matching_entry [0] if matching_entry.count() > 0 else None @cached_property def LESS_RELEVANT_ENTRY_FIELD_3(self): return self._LESS_RELEVANT_ENTRY.FIELD_3 if self._LESS_RELEVANT_ENTRY else None Above logic kind … -
Python Speech to Text API (Postman)
I have written API for python speech to text and I want to test using postman so far I have tried this code but not be able to get the result. import speech_recognition as sr from flask import Flask from flask import jsonify from flask import request import json app = Flask(__name__) @app.route("/sp", methods=["POST"]) def index(): transcript = "" if request.method == "POST": postedData = request.get_json() filename = postedData["fileName"] print(filename) path="C:/Users/Mindpro/Desktop/wavFiles" url = path+filename print("FORM DATA RECEIVED") recognizer = sr.Recognizer() audioFile = sr.AudioFile(filename) with audioFile as source: data = recognizer.record(source) transcript = recognizer.recognize_google(data, key=None) print(transcript) return transcript if __name__ == '__main__': app.run(host='127.0.0.1',port='5000',debug=False) -
How to set the django project can enter the admin management login page from multiple urls
How to set up the django project can enter the admin management login page from multiple urls, I want to use different databases according to different urls But it doesn't seem to work. When I visit the login page of admin1-3, he will be reset to adminenter image description here Even if I return in the database routing judgment, there will still be errors when logging inenter image description hereenter image description here Is my idea wrong? Can you give me some advice, thank you very much. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'admin', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': 3306 }, 'adminx1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'adminx1', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': 3306 }, 'adminx2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'adminx2', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': 3306 }, 'adminx3': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'adminx3', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': 3306 } } urls.py urlpatterns = [ path('app_test/', include('apps.app_test.urls')), path('admin/', admin.site.urls), path('admin1/', admin.site.urls), path('admin2/', admin.site.urls), path('admin3/', admin.site.urls), ] middleware.py import threading from django.conf import settings request_cfg = threading.local() class AppTestMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each … -
How to query so that a field in an instance will show up instead of the actual instance
I am trying to query so that the value for a field in each model instance will show up with no duplicates. All of this is happening within the form: class OrganisorClassStatusUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrganisorClassStatusUpdateForm, self).__init__(*args, **kwargs) self.fields['off_day_student'] = forms.ModelChoiceField( queryset= Class.objects.filter(teacher=self.instance.teacher).filter(is_new_set=True).filter(time=self.instance.time).order_by('-date')[:10] ) Here, self.instance is referring to a Class model instance I am updating with this form. However, with this code, I would receive a list of Class instances for one of the form fields. What I want is a list of Student corresponding to each Class instances in the form field (there is only one student for each class). Therefore, instead of Class1, Class2, Class3, I would like to have Student1, Student2, Student3. Moreover, if there are any duplicates of a student's name, I would like to show only one. I hope the students are also listed in the order of -date for the classes as shown in the above code. Please ask me any questions. Thanks a lot. Here is the Class Model as some of you have asked: class Class(models.Model): teacher = models.ForeignKey('Agent', null=True, blank=True, on_delete=models.SET_NULL) student = models.ForeignKey('Lead', null=True, blank=True, on_delete=models.SET_NULL, related_name='student') -
How to integrate Coinbase in Django
I need to integrate Coinbase in Django to receive payments, but not Coinbase Commerce. I have been researching this and I think that with Coinbase Commerce, the normal one is not an option nowadays but anyway I would like to use it. Can I use Coinbase? -
Django Query - Many to Many fields query
I have these 3 models. class AddTemplate(models.Model): template_name = models.CharField(max_length=100, primary_key=True, default='Template 01') tests = models.ManyToManyField(AddTest, blank=True) clients = models.ManyToManyField(AddClient, blank=True) class AddClient(models.Model): client_name = models.CharField(max_length=300, primary_key=True, default='') class AddTest(models.Model): test_name = models.CharField(max_length=100, primary_key=True, default='Test 01') Now I'm trying to do something like this in my views.py file. def save_score(request, pk, pk_1): score = AddTemplate.objects.get(client_name=pk, test_name=pk_1) But it's showing an error 'matching query does not exist'. Any solution? -
how to filter objects by CharField
I want to filter cases_alert(class) by CaseAlert.alert_type which is a CharField. But the parameter of the filter function is not CharField. Anyone can give me help to fix this? Thank you. class CaseAlert(models.Model): alert_type = models.CharField(max_length=16) cases_alerts = CaseAlert.objects.all().prefetch_related('reports').filter(CaseAlert.alert_type.in_(['u1'])).order_by(CaseAlert.alert_key) -
Can't find django model instance in new view
I have a CreateView in which users enter details, after submitting this should take the user to a DetailView for the just submitted entry. I am wanting to use a UUID to identify the entires - but after submitting the form I get the following error: http://localhost:8000/patient/2792470c-216a-44cc-a4ef-98c12d946844/ NO patient found matching the query This is the basic project structure: models.py: class Patient(TimeStampedModel): # get a unique id for each patient patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) name = models.CharField("Patient Name", max_length=255) views.py class PatientCreateView(LoginRequiredMixin, CreateView): model = Patient fields = ['name'] def form_valid(self, form): form.instance.creator = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('patient:detail', kwargs={"slug": self.object.patient_id}) class PatientDetailView(DetailView): model = Patient urls.py urlpatterns = [ path( route='add/', view=views.PatientCreateView.as_view(), name='add'), path( route='<slug:slug>/', view=views.PatientDetailView.as_view(), name='detail'), ] Please could someone try and point out where i am going wrong? -
Django HTML: how do I make a "go home" link?
Here is the file structure of my project. I am adding a link in testpage.html, and I want it to take the user back to the root directory (http://127.0.0.1:8000 on localhost server) which is configured to use index.html as the homepage under pages > templates > index. testpage.html is below. the link is in line 3 (currently empty): <h1 class='list'>Classes</h1> {% if mydata %} <a href="">Go home</a> {% endif %} {% for k in mydata %} <table border="1"> <thead> <th>Team</th> <th>Name</th> <th>ClassCode</th> </thead> <tr> <td>{{k.Team}}</td> <td>{{k.Name}}</td> <td>{{k.ClassCode}}</td> </tr> </table> {% endfor %} {% endblock %} -
Logo is not showing on server after deploying but it is perfectly working on local server
I am using django rest framework. I want to create PDF from HTML and its working fine but when i deploy file on Amazon server, logo is not showing. I have used xhtml2pdf library for creating PDF. -
LoginRequiredMixin is not working with FormView
I am trying to force login for a formview but loginrequired mixin is not redirecting to the login url d efined in the settings file login url defined is LOGIN_URL = "django_auth_adfs:login" here is the Form view defined as class AddPage(LoginRequiredMixin, FormView): form_class = AddForm template_name = 'add.html' def get_initial(self): initial = superAddPageself).get_initial() if self.request.user.is_authenticated: res = requests.get(self.request.build_absolute_uri(reverse('add-list'))) initial.update({'Username': self.request.user.get_full_name()}) return initial def form_valid(self, form): return super(AddForm, self).form_valid(form) -
Sir,whenever I try to import veiws.py in url.py ,it shows an import error
Image of terminal of django showing import error