Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting values in a database to Django models
I have manually imported data (via a .csv file) into a database, how can I now connect the values imported into the database to a Django model so that I could then reference the data via application logic? I know that this is the opposite of the standard process and as a result, I have been able to find no references to this process online. -
Why isn't my attribute value printing correctly to the shell in Django?
This feels very simple but I can't find the solution anywhere... I have an object (question) defined as an instance of my Question model. It has the attribute 'type' which has 2 options. When querying it in the shell, I can see the correct attribute value, but when I try to print this value I get 'None'. This is affecting one of my views as I need to call a different html template depending on the type of question. e.g.: question=Question.objects.get(id=24) q_type = question.type When I call q_type, the correct attribute ['Single'] is printed to shell , When I call print(q_type), None (with no quotation marks) is printed to shell Feel like I'm missing something obvious here.. please help -
ValueError at /profiles/testuser/ Field 'id' expected a number but got 'testuser'
Well I need a help. I am working with class base views and models in django. I am trying to build follow system but got an error. : ValueError at /profiles/testuser/ Field 'id' expected a number but got 'testuser'. , I have search on it but couldn't solve it. Can you guys help me. I hope you python and django community help me. urls.py urlpatterns = [ path('<str:username>/',UserProfileDetailView.as_view(),name = 'detail'), ] views.py class UserProfileDetailView(DetailView): model = UserProfile template_name = "profiles/userprofile_detail.html" slug_url_kwarg = "username" # this the `argument` in the URL conf slug_field = "user" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args,**kwargs) print(self.object.user,'view profile') print(self.request.user.userprofile.follower.all(),'my profile') is_following = False if self.object.user in self.request.user.userprofile.follower.all(): is_following = True context["is_following"] = is_following return context models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) def __str__(self): return f'{self.user.username}' traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/profiles/testuser/ Django Version: 3.0.3 Python Version: 3.8.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'accounts', 'posts', 'profiles'] Installed 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'] Traceback (most recent call last): File "C:\Users\AHMED\anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value return int(value) The above … -
Django unit testing form with field assigned from request object
I have this form class PostCreationForm(forms.ModelForm): def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and I'm trying to unit test it with this test class PostCreationByFormTestCase(TestCase): def __init__(self, *args, **kwargs): super(PostCreationByFormTestCase, self).__init__(*args, **kwargs) self.CustomUser = get_user_model() def setUp(self): self.credentials = { 'username': 'john_smith', 'password': 'St0ngPassw0rd' } self.user = self.CustomUser.objects.create( username=self.credentials['username'], email='john_smith@mail.com', password=self.credentials['password'], first_name='John', last_name='Smith' ) def test_simple_form(self): form_data = { 'author': self.user, 'title': 'Simple Post', 'description': 'very good description', } form = PostCreationForm(form_data) self.assertTrue(form.is_valid) post = form.save() the assert passes, but the form.save() produces django.db.utils.IntegrityError: null value in column "author_id" violates not-null constraint I tried changing the form to class PostCreationForm(forms.ModelForm): def form_valid(self, form): if not form.instance.author: form.instance.author = self.request.user return super().form_valid(form) but it still does not work. I saw this as a recommended way to assign field to object if I don't want to take it as an input from the user as in this case where I want the author of the post to be the current user. How should I fix that in order to be able to test the form? -
Is this MySQL query equivalent to this Django query
Is this MySQL Query SELECT * from books WHERE ISBN = (SELECT ISBN FROM userWishlist WHERE userid_id = request.user.id) equivalent to this Django query? q = userWishlist.objects.filter(userid_id = request.user.id).values('isbn_id') return books.objects.filter(ISBN = q) -
Django makemigration freezes / hangs
I recently updated my project and it had changes that needed to be migrated. I tried to run migrations but the process freezes, and I don’t get the stack trace as I have to kill the process manually. I have also tried to run migrations with a very verbose output (migrate -verbosity 3) but nothing comes out of the command line. I've also run python manage.py makemigrations with faulthandler, but the log is empty in that. I have tried making migrations both in the IDE and in the terminal, but both have the same behavior. Here are the troubleshooting steps I’ve tried so far: Docker-compose down and docker-compose down –volumes to delete the database Killed all postgres processes running on my computer Deleted all migrations and tried rerunning makemigrations (makemigrations freezes in the same way migrate does) Switched branches and tried running migrations from the other branch I’ve googled this issue but the steps I’ve outlined above cover what was recommended. If you have any thoughts on how to handle this issue I appreciate any guidance you might have. -
Why do retrieved Django models don't have the timezone set to its datetime?
I have a question about the way Django works with timezones. In my settings I configure my timezone: USE_TZ = True TIME_ZONE = 'Europe/Amsterdam' # At time of writing UTC+2 I have a model with a DateTimeField. I know that whenever Django saves this model in the timezone UTC regardless of timezone settings. I also know that whenever Django encounters a datetime without timezone (a naive datetime) it will assume it in the default time zone (in my case Amsterdam) and convert it to UTC upon saving. See https://docs.djangoproject.com/en/3.1/topics/i18n/timezones/#interpretation-of-naive-datetime-objects However, whenever I retrieve a model from the DB using Django, the DateTimeField will have a datetime that does not have a timezone. I know by specification that it is in UTC, but whenever I save my model back to the DB (after updating some fields) Django will see the datetime is naive and assume it is in the default timezone. In my case it keeps subtracting 2 hours from the datetime every time an object is updated. So, whenever I do this. A = MyModel.object.get(pk=1) A.some_field = 10 A.save() I will get a RuntimeWarning: DateTimeField received a naive datetime and my timestamp got subtracted 2 hours. I can solve this … -
In Django, is it possible to force prefetch_related to exec only one SQL query?
with these models: class CustomUser(PaymentUserMixin, AbstractUser): pass class Customer(StripeModel): subscriber = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name="djstripe_customers", ) Is it possible to force this QuerySet to use only one SQL query (instead of two) ? CustomUser.objects.prefetch_related('djstripe_customers').get(email="user@gmail.com") that generates that: SELECT "accounts_customuser"."id" FROM "accounts_customuser" WHERE "accounts_customuser"."email" = 'user@gmail.com' LIMIT 21; args=('user@gmail.com',) SELECT "djstripe_customer"."djstripe_id" FROM "djstripe_customer" WHERE "djstripe_customer"."subscriber_id" IN (6); args=(6,) Note: I cannot modify Customer model -
Editing Django formset data creating new records instead of updating
I am trying to update a group of formsets that are related the main form (Project Information) by the main forms pk. The create form works fine, but I am finding it extremely difficult to implement the update version. I swear to you that I have read everything and taken some online courses and I just cannot get this. The form that is presented to the user has a dropdown choice and they select the project they would like to update. I've included an image of this. The selected project triggers an AJAX request to def project_data(request) below in view.py and the data for each formset is looped through and the formsets are created dynamically and populated. This also can be partially seem in the included image. All of that works fine. It's the save as an update part that I cannot for the life of me figure out. Here comes the example. Don't laugh! view.py @login_required def edit_project(request): SampleInformationFormSet = formset_factory(SampleInformationForm, extra=1) DissolutionMethodsFormSet = formset_factory(DissolutionMethodsForm, extra=1) DissolutionEndAnalysisFormSet = formset_factory(DissolutionEndAnalysisForm, extra=1) DissolutionSamplingFormSet = formset_factory(DissolutionSamplingForm, extra=1) DissolutionStandardsFormSet = formset_factory(DissolutionStandardsForm, extra=1) DissolutionMediaFormSet = formset_factory(DissolutionMediaForm, extra=1) DissolutionAnalysisRunFormSet = formset_factory(DissolutionAnalysisRunForm, extra=1) form = ProjectInformationForm(request.POST or None) si_formset = SampleInformationFormSet(request.POST or None, prefix='si') d_formset = … -
The django admin login in is not working and the template is lost
I just get into the Django. everything works on my local: enter image description here but after I deploy it on the on Heroku, the admin login page becomes like this: enter image description here enter image description here and I can not log in ever thought I create the superuser. here is my setting.py INSTALLED_APPS = [ 'event.apps.EventConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', #'django.contrib.gis', ] 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', ] ROOT_URLCONF = 'meetUpFinder.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':[os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] WSGI_APPLICATION = 'meetUpFinder.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR , 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True SITE_ID = 1 LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR , 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, … -
Django and Azure SQL Database connection error?
I'm trying to link my SQL database in azure to my django application, here are my settings: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'network-project', 'USER': 'adminenrique@network-project', 'PASSWORD': '***', 'HOST': 'network-project.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver':'ODBC Driver 13 for SQL Server' }, }} Here's the error when I'm trying to migrate: $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying admin.0001_initial...Traceback (most recent call last): File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\sql_server\pyodbc\base.py", line 546, in execute return self.cursor.execute(sql, params) pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Foreign key 'django_admin_log_user_id_c564eba6_fk_network_user_id' references invalid table 'network_user'. (1767) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Could not create constraint or index. See previous errors. (1750)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\Enrique … -
Cant get page to redirect with Django
I cant seem to get the redirecting to work. Everything else works up till there please help. Below are my code and error views.py error -
How does one keep a user logged in with Django Rest Framework?
I'm new to Django coming from the Firebase world, where authentication and keeping a user logged in is super easy. In learning Django (Rest Framework) I came to find out that you can log in a user, get a token and save the token in Cookies to reuse is next time that same user goes into the website. Is this the best way to keep a user logged in? So far, I can log a user in, get their token and some additional info, but I'm not sure how to prevent this from happening over and over again. I'd like to know how to keep the user logged in. Also, whenever the user gets back on the browser, do I place a POST request to get their own information (if needed to display on the screen)? Always? I'm very confused as to how authentication/logging in works. -
Show all user articles in his profile (DetailView) [django]
In user appI have Profile model: class Profile(AbstractUser, HitCountMixin): bio = models.TextField(blank=True, null=True, default='Brak') slug = models.SlugField(null=False, unique=True) photo = models.ImageField(blank=True, null=True, upload_to='profile_photos') In Views: class ProfileView(HitCountDetailView): model = Profile template_name = 'profile/profile.html' count_hit = True Also I have 2 other app: articles and videos. class AllArticlesListView(ListView): template_name = 'news/articles_list.html' model = Article paginate_by = 5 def get_queryset(self): return self.model.objects.all().order_by('-pk') class AllVideosListView(ListView): template_name = 'video/videos_list.html' model = Video queryset = Video.objects.order_by('-pk') paginate_by = 5 How can I put all user articles and videos to his profile to ProfileView(DetailView)? -
Retrieving multiple rows from seperate model in django relationships
I've been struggling with this puzzled for a few hours. Here's a schema of what I'm trying to do. I have a user model and a profile model, it's a one-to-one relationship, but I'd like to be able to query a user and retrieve all the email addresses (from the User model) for users that share the same company (from the Profile Model). To be fair, my understanding of django is limited, but I went through the serializer relations guide and tried my hands at most approach described there, to no avail. At this point, I'm not even sure I'm on the right path. So, my understanding of it is From the user, I need to fetch the profile (a source='profile' approach may work) From that profile, I need to retrieve the company From that company, I need to retrieve all the user_id that belongs to that company From those user_ids, I need to lookup the email fields of all those users I need to also filter out the email address of the user making the request Does this make any sense? At this point, I'm trying to accomplish all of that from the serializer, but was unsuccessful. Here are … -
How to render markdown file to HTML using django?
I am trying to render a page that written in markdown to HTML when clicking a link using Django. but every time I click on the link the markdown page does not render will here's my views.py: from django.shortcuts import render from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def search(request, name): return render(request, f"{ name }.md") and here's the urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.search, name="search") ] -
How to export arabic characters to pdf in xhtml2pdf?
I want to export arabic characters to pdf using xhtml2pdf, cause I'm using it in my django app. I know that they made an update saying that they fixed it, but it didn't work with me, I used a custom font but still not working. So please anyone knows the right encryption for this or anyway around it, help me. invoice.html : {% load static %} <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <head> <title>{{title}}</title> <style type="text/css"> @font-face { font-family: Amiri, "Amiri Font"; src: url("{% static 'font/Amiri-Italic.ttf'%}"); } body { font-weight: 200; font-size: 14px; } </style> </head> <body><pdf:language name="arabic"/> <div class='wrapper'> <div class='header'> <p class='title'>Invoice # {{ invoice_ID }} </p> </div> <div> <div class='details'> <pdf:language name="arabic"/> <p> تجربة</p> customername : {{customer_name}} <br><hr> <hr class='hrItem' /> </div> </div> </body> </html> utils.py : from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None views.py : from django.shortcuts import render, redirect, HttpResponse import pandas as pd from .models import SaleInvoice, TransferWays, User, InstallingCities from siteManagment.models import MarketersManagment, … -
DRF - Create a Viewset Mixin/Baseclass to inherit a viewset-action
I have a website that is essentially a wiki for a DnD campaign that I am participating in. As such it has articles of Creatures, Characters, Locations and more. I wanted to use Viewsets to access them easily and wanted to use a Viewset action (together with a custom router) to be able to look for individual records not through pk, but through various query-parameters. I already have something that works for this, now I would like to apply some inheritance to it to not repeat myself. What I'd like to do is something like this: class WikiBaseViewset (viewsets.ModelViewSet): detail_with_params_url_pattern_suffix: str @action(detail=True, url_name="detail-params", url_path=detail_with_params_url_pattern_suffix) def detail_through_params(self, request, **kwargs): if self.detail_with_params_url_pattern_suffix == "": raise InvalidViewsetURLException("URL of view 'detail_through_params' of WikiBaseViewset is not defined!") model = self.serializer_class.Meta.model instance = get_object_or_404(model, **kwargs) serializer = self.get_serializer(instance) return Response(serializer.data) class CharacterSerializer (serializers.HyperlinkedModelSerializer): class Meta: model = wiki_models.Character fields = '__all__' class CharacterViewSet(WikiBaseViewset): """Called with URLs: character, character/<str: name>""" serializer_class = CharacterSerializer queryset = wiki_models.Character.objects.all() detail_with_params_url_pattern_suffix = "(?P<name__iexact>.+)" However, I'm struggling over the fact that the decorator absolutely requires the URL parameter in the base class. Otherwise the code just doesn't compile. If you were to set detail_with_params_url_pattern_suffix="" in the base-class in order to not get … -
Django-allauth confirm email message redirect to different URL
I am trying to set up django-allauth to verify user emails. Currently, I have set it up to send an email, however, after signup, it redirects to the login page and I do not know how to configure it to should a custom HTML message that users need to verify email address. Currently my signup view is: from allauth.account.utils import * def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() send_email_confirmation(request, user, True) return redirect('main:user_login') else: form = SignUpForm() return render(request, 'main/signup.html', {'form': form}) How can I configure it so it shows a message: Confirmation email sent to someone@example.com On my custom HTML template. I cannot find this on the docs I only have managed to change the custom email template which I have set in my project directory in: project --app1 --app2 --templates ----account -------email ---------emain_confirmation_message.txt How can I redirect users after signup to a message page that they need to verify their email address? And they can resend if it is incorrect? -
Django Rest Framework - How to return all info from a model in a Response when getting Object of type model is not JSON serializable?
I am trying to return an object with more information after a user logs in. class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) player = Player.objects.get(id=user.pk) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email, 'full_user_info': player, # Object of type Player is not JSON serializable }) I've tried dict(player) but then the error reads TypeError: 'Player' object is not iterable -
AttributeError: 'QuerySet' object has no attribute '_require_cacheprofile'
I have an error when trying to use @cached_as(OmittedLeadEmail) @cached_as(OmittedLeadEmail) File "/pyenv/versions/3.7.8/lib/python3.7/site-packages/cacheops/query.py", line 92, in cached_as querysets = lmap(_get_queryset, samples) File "/pyenv/versions/3.7.8/lib/python3.7/site-packages/funcy/seqs.py", line 114, in lmap return _lmap(make_func(f, builtin=PY2), *seqs) File "/pyenv/versions/3.7.8/lib/python3.7/site-packages/funcy/compat.py", line 8, in lmap return list(map(f, *seqs)) File "/pyenv/versions/3.7.8/lib/python3.7/site-packages/cacheops/query.py", line 88, in _get_queryset queryset._require_cacheprofile() AttributeError: 'QuerySet' object has no attribute '_require_cacheprofile' -
How To Make Files Downloadable But Not shareable
I am developing a music distribution platform like that of Itunes model, I want to be able to allow music artist upload their tracks and sell it, but I want to make it in such a way that they are downloadable after being paid for but when they get to any third party device they can no longer be shared via Bluetooth, social media apps or any file sharing software. I want one music to be unique to a single device. any suggestions ?? -
Django on Heroku: relation "app_label" does not exist
I'm trying to deploy my Django app on Heroku. The build is successful, but the deployment fails with django.db.utils.ProgrammingError: relation "app_label" does not exist. I'm deploying directly from GitHub; the repo is public. I already looked for advice online and added try-except around the urlpatterns as suggested here, but it didn't help. I also have all the migrations committed. Now I'm not sure what might have caused the problem or how to fix it. I have successfully deployed another Django and proceeded the same way now, which is why I'm surprised it doesn't work. I'm trying to connect to the same PostgreSQL DB on Heroku that I use for the other Django app. Is that a problem? Do I need to reconfigure something here? Or do I ever need to run python manage.py migrate manually on Heroku? I think this should be taken care of by my Procfile. Any ideas or tips? I'm using Python 3.8 and Django 3.1. -
Django conditional field display on form
I am trying to make a simple form, that conditionally shows the website input field based on the value of another database field (that is not on the form) status. For the sake of this process the status field is not editable by the user, just by the admin. Both fields are in the same table: profile. After working at this for a while I copped-out and just did the conditional hiding and showing on the template. But, I realise this is the unsophisticated method, and would like to improve it. What I tried so far in forms.py: class WebsiteForm(forms.ModelForm): class Meta: model = Profile fields = ( 'e-mail', 'website', ) if Profile.status == 'personal' : exclude = ('website',) This method in forms.py works effectively, in that I can conditionally show and hide the field if I use test comparitors in the if statement like: if 1 == 1: or if 1 != 1: But, I cannot get an effective test using the field Profile.status, the value in the field seems to be unavailable at the point the if test in forms.py is performed. If I use print(Profile.status) I get the following output in the terminal: user__profile__status__isnull, so I think … -
static files doesnt want to work as they are shown on website
From this link i copied all to create my index.html https://codepen.io/jeffglenn/pen/KNYoKa I copied and pasted all css into new created main.css file in statics and rest of HTML i pasted into my index.html body section, typed on the top {% load static %} created new lane in head <link rel="stylesheet" type="text/css" href="{% static 'wwwapp/main.css' %}"> and when Im restarting localserver, then i can see .css images but they are not moving as they are on demo + they are all the time grey... If you can explain me how can i amend this lane <div class="tl-bg" style="background-image: url(https://placeimg.com/802/802/nature)"></div>to get my .jpg instead of rendered photo from www. my path to downloaded images is wwwapp/static/wwwapp/images/11.jpg and 22.jpg and so one... Can someone help ?:)