Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Test Client returning error on client.get(reverse('polls:index'))
working through the Django tutorial and running into issues. Patience appreciated! I'm on part 5 attempting to use the test client. When I run: > response = client.get(reverse('polls:index')) I get the following error: TemplateSyntaxError: Invalid block tag on line 38: '<span', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I'm sure it has to do with my index.html or some other file associated with my Django code so please ask me to edit this post with applicable files. For now, here is the index.html code: <meta charset="utf-8"> <title>My test page</title> </head> <body> <h1>subtitle test thing</h1> <p> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li> <a href=“{% url 'polls:detail' question.id %}”>{{ question.question_text }} </a> </li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} </p> </body> </html> Fair point here: I DO NOT KNOW HTML. I understand that Django provides incomplete HTML so I did my best to build structure around it. I have no idea if it's even right. Other files that might be helpful: urls.py: > from django.urls import path from . import views > > app_name = 'polls' urlpatterns = [ > path('', views.IndexView.as_view(), … -
print Python dictionary in some another way
t = '%(a)s %(b)s %(c)s' print(t % dict(a='Welcome', b='to', c='home')) I have seen the above question in one of my python test but didn't get an idea of what is happening here. Can someone please explain to me what is happening why the print function is printing 'Welcome to home'? -
How do I build a system to view a user's profile contents trough a link
I already have a profile viewing and updating page for user. But I want everyone able to view the users profile through a link in the user's post. views.py: def teacherprofile(request, id): userT = User.objects.filter(id=id) return render(request, 'viewprofile.html', {'posts': userT}) urls.py: urlpatterns = [ path('', views.index, name='index'), path('home', views.index, name='home'), path('signup', views.signup, name='signup'), path('postskill', views.postskill, name='postskill'), path('profile', views.profile, name='profile'), path('teacherprofile/<int:id>',views.teacherprofile, name='teacherprofile'), path('post/<int:id>', views.post, name='post'), path('post_delete/<int:pk>', views.post_delete, name='post_delete') ] home.html template from where the url for teacherprofile is called: {% for a in skills %} <ul> <div class = "rca"> <li>Posted By: <a href="{% url 'teacherprofile' a.id %}"> <h5> {{a.teacher_name}} </h5></a></li> <li>Subject Type: {{a.skill_type}}</li> <li>Subject Name: {{a.name}}</li> <li>Duration: {{a.duration}} months</li> <li>Cost: Rs. {{a.cost}}</li> <li>Location: {{a.location}}</li> </div> </ul> {% endfor %} viewprofile.html template: {% extends "base_generic.html" %} {% load crispy_forms_tags %} {% block content %} <img class="rounded-circle account-img" src="{{posts.image.url}}" height="100" width="100"> <h5> First Name: {{posts.first_name}} </h5> <h5> Last Name: {{posts.last_name}} </h5> <h5> Username: {{posts.username}} </h5> <h5> Email: {{posts.email}} </h5> <p> Bio: {{posts.profile.bio}} </p> {% endblock %} -
Hi, I want to know how to implemente a logic using PayPal in Django :)
I am struggling with the logic, since I want to charge the customer before creating the "Reservacion" instance. So, the code in the view where I have the logic is here: if (Cantidad_Mesas - Mesas_Ocupadas) >= Mesas_a_Ocupar_Cliente: nueva_reservacion = Reservacion.objects.create(Nombre=Nombre, Dia=Dia, Numero_Personas=Numero_Personas, Email=Email, Horario=Horario) # Creamos una instancia del modelo Reservación directamente desde el "view.py". nueva_reservacion.save() # Guardamos la nueva instancia creada en la base de datos. set_ = True # Hacemos uso de esta bandera, para indicar que SÍ fue posible guardar la reservación en la BD. return render(request, "reservacion/disponibilidad_horarios.html", {"disponibilidad": lista_horarios, "dia_reservacion": Dia}) But I want to do is, as I said, before creating the instance "Reservacion", I want to be able to built-in a payment using PayPal, so. Any Ideas? Thank u, so much! -
clients.models.Clients.DoesNotExist: Clients matching query does not exist. - django python
this is how I solve the problem clients.models.Clients.DoesNotExist: Clients matching query does not exist for r in orders_page: try: cls2 = cls.objects.get(related_uuid=r.related_uuid) related_list.append(cls2) except clients.models.Clients.DoesNotExist: pass is there any better solution for get empty? -
Django - account.models.Account doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS while using pinax-notifications
Integrating client project with pinax-notifications for notification kind of functionality. *File "/home/user/Shwetha/ramble/ramble/rambleapp/urls.py", line 56, in <module> url(r"^notifications/", include("pinax.notifications.urls", namespace="pinax_notifications")), File "/home/user/.local/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/user/.local/lib/python3.6/site-packages/pinax/notifications/urls.py", line 3, in <module> from .views import NoticeSettingsView File "/home/user/.local/lib/python3.6/site-packages/pinax/notifications/views.py", line 5, in <module> from .compat import login_required File "/home/user/.local/lib/python3.6/site-packages/pinax/notifications/compat.py", line 12, in <module> from account.decorators import login_required File "/home/user/.local/lib/python3.6/site-packages/account/decorators.py", line 5, in <module> from account.utils import handle_redirect_to_login File "/home/user/.local/lib/python3.6/site-packages/account/utils.py", line 13, in <module> from .models import PasswordHistory File "/home/user/.local/lib/python3.6/site-packages/account/models.py", line 26, in <module> class Account(models.Model): File "/home/user/.local/lib/python3.6/site-packages/django/db/models/base.py", line 116, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class account.models.Account doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.* As per the https://github.com/pinax/pinax-notifications#documentation Documentation , it was installed and configured. Encountered the above error while configuring. Already tried: In settings.py, INSTALLED_APPS section add both pinax and pinax-notifications. Added Sites in INSTALLED_APPS and made SITE_ID=1 in … -
Error accessing Sendinblue (Hosting: Pythonanywhere)
¡Hello! I have recently deployed a website developed in Django to Pythonanywhere. The web is integrated with Sendinblue, I checked the Whitelisted and saw that the API is allowed for free accounts in Pythonanywhere. I ask for your help because all the API queries give me errors like the one I show you at the end, on the other hand everything works fine outside the hosting. I would appreciate if you could tell me what I should do to access the Sendinblue API. Thank you very much to all. Greetings Error: 2021-03-17 11:55:19,469: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7fb4274735d0>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /v3/contacts?limit=5&offset=0 -
Django, using select2 for choice field
Now that select2 is shipped in django for the autocomplete_fields feature, I have been looking for a way to use the select2 widget for a simple choice field which has many options. what's the current best way to do so? -
Stop forloop tag template - Django
I am trying to stop a "forloop" tag template in Django, but I couldn't find a way to do that. In my Django template, I want to show all the articles that I have in my database. And each of those articles is connected to one or more SDGs. For now, my code is showing all the related SDGs, but I would like to only show the first result, and thus stop the "forloop" as soon as there is one positive result. Would someone know how to do that? Here is my Django template: <section> <div class="row px-4"> {% for article in articles %} <div class="col-md-12 col-lg-3 px-3 mb-5" data-aos=fade-up> <div class="card shadow lift rounded"> <div class="card-body py-4"> <h3 class="card-title">{{ article.title }}</h3> {% for sdg in sdg_seed_image %} {% if sdg.seed_id == article.id %} <h4>{{ sdg.sdg_id }}</h4> {% endif %} {% endfor %} </div> </div> </div> {% endfor %} </div> </section> Here is my view code: def article_view(request): articles = Article.objects.all().order_by("-date_publication") sdg_seed_image = SDG_Seed.objects.all() return render(request, "dist/inside/article/view_all.html", context={"articles": articles, "sdg_seed_image": sdg_seed_image}) -
Update with signals in django
I would like when i make any changes on client, to be modified on this table too. class ClientsBalance(models.Model): company = models.ForeignKey(Company, on_delete=models.PROTECT) exercice = models.ForeignKey(Exercice, on_delete=models.PROTECT) client = models.OneToOneField('Client', on_delete=models.CASCADE, related_name='Client') def create_client(sender, **kwargs): if kwargs['created']: client = ClientsBalance.objects.create(client=kwargs['instance'], company=kwargs['instance'].company, exercice=kwargs['instance'].exercice) post_save.connect(create_client, sender=Client) -
dj-rest-auth limit social sign up to a specific email address domain
I'm getting started with dj-rest-auth and I have an app which allows user to only sign in via google. However, I want users to only be able to access my service with a specific google apps email domain. I'm using dj-rest-auth in conjunction with django-allauth. This is what I tried: I created allauth adapters like this: class CustomAccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request): return False # No email/password signups allowed class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): def is_open_for_signup(self, request, socialaccount): u = socialaccount.user return u.email.split("@")[1] == "mydomain.com" and in my settings I have ACCOUNT_ADAPTER = "users.adapters.CustomAccountAdapter" SOCIALACCOUNT_ADAPTER = "users.adapters.CustomSocialAccountAdapter" With this solution, if the user tries to sign in with a valid email, everything works, whereas if they use a non-allowed email domain, I get this error in my console: Traceback (most recent call last): File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/dj_rest_auth/views.py", line 48, in dispatch return super(LoginView, self).dispatch(*args, **kwargs) File "/home/my_user/.local/share/virtualenvs/my_project-mzTAT1MS/lib/python3.8/site-packages/rest_framework/views.py", line … -
partial matching in django-filter
suppose, i'v an username (abcde). now if i search for abcd or bcde it should return that object which username is abcde. How to do that? #filters.py from .models import User import django_filters class UserFilter(django_filters.FilterSet): class Meta: model = User fields = ['username'] #views.py @api_view(['GET']) @permission_classes((IsAuthenticated,)) def search(request): queryset = User.objects.all() filterset = UserFilter(request.GET, queryset=queryset) if filterset.is_valid(): queryset = filterset.qs serializer = SimpleUserSerializer(queryset, many=True) return Response(serializer.data) -
How to activate virtual environment
I installed Django not knowing I was to create a virtual environment before installing it.(I don't know if I am making sense) but now I cant activate my virtual environment? is there something that I can do to rectify this -
Is Django's Caching Framework per user or across all user's
I have read through Django's caching framework documentation (https://docs.djangoproject.com/en/3.1/topics/cache/#), and want to know if the caching is per user or for all user's. For example, User A: Generates this link with parameters --> https://example.com/?parameters=hello User A: Re-opens the previous link and experiences a fast reload. User B: Opens the link User A generated, but does not experience a fast reload time. No where in the documentation does it state it's per user, but from testing it seems to be that way. I just want to know if this is the intended purpose behind the caching framework? If, so is there a way to cache the requests for all user's? -
How to redirect to different site, and pass auth credentials using Django
Is it possible to redirect to a different URL with authentication using django? For example, with python requests, I can log into a site by passing credentials like: UN= "myuser" PWD = "mypassword" loginUrl = "https://example.com/" client = requests.session() header_data = {'referer' : loginUrl, 'User-Agent' : 'Custom'} r = client.post(loginURL, auth=(UN, PWD), headers = header_data) But If I want a button on a django powered page to redirect to another site, and login into it automatically, how can this be done? I tried using redirect, which works to redirect obviously, but I can't seem to figure out how to pass auth crendtials using a django view. I also tried redirect(user:password@example.com) which gives an error that this feature is depreciated on chrome, and I cannot pass credentials this way. Any help is appreciated! -
Is Pinax still being maintained?
This question is basically an update for this one. I recently discovered the django pinax ecosystem but I am not sure if this is currently being maintained and works for recent versions of Django. Documentation is not clear to me on this. Since this is a collection of different apps it may happen that some of them are more maintained than others, so the question would be if most of the apps listed here and the pinax-starter-projects are up to date with current django/python versions in 2021 (django 2.2/3, python 3+) -
What am I Doing Wrong? Trying to Deploy Django Application to Heroku and keep getting error code H10
I apologize this is my first time posting on here and I am not familiar with the formatting. Can someone please help me identify what I am doing wrong here? ''' 2021-03-17T15:47:40.537869+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=phil.herokuapp.com request_id=a917acfe-3ff8-4d9b-8ce8-62df15f56b58 fwd="68.48.189.95" dyno= connect= service= status=503 bytes= protocol=https ''' ''' 2021-03-17T15:47:41.230050+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=phil.herokuapp.com request_id=8cb225e2-c677-48d1-936e-1a5ed8c29904 fwd="68.48.189.95" dyno= connect= service= status=503 bytes= protocol=https ''' '''2021-03-17T16:33:48.040804+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=phil.herokuapp.com request_id=69e8e429-e064-42dc-be4d-2c4c7db5ce47 fwd="68.48.189.95" dyno= connect= service= status=503 bytes= protocol=https ''' ''' 2021-03-17T16:33:48.592375+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=phil.herokuapp.com request_id=c26a368c-af03-4604-93a0-13fd5c6be104 fwd="68.48.189.95" dyno= connect= service= status=503 bytes= protocol=https ''' ''' 2021-03-17T16:44:02.920835+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=phil.herokuapp.com request_id=a3444390-698d-4c77-8998-23bb6a75b04b fwd="68.48.189.95" dyno= connect= service= status=503 bytes= protocol=https ''' -
Django - Pandas - add_format: cell get format but only applied if enter keys is pressed
I have a django function in the backend that collect some numbers from a database using a for loop, set the format for the workbook with workbook.add_format and write to a spreadsheet that get then downloaded. This is the core of my code: native_format = workbook.add_format({'num_format': '#,##0.00;[Red]-#,##0.00'}) for index, wp_number in enumerate(df['WP no.']): # workpackets' row index start at row=1 row = index + 1 worksheet.write_number(row, 5, df['Invoice total'][index], formats[-1]) worksheet.write_number(row, 6, df['Against this WP'][index], native_format) the format is correctly applied to the cells but when i download and open the spreadsheet the following happens: As you can see the format is applied as custom and not number. Only if I select a cell and press enter the format is recognised and applied: I can make the format to automatically apply to all cell? Thank you for your help -
default groups& permissions not working for abstract base user with permissions mixin in django
I am working with AbstractBase user. I have created users and groups. After I assign group to user, if I login with that user , the user has access to the complete admin site with all the CRUD operations. I have a created a product group with add-delete-edit-view permissions(default) and assigned a user to it. But when this user logins to the admin site, he has access to all the other items of the site as well. How do I make sure the logged in user can access only the items from assigned groups /permissions??? #managers.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) #models.py from __future__ import unicode_literals from django.db import models from django.core.mail import send_mail from django.contrib.auth.models import … -
What is _() in a Python dictionary?
This might be a dumb question but I recently stumbled upon this code in Django Rest Framework, couldn't find out what is the _() inside that dictionary... class SlugField(CharField): default_error_messages = { 'invalid': _('Enter a valid "slug" consisting of letters, numbers, underscores or hyphens.'), 'invalid_unicode': _('Enter a valid "slug" consisting of Unicode letters, numbers, underscores, or hyphens.') } -
link to user who posted an ad displays current users profile. django
I am building a web application for finding tutors where tutors can post a job. In the post, a link to user whose profile should be displayed is given. I tried doing that on my own but ended up showing the current user profile (profile of the user who is logged in currently). Please teach how to show the profile of the user who posted the job. View for profile: def profile(request): if request.method == 'POST': p_form = UpdateProfile(request.POST, request.FILES, instance=request.user.profile) if p_form.is_valid(): p_form.instance.user = request.user p_form.save() return redirect('profile') else: p_form = UpdateProfile(instance=request.user.profile) context = { 'p_form': p_form, } return render(request,'profile.html',context) Note: the profile view also has model form to update Urls.py: urlpatterns = [ path('', views.index, name='index'), path('home', views.index, name='home'), path('signup', views.signup, name='signup'), path('postskill', views.postskill, name='postskill'), path('profile', views.profile, name='profile'), path('post/<int:id>', views.post, name='post'), path('post_delete/<int:pk>', views.post_delete, name='post_delete') ] models.py and form for profile : class Profile(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE) image= models.ImageField(default = 'default.jpg',upload_to='profile_pics') bio=models.CharField(default = 'no bio',max_length=350) def __str__ (self): return f'{self.user.username} Profile' class UpdateProfile(forms.ModelForm): class Meta: model = Profile fields =['image','bio',] def clean(self): super(UpdateProfile, self).clean() return self.cleaned_data Template profile.html: {% extends "base_generic.html" %} {% load crispy_forms_tags %} {% block content %} <style> #hide { display: none; width: 100%; padding: 50px … -
Issues when converting image binary data from PostgreSQL using Python to string format
I am trying to come up with a solution to retrieve binary data of an image saved as byteatype from PostgreSQL, and convert it to string format so that <img src>can read it. It was written in the Python based framework Django. Here is the code from models.py class Images(models.Model): image_code = models.BinaryField() caption = models.CharField(max_length=100,default='IMG_CAPTION') In my views.py,what I have is the following: def imageRetrieving(request): store_length = len(Images.objects.all()) image_shown = Images.objects.all()[store_length-1] print(image_shown.image_code.decode('ascii')) context = { 'img_src':str(image_shown.image_code) } return render(request,'imgstore/formTesting.html',context) When I run, I always receive an error message 'memoryview' object has no attribute 'decode' in the browser. I am looking for some guidance here. Thank you. -
Django MYSQL created_date and mod_date with specific SQL
I'm relatively new to Django, and am trying to have the following SQL statements for two fields that appear in all of my models: sys_created_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, sys_mod_date datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, currently the model fields look like this: sys_created_date = models.DateTimeField(auto_now_add=True,blank=False,null=False) sys_mod_date = models.DateTimeField(auto_now=True) However, when I inspect the MYSQL database directly the fields look like this: `sys_created_date` datetime(6) NOT NULL, `sys_mod_date` datetime(6) NOT NULL, What would be the best (most Django appropriate) way to alter these MYSQL columns so that the constraints listed above are contained directly within the MYSQL database? Thanks for the help. -
virtualenv is installed in my machine but still getting "not recognised as internal or external command "
I have installed virtualenv and virtualenvwrapper-win directories in my machine using commands pip install virtualenv and virtualenvwrapper-win And also when I run pip show virtualenv It is displaying everything about it .But when I try to run mkvirtualenv my_project It's showing me this error 'mkvirtualenv' is not recognized as an internal or external command, operable program or batch file. Idk why ... please help me out . -
Is it possible to pass a variable variable when including Django template
I want to use a Django template to create links to unchosen releases in a dropdown button. The created links are defined like this: {% for release in all_releases %} {% if release != in_release and release != out_release %} <a href="{% url url_view %}?in_release={{release}}&out_release= {{out_release}}">{{release}}</a> {% endif %} {% endfor %} and {% for release in all_releases %} {% if release != in_release and release != out_release %} <a href="{% url url_view %}?in_release={{in_release}}&out_release={{release}}">{{release}}</a> {% endif %} {% endfor %} Would it be possible to create dropdown-link.html file containing: {% for release in all_releases %} {% if release != in_release and release != out_release %} <a href="{% url url_view %}?in_release={{in_release_query}}&out_release={{out_release_query}}">{{release}}</a> {% endif %} {% endfor %} and to invoke it in the actual rendered template like this, sort of creating variable variables: {% include "release-dropdown.html" with in_release_query=release out_release_query=out_release %} ... {% include "release-dropdown.html" with in_release_query=in_release out_release_query=release %} I know this exact approach is not possible here. Would you recommend an alternative?