Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Select the custom field within the query
When I want to select the custom field (its foreignkey related table field) within the query. Get some error like "column "isyeri" does not exist" models.py from django.db import models class isyerleri(models.Model): isyeri = models.CharField(max_length=30) def __str__(self): return self.isyeri class malzemeler(models.Model): malzeme = models.IntegerField() def __int__(self): return self.malzeme class isyerimalzemebilgileri(models.Model): isyeri = models.ForeignKey(isyerleri, on_delete=models.CASCADE) malzeme = models.ForeignKey(malzemeler, on_delete=models.CASCADE) net_islem_zamani = models.IntegerField() satis_fiyati = models.IntegerField() uretim_maliyeti = models.IntegerField() def __int__(self): return self.isyeri class gercekzamanlıveri(models.Model): isyeri = models.ForeignKey(isyerleri,on_delete=models.CASCADE) malzeme = models.ForeignKey(malzemeler,on_delete=models.CASCADE) brut_uretim_suresi = models.IntegerField() net_uretim_miktari = models.IntegerField() tarih = models.DateTimeField() def __int__(self): return self.isyeri view.py class alldatagercekzamanliveriListView(ListAPIView): queryset = gercekzamanlıveri.objects.raw("""SELECT isyeri FROM ( (SELECT * FROM tee_gercekzamanlıveri) a INNER JOIN (SELECT * FROM tee_isyerimalzemebilgileri) b ON a.isyeri_id= b.isyeri_id AND a.malzeme_id = b.malzeme_id) c""") serializer_class = alldatagercekzamanlıveriserializer serializers.py class alldatagercekzamanlıveriserializer(serializers.Serializer): id=serializers.IntegerField() isyeri = serializers.CharField(max_length=30) malzeme = serializers.IntegerField() isyeri_id = serializers.CharField(max_length=30) malzeme_id = serializers.CharField(max_length=30) tarih = serializers.DateTimeField() malzeme = serializers.IntegerField() brut_uretim_suresi = serializers.IntegerField() net_uretim_miktari = serializers.IntegerField() net_islem_zamani = serializers.IntegerField() satis_fiyati = serializers.IntegerField() uretim_maliyeti = serializers.IntegerField() [ { "id": 1, "isyeri": "Torna 1", "isyeri_id": "1", "malzeme_id": "1", "tarih": "2019-02-13T21:00:00Z", "malzeme": 2000001, "brut_uretim_suresi": 445, "net_uretim_miktari": 3560, "net_islem_zamani": 6, "satis_fiyati": 10, "uretim_maliyeti": 7 }, ] -
Realtion takeover from other site
as example my model.py: class address (models.Model): name= models.CharField(max_length=80) firstname= models.CharField(max_length=80) class bill (models.Model): address_link = ForeignKey(address) now i want to create a billform. In this billform i want a href with text adress and when i click on this href a new modal or popup open. In this modal/popup is how a table with all adressdata. Now user can select one adress and after submit this adress is insert in the original billform. How can i do this? Regards -
How to I find all the attributes of request.session.get
num_visits = self.request.session.get('num_visits',0) print(dir(self.request.session.get)) ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] I'm trying to figure out how to find self.request.session.get(num_visits). It's clearly an attribute because if I try self.request.session.get(blah_visits) I get an AttributeError. Where can its base attribute be accessed from? -
How to change django admin design like css, js, img ant etc
i want to change Django admin panel design for example i want to have material design in my Django admin and make some change in admin panel. how can i do this? i already use: collectstatic and create static folder that contain Django-admin static files bud when i do some changes on this files nothings happen. -
Django Url Pattern Not Being Found
I followed a tutorial to allow users to register an account but the url path does not seem to be found. It allows me to access 127.0.0.1:8000/accounts/signup but not 127.0.0.1:8000/signup when I have set the name for it. I tried changing the urlpatterns from a path to a url method but that didn't solve the problem. my file structure is as follows: App: accounts: urls.py views.py ... Server: settings.py urls.py ... templates: registration: login.html base.html home.html signup.html manage.py In my Server\urls.py I have from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='home.html'), name='home'), ] In my accounts\urls.py I have from django.urls import path from . import views urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), ] The error I get is Using the URLconf defined in Server.urls, Django tried these URL patterns, in this order: admin/ accounts/ accounts/ [name='home'] The current path, signup, didn't match any of these. I'm not too sure what is going on since I'm still sort of new to Django and busy learning as I go along. -
Django- invalid token in plural form: EXPRESSION
I added 'Kurdish' language to my django website. this language is not supported by django, so I added to languages as follow: in settings.py gettext = lambda s: s NEW_LANG_INFO = { 'ku': { 'bidi': True, 'code': 'ku', 'name': 'Kurdish', 'name_local': u'کوردی', }, } import django.conf.locale LANG_INFO = dict(**django.conf.locale.LANG_INFO, **NEW_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO LANGUAGES = ( ('en', 'English'), ('ku', gettext('Kurdish')), ('ar', 'Arabic') ) now when i go to mysite.com/en/admin/ it works properly. when I go to mysite.com/ar/admin/ it works properly. but when I go to mysite.com/ku/admin/ it raises an error with this message: ValueError at /ku/admin/ invalid token in plural form: EXPRESSION the django version is 1.11.6. what's the problem and how can i solve it? -
Django2.1.7 project urls.py not working properly (giving 404 error)
Project main urls problem. my code example below from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('/', include('homepage.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) applicaiton setting INSTALLED_APPS = [ 'homepage', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] homepage urls urlpatterns = [ path('', views.homepage, name='homepage'), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def homepage(request): return HttpResponse('Hello') Result: But if I change main project urls like below from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('homepage.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) result is: How can i see http://localhost:8000/blog in http://localhost:8000/ -
how to insert data in 2 database using view?
i am having problem to store data in 2 database table using one view i want to store data in 2 database table using 1 view on click event! please help it's urgent model.py class login(models.Model): Login_ID = models.AutoField(primary_key=True) Email_ID = models.CharField(max_length=20) Password = models.CharField(max_length=15) Roll_ID = models.IntegerField() class Meta: db_table = 'login' class roll_details(models.Model): Roll_id = models.AutoField(primary_key=True) Roll_Name = models.CharField(max_length=15) class Meta: db_table = 'roll_detail' class registration(models.Model): Register_ID = models.AutoField(primary_key=True) First_Name = models.CharField(max_length=10) Middle_Name = models.CharField(max_length=15) Last_Name = models.CharField(max_length=20) Contact_No = models.CharField(max_length=10) Address = models.CharField(max_length=150) Email_ID = models.EmailField(max_length=30) Date_of_Birth = models.DateField(max_length=20) Gender = models.CharField(max_length=6, choices=GENDER_CHOICES) #Gender = models.CharField(max_length=10) Login_id = models.IntegerField(max_length=10) Password = models.CharField(max_length=50) class Meta: db_table = 'registraion_detail' [this is my form i am using all value in from database][1] form.py class RegistrationForm(forms.ModelForm): class Meta: model = registration fields = '__all__' class LoginForm(forms.ModelForm): class Meta: model = login fields = "__all__" view.py def registraion_page(request): form = RegistrationForm(request.POST) form1 = LoginForm(instance=registration()) if request.method == 'POST': reg = RegistrationForm(request.POST) if reg.is_valid(): reg.save() form1 = LoginForm(request.POST,instace=registration) if form1.is_valid(): form1.save() return redirect(login_page) else: form = RegistrationForm() return render(request,"Registration.html",{'form':form}) i want to store data in 2 database table using 1 view on click event! i want to store data in 2 database table … -
how can I modify the urls or models to see the images in template(404 not found)?
My appName is photo. As you can see below in models.py the SubImages(file) save on 'photo/static/subImages/' but in works.html I cant see that subImages. In inspect element I see http://127.0.0.1:8080/works/29/photo/static/subImages/blah.jpg 404 not found, And I know the subImages saved on http://127.0.0.1:8080/photo/static/subImages/blah.jpg. What should I do in urls.py or models.py to see the subImages? models.py class SubImage(models.Model): image = models.ForeignKey('Image', on_delete=models.SET_NULL, null=True) file = models.ImageField(upload_to='photo/static/subImages/',max_length=1000, null=True) class Image(models.Model): title = models.CharField(max_length = 100) file = models.ImageField(upload_to='photo/static/images/',max_length=1000, null=True) works.html <img src="{{subImage.file}}"> urls.py url(r'^works/(?P<param1>\d+)/$', views.specsView, name='specsView'), views.py def specsView(request, param1): subImage_list = models.SubImage.objects.filter(image_id__exact = '29') -
How to setup nginx for multiple website under one domain?
I created two websites (with database) using django, let's call them web1 (database=web1_db) and web2 (database=web2_db). I'd like to run them under one domain in this way (main.html for example, each website has url.py to direct pages): www.mywebsite.com/web1/main.html www.mywebsite.com/web2/main.html I'm using nginx and uwsgi to serve the website and I can get web1 and web2 work separately. To serve both websites as stated above, I setup uwsgi in emperor mode (successfully, I think), but I can't figure out how I should config nginx to make this work. Can someone give me some suggestion? my nginx conf for single website is as below: upstream mywebsite { server unix:///tmp/mywebsite.sock; } server { listen 80; server_name www.mywebsite.com; proxy_http_version 1.1; ssl_protocols TLSv1.2; location /media{ alias /pathtomedia; } location /static{ alias /pathtostatic; } location / { include /etc/nginx/uwsgi_params; include /etc/nginx/mime.types; uwsgi_pass mywebsite; } } -
How to run @classmethod as a Celery task in Django?
How to run @classmethod as a Celery task in Django? Here is example code: class Notification(TimeStampedModel): .... @classmethod def send_sms(cls, message, phone, user_obj=None, test=False): send_message(frm=settings.NEXMO_FROM_NUMBER, to=phone, text=message) return cls.objects.create( user=user_obj, email="", phone=phone, text_plain=message, notification_type=constants.NOTIFICATION_TYPE_SMS, sent=True, ) n = Notification() n.send_sms(message='test', phone='1512351235') -
How to send message from one to other user with Django?
I want make custom message web app, which users can send messages each other(not chat, just sending message). I've message model and message form, but i don't know about views and templates looks like. I can't found any tutorial or something about this, most of i found just libraries or something packages. Then, how about this views and templates? here my models.py: from django.contrib.auth import get_user_model class Message(models.Model): sender = models.ForeignKey(get_user_model(), related_name="sender") receiver = models.ManyToManyField(get_user_model(), related_name="receiver") message_file = models.FileField(upload_to='mails/') timestamp = models.DateTimeField(auto_now_add=True) unread = models.BooleanField(default = True) forms.py from django import forms from .models import Message class MessageForm(forms.ModelForm): class Meta: model = Message fields =[ 'sender', 'receiver', 'message_file', ] Thanks in adnvance -
Set the data in render method after pre-declaration in Django
I have declared the variable as given below: response = render( request, 'authme/login.html', {} ) At some point of time, I need to set the temporary cookie and pass the value of temporary cookie in the view. I tried the following ways to set the data as given below: response['message'] = "Login Failed: Please try again" response.message = "Login Failed: Please try again" Can anyone suggest how can I set the message part using variable "response", in the same way, How do we use for setting cookie, PFB: response.set_cookie('message','Login Failed: Please try again') So that it is equivalent to this line of statement: response = render( request, 'authme/login.html', {"message":"Login Failed: Please try again"}) -
How to let users define the Django model complying with their excel files to upload?
I am starting to develop a django project which need to provide a HTML page for other students to upload their experiment results which are excel files (maybe CSV), and save them to databases. But when it comes to defining the models, most tutorial define the "static" model rather than letting users to define them. In my case, students may have diffent sheets to upload, for someone it maybe "date-time, id, max, min, eta", while "date, time, name, sex, notes" for someone else. Currently I can get the first row of the xls files and use them as the headers of database, and import them with excuting a single *.py file. But how can I do this with Django and deal with the database? Can anyone help me? Django 2.1.7 -
Codes in one of my views are not processed when I access to that view
My intention is to change from interface view -> switch view to process some data and send those data and change to -> test view to display the result. However, nothing in switch view seems to be processed and switch view doesn't change to test view after I hit 'submit' on userInterface.html. My guess is that the problem lies on the HttpResponseRedirect() function or anything related to url paths. Everything worked find with my other project that I worked on my computer. I'm not sure what I need to change to use Django on RaspberryPi. At first, I found out I didn't import libraries needed for those function. After I imported them, the code was still not working. I commented out other codes in switch view that do nothing with changing views and just focus on changing view in my switch view. view.py def user_interface(request): return render(request,'zuumcoin/userInterface.html', {}) def switch(request): return HttpResponseRedirect(reverse('zuumcoin:test')) def test(request): return render(request,'zuumcoin/test.html',{}) userInterface.html .... <form action="{% url 'zuumcoin:swicht' %} method = "POST"> {% csrf_token %} ... ... </form> urls.py app_name='zuumcoin' urlpatterns = [ url(r'', views.user_interface, name='interface'), url(r'switch/', views.switch, name='switch'), url(r'test/', views.test, name='test') ] I expect HttpResponseRedirect to direct me to test view instead of being stuck … -
recommed me courses of django with pymongo as a backend
Is there any online course related to Django with pymongo as a backend? If anyone knows about these kinds of courses please let me know. Thanks in advance. -
I'm not able to import my model class into serializer file
I'm trying to import classes from my model.py file into serializer.py file. Here's my code for model file from django.db import models from django.utils import timezone from django_hstore import hstore class WebhookTransaction(models.Model): UNPROCESSED = 1 PROCESSED = 2 ERROR = 3 STATUSES = ( (UNPROCESSED, 'Unprocessed'), (PROCESSED, 'Processed'), (ERROR, 'Error'), ) date_generated = models.DateTimeField() date_received = models.DateTimeField(default=timezone.now) body = hstore.SerializedDictionaryField() request_meta = hstore.SerializedDictionaryField() status = models.CharField(max_length=250, choices=STATUSES, default=UNPROCESSED) objects = hstore.HStoreManager() def __unicode__(self): return u'{0}'.format(self.date_event_generated) class Message(models.Model): date_processed = models.DateTimeField(default=timezone.now) webhook_transaction = models.OneToOneField(WebhookTransaction) team_id = models.CharField(max_length=250) team_domain = models.CharField(max_length=250) channel_id = models.CharField(max_length=250) channel_name = models.CharField(max_length=250) user_id = models.CharField(max_length=250) user_name = models.CharField(max_length=250) text = models.TextField() trigger_word = models.CharField(max_length=250) def __unicode__(self): return u'{}'.format(self.user_name) Now when I'm trying to write serializer.py file for this. I'm not able to import model classes in this file from rest_framework import serializers from slack.models import WebhookTransaction, Message class WebhookTransactionSerializer(serializers.ModelSerializer): class Meta: model = WebhookTransaction fields = '_all_' class MessageSerializer(serializers.ModelSerializer): class Meta: model = Message fields = '_all_' -
Q: How to store session data before authentication occured
I'm using django-all auth with GMail login. There one of my view that will receive HTTP-POST from a Hotspot login page in other server (actualy it's mikrotik hotspot redirect). I need to read their posted data AFTER social login. I read https://stackoverflow.com/a/32250781/5901318 Looks like the safest way is to store the POST data in session, and later my view will get it from request.session but I don't know how to 'store data safely in request.session before the authentication occurs'. def my_login_required(function): #https://stackoverflow.com/a/39256685/5901318 def wrapper(request, *args, **kwargs): decorated_view_func = login_required(request) if not decorated_view_func.user.is_authenticated: if request.method == "POST" : print('my_login_required POST:',request.POST.__dict__) print('my_login_required ARGS:',args) print('my_login_required KWARGS:',kwargs) print('my_login_required SESSION:',request.session.__dict__) wrapper.__doc__ = function.__doc__ wrapper.__name__ = function.__name__ return wrapper #@receiver(user_logged_in) @csrf_exempt @my_login_required def hotspotlogin(request,*args,**kwargs): print('HOTSPOTLOGIN') I tried to access it using requests : r = requests.post('http://mysite:8000/radius/hotspotlogin/', json={"NAMA": "BINO"}, headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}) but in django shell I only got : my_login_required POST: {'_encoding': 'utf-8', '_mutable': False} my_login_required ARGS: () my_login_required KWARGS: {} my_login_required SESSION: {'storage_path': '/opt/djangos/radius03/mysessions/', 'file_prefix': 'sessionid', '_SessionBase__session_key': None, 'accessed': True, 'modified': False, 'serializer': <class 'django.core.signing.JSONSerializer'>, '_session_cache': {}} Kindly please give me any clue to do that. Sincerely -bino- -
django not found Infinite loop
If there is no image, I feel like I'm caught in an infinite loop. {% for test in test_profile %} <tr> <td> {% if test.path != '' %} <img style=' width:70px;' src="{% static '/uploads' %}{{ test.path }}/pic_{{ test.name }}" onerror="this.src='/images/template/test_{{ test.gender }}.png';"> {% endif %} </td> <td>{{ test.l_idx }}</td> <td>{{ test.l_name }}</td> <td style="padding-left:10px;">{{ test.sub_name }}</td> </tr> {% endfor %} error message Infinite loop..... [30/Mar/2019 11:08:11] "GET /images/template/lawyer_0.png HTTP/1.1" 404 37457 Not Found: /images/template/lawyer_1.png [30/Mar/2019 11:08:11] "GET /images/template/lawyer_1.png HTTP/1.1" 404 37457 Not Found: /images/template/lawyer_0.png [30/Mar/2019 11:08:11] "GET /images/template/lawyer_0.png HTTP/1.1" 404 37457 Not Found: /images/template/lawyer_1.png ......................... -
Model doesn't appear to be inheriting
I am attempting to have one class relate to another in my models.py but it seems that only my Card class is relating to Subject correctly. I am trying to have them relate like so: "Each Stack will have multiple Subject(s), and each category will have multiple Card(s). When I run my migration I have no errors, but it only says: Migrations for 'flashcards': flashcards/migrations/0001_initial.py - Create model Card - Create model Stack - Create model Subject - Add field subject to card Just based on my migrations output it seems that only Card was related to Subject but Subject was not related to Stack, or am I reading this wrong and it worked fine? I am a new programmer, and only just learning how to test. models.py from django.db import models from django.conf import settings from django.utils import timezone from django.contrib.auth.models import User class Stack(models.Model): #A stack of cards that contains multiple categories author = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 200, unique = True) description = models.CharField(max_length = 300) created_date = models.DateTimeField(default = timezone.now) published_date = models.DateTimeField(blank = True, null = True) def __str__(self): return self.title class Subject(models.Model): #Subjects that are related to each stack title … -
how to define models in DJANGO 1.9
I have a model for a project in which I have to use Django and DRF. So I'm making a different file which takes all the objects from my model instances and provide a serializing. But in case of django 1.9 I'm not able to use Model.serializer from rest_framework import serializers from slack.models import WebhookTransaction from slack.message import Message class WebhookTransactionSerializer(serializers.ModelSerializer) class Meta: model = WebhookTransaction fields = '_all_' class MessageSerializer(serializers.ModelSerializer) class Meta: model = Message fields = '_all_' After running the server it's giving me this error File "/Users/sid/webhook10/tutorial/slack/serializer.py", line 8 class MessageSerializer(serializers.ModelSerializer) ^ SyntaxError: invalid syntax -
Count the number of objects in another model
I have two models in different apps: Program in programs and Contact in contacts. Each program can have many contacts. I want to have a field in Program called database_quantity that shows how many contacts are associated with that program. Here is what I have tried so far which is giving me this error: ImportError: cannot import name 'Contact'. I think this has to do with circular referencing but I am lost with how to proceed. programs models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from contacts.models import Contact class Program(models.Model): program_code = models.CharField(max_length=6) program_format = models.ForeignKey(ProgramFormat, models.SET_NULL, blank=True, null=True) program_type = models.ForeignKey(ProgramType, models.SET_NULL, blank=True, null=True) program_board = models.ForeignKey(RealEstateBoard, models.SET_NULL, blank=True, null=True) article_content_type = models.ForeignKey(ArticleContentType, models.SET_NULL, blank=True, null=True) program_name = models.CharField(max_length=60) date_created = models.DateTimeField(default=timezone.now) client = models.ForeignKey(User, on_delete=models.CASCADE) def get_database_quantity(self): database_quantity = Contact.objects.all().filter(author=self.request.user) return database_quantity database_quantity = property(get_database_quantity) contacts models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from programs.models import Program class Contact(models.Model): first_name1 = models.CharField(max_length=100, verbose_name='First Name') last_name1 = models.CharField(max_length=100, verbose_name='Last Name', blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) active_status = models.BooleanField(default=True) program_code = models.ForeignKey(Program, on_delete=models.DO_NOTHING, null=True, blank=True) -
How can I structure my JSON response using the Django Rest Framework serializer?
I have a database table: servicenumber | meternumber | usagedatetime | usage 11111 | 22222 | 2019-01-01 | 1.85 11111 | 22222 | 2019-01-02 | 2.25 11111 | 22222 | 2019-01-03 | 1.55 11111 | 22222 | 2019-01-04 | 2.15 11111 | 33333 | 2019-02-01 | 2.95 11111 | 33333 | 2019-02-02 | 3.95 11111 | 33333 | 2019-02-03 | 2.05 11111 | 33333 | 2019-02-04 | 3.22 As you can see, a service number can be related to multiple meter numbers. Think of the service number as a unique identification for a geographic location that doesn't change. And I have a Django model: class MeterUsage(models.Model): objectid = models.IntegerField( db_column='OBJECTID', unique=True, primary_key=True) servicenumber = models.IntegerField( db_column='serviceNumber', blank=True, null=True) meternumber = models.IntegerField( db_column='meterNumber', blank=True, null=True) usagedatetime = models.DateTimeField( db_column='usageDateTime', blank=True, null=True) usage = models.DecimalField( max_digits=38, decimal_places=8, blank=True, null=True) And I have a basic serializer: class MeterUsageSerializer(serializers.ModelSerializer): class Meta: model = MeterUsage fields = ( 'usagedatetime', 'usage' ) And the current response is: [ { "usagedatetime": "2018-03-01T00:00:00Z", "usage": "2.81600000" }, { "usagedatetime": "2018-03-01T01:00:00Z", "usage": "2.81600000" }, { "usagedatetime": "2018-03-01T02:00:00Z", "usage": "3.52000000" }, .... ] But what I really want is: [ { "servicenumber": "11111", "meternumber": "22222", "usagedata": [ { "usagedatetime": "2018-03-01T00:00:00Z", "usage": … -
Reversing to django admin index page
I am trying to redirect django index url to admin url which I can do something like below: # url.py path("", admin.site.urls,), url("^admin/", admin.site.urls, name="admin"), However, this generating warning WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace Hence, I decided to create a index view and use django.view.genertic.redirectview to pass to Django admin root URL as url attribute. I am trying find better way to generate Django admin root url using reverse function. -
Unable to correctly parse URLs using Django template language
I currently am trying to link a researcher's name if they provided a link, otherwise if they provide a blank input or N/A, then I choose not to link their name. I use the information from the researcher object using Django's template language, but when I check the result it ends up linking all of them, and those without input just have href = "" which links back to the homepage. I've tried using {{r.website_link|length}} instead, but that just creates errors and the page won't load. I'm a newbie to frontend so I'm not sure if my "if" statement is incorrect or if my HTML logic is incorrect. <div> {% for r in researcher %} <div class="researcher"> {% if "{{r.website_link}}" != "N/A" and "{{r.website_link}}" != "" %} <p><a class="researcherwebname" href="{{ r.website_link }}">{{ r.fullname|title}}</a> | {{ r.institution }} | {{r.position}} | <i>{{ r.des|capfirst }}</i></p> {% else %} <p> {{ r.fullname|title}} | {{ r.institution }} | {{r.position}} | <i>{{ r.des|capfirst }}</i></p> {% endif %} </div> {% endfor %} </div> I expect it to link researchers with an actual r.website_link input, otherwise the name should be unlinked.