Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use concat and chr function in a django queryset?
I'm trying something like this: my_field=Concat( (chr(65) + F("foo")), F("bar") + Value(1), output_field=CharField(), ) But I got this error: invalid input syntax for integer: "A" foo and bar return a integer and I expect "A1, A2" like a result. -
update the DTL cycle without rebooting
Suppose my template has a lot of content that is generated using a DTL loop, which also has a lot of content. How can I, after an ajax request, update part of the content without reloading the page and display the new content using the DTL cycle? (I do not consider it necessary to insert the code, since the question requires a general answer) -
Django admin group permissions for CBV's
I am working on an app and right now I am dealing with a specific admin group that I created called post admin. In my django admin I have the permissions for the group set to Can Change Post, Can Delete post, Can View Post I want to give my post admin group users better access to be able to do this. Not just in the admin page. I want them to be able to go to my DeleteView, UpdateView and be able to edit/delete any users posts. So basically I need to be able to give access to the view to the user who originally created the post and my post admin group. Any tips/advice how to incorporate this? -
Filtering a Django model using the related names of 2 M2M fields
I have the following structure in my models: class Sauce(models.Model): ... class Topping(models.Model): ... class Pizza(models.Model): sauces = models.ManyToManyField(Sauce, related_name='pizzas') toppings = models.ManyToManyField(Topping, related_name='pizzas') Now, lets say I want to query all the pizzas given a list of toppings and sauces. For example: sauces_ids = [2, 5, 7, 8] toppings_ids = [1, 4, 5, 21] What is the most efficient way to query this using Django's ORM? Thanks for any help. -
I need to allow users to upload photos but my form is in forms.py not HTML
Our users are uploading photos through form.py ProfileForm, which is currently only allowing the admin to upload photos to the site. We added enctype="multipart/form-data" to our html that is rendering the form, but it still wont allow the user to upload their photos. class ProfileForm (forms.ModelForm): class Meta: model = Profile fields = ('nickname', 'gender', 'age', 'height', 'location', 'job_title', 'education', 'hometown', 'drinker', 'smoker', 'photo_one', 'photo_two', 'photo_three', 'prompt_one', 'prompt_two', 'prompt_three', 'age_preference_max', 'age_preference_min', 'gender_preference') {% extends 'base.html' %} {% block content %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> {% endblock %} -
Django adding custom admin.py to project causes error of not detecting one of applications in INSTALLED_APPS
I am doing a project which could be found here. If you check the link you find out that I have changed the default structure a little bit and its something like this: config/ env/ .env files requirements/ __init__.py ... settings/ __init__.py base.py local.py __init__.py urls.py views.py wsgi.py projects/ api/ town/ apps.py urls.py views.py ... core/ models/ town.py .... admin.py apps.py views.py serializers/ town_serializer.py ... tests/ test_town.py manage.py The project tests were running with no problem until I decided to develop customized admin located in project/core. This is admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from core import models class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display = ['email', 'name'] admin.site.register(models.User, UserAdmin) very simple as you see. After writing this I run the previous test and I found this error: RuntimeError Model class core.models.town.Town doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Which is really weird because I already have registered it in INSTALLED_APPS. take a look at base.py in config/settings/ directory file which is part of default settings.py file of django: DJANGO_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) THIRD_PARTY_APPS = ( 'rest_framework', 'django_filters', ) LOCAL_APPS = ( 'project.core.apps.CoreConfig', 'project.api.city.apps.CityConfig', 'project.api.town.apps.TownConfig', … -
Django urls.py deprecated, urlpatterns to change
I try to compile an old code in Django 1.4 Many things are deprecated. I manage to change some of them but I don't knwo how to go futher on the urls.py here is the old code from django.conf.urls.defaults import * from django.conf import settings dynurls = patterns('minesweepr.views', (r'^api/minesweeper_solve/$', 'api_solve'), ) staticurls = patterns('minesweepr.views', (r'^player/$', 'template_static'), (r'^query/$', 'template_static'), ) urlpatterns = patterns('', ('^%s' % settings.BASE_URL, include(dynurls)), ('^%s' % settings.BASE_STATIC_URL, include(staticurls)), ) I know django.conf.urls.defaults is deprecated and I tried to change the code like this from django.conf.urls import url, include from django.conf import settings dynurls = ['minesweepr.views', (r'^api/minesweeper_solve/$', 'api_solve'), ] staticurls = ['minesweepr.views', (r'^player/$', 'template_static'), (r'^query/$', 'template_static'), ] urlpatterns = ['', ('^%s' % settings.BASE_URL, include(dynurls)), ('^%s' % settings.BASE_STATIC_URL, include(staticurls)), ] But it is not sufficient It is said my url patterns are invalid. Anybody has an idea ? Thank you -
GitLab Job failed Django + Postgres project
I'm using Gitlab Job to build and test my Django project. I can't run my tests because my web container (the django one) is always restarting. I'm using a script .wait-for-postgres.sh to run my web container after the postgres one but it doesn't change anything. For info I'm using a scpefic Runner running inside a Gitlab container. Here is my config.toml file : concurrent = 1 check_interval = 0 [session_server] session_timeout = 1800 [[runners]] name = "Core API Runner" url = "https://gitlab.com/" token = "<my-token>" executor = "docker" [runners.custom_build_dir] [runners.docker] tls_verify = false image = "docker:stable" privileged = false disable_entrypoint_overwrite = false oom_kill_disable = false disable_cache = false volumes = ["/var/run/docker.sock:/var/run/docker.sock", "/cache"] shm_size = 0 [runners.cache] [runners.cache.s3] [runners.cache.gcs] And here is my runner output : -
Blog Post doesn't show images, bold text, or other attributes only the raw code... Django/Ckeditor
I've followed a tutorial on implementing a ckeditor RichTextUploadingField() to my blog so I can have more functionality and better looking post/blogs. Everything seems to be working but when I go to see the actual post after adding the picture and some words. I get a raw output with all my text... Here is my output on my blog <p><span style="color:#1a1a1a"><span style="background-color:#ffffff">First of all, I have assumed that you have seen countless rubbish articles, and still can&#39;t understand classes and objects, but at least know that there are two things like classes and objects.</span></span></p> <p><span style="color:#1a1a1a"><span style="background-color:#ffffff">Since you don&#39;t have programming experience, you can&#39;t understand Python&#39;s &#39;classes and objects&#39; by analogy from the programming language you&#39;ve learned.&nbsp;Let&#39;s use the example of life to build a house.</span></span></p> <p>&nbsp;</p> <p><span style="color:#1a1a1a"><span style="background-color:#ffffff"><img alt="" src="/media/upload/2019/11/08/01.png" style="height:268px; width:400px" /></span></span></p> Not sure why it doesn't look like the output I get before I post the article while I'm editing and creating it. MODELS.PY from ckeditor_uploader.fields import RichTextUploadingField from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=100) # content = models.TextField() content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return … -
How to accses queryset created by view in serializer so I can do some calculations based on it
I have a review model which has a large data so, first I want to filter based on the date range, I actually did that like this, class ProgressView(generics.ListAPIView): """ Return a list of all Feedback reviews for progress. """ serializer_class = ReviewProgressSerializer filterset_class = ProgressFilter pagination_class = UnlimitedPagination def get_queryset(self): return Review.objects.filter(division__pk=self.kwargs['division_pk']) Now I want to do some calculations based on this filtered queryset, but the problem I have is how to access this queryset and do calculations on it, I don't know how to do that in the serializer or should I do it in view. Please note that I need to do both, serialize the review data and return calculations too. I feel like there is a way to do both in one place because in the end, it is only one queryset so there must be a way to do anything I want with it in one place. so my question is how to access the queryset created by view in serializer or should I do that in another place or what. Thank you -
why can't I log in into any account until I reset its password in django admin?
I have a Profile model that has a one to one relationship with the User model from django.contrib.auth.models , when I add a new profile from the admin panel I noticed that the password field is not transformed into dots when typing , it shows the actual password , that's not the issue though , the issue is , when ever I create a new profile which in turns creates a new User , and mark the is staff attribute as true, I can't log in into the admin panel with that created account, unless I reset the password manually with python manage.py changepassword the-user-name after I have reset the password and only then even with the same password, I can log in into the account normally, does anybody know why is that happening ? I made sure it's not a mistake in typing the password and I tried it several times until I made sure that this is what is actually happening -
django deferring all fields in a related model queryset
I have a query where I need the second related model Model1.objects.all().select_related("model2__model3") but I don't need any field from model2, only many different fields from model3, e.g. obj.model2.model3.name and others How can I defer all fields from model2 without explicitly mentioning them one after the other? -
From where should we hit third party apis in django?
I'm a beginner in django. So my current structure is --/project ----/settings.py ----/urls.py ----/wsgi.py --/app1 ----/migrations ----/admin.py ----/apps.py ----/models.py --/app2 ----/migrations ----/serializers.py ----/apps.py ----/urls.py ----/views.py I want to know where and how (to access) should i code some things: I want to connect with a third party storage service by hitting their apis and getting the data i need. I want to store that data in my database in some model I created in models.py let's say 'Setting' I want to generate some more data using Setting data and store it in database for another model let's say 'Item' Finally the Item is what will be sent in the response for the rest api of my app which i have already achieved. Right now I am hitting the third party apis inside my views.py like this: class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = serializers.ItemSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): return self.queryset.order_by('order_id') def perform_create(self, serializer): """Create a new Item""" # generate some auth string and hit api # http = urllib3.PoolManager() # response_auth = http.request( # 'GET', # SOME_URL, # headers={auth: auth_string}, # ) # print(response_auth.status) # print(response_auth.data) # auth_response = json.loads(response_auth.data.decode('utf8')) # print(auth_response) # serializer.save(user=self.request.user, name=auth_response['name']) Also … -
Hello. I am having a problem to change the pages in my django project that it shows a page not found (404)
I've been building my first Django project, and I was doing the "login page", and it is working, but when then, I've made a condition that if the login is wrong, it comes back to the login page and shows an error message, and if it is right, it should go to a page where is written "logadissimo", but when I try this last one, I get the problem below: Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in sitetcc.urls, Django tried these URL patterns, in this order: admin/ login/ login/submit login/logado The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. this is my url.py from the project: Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls.conf import include from django.urls import path from core import views urlpatterns = [ … -
got issue OSError at /password-reset/ [Errno 101] Network is unreachable in django when send emails
try to send emails from django on localhost. previously everything works well, but now see that issue. net conection is ok. cant find info about how to solve it in the django. pleese help. here is a part of my settings.py file: # sending email for password reset EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '***@gmail.com' EMAIL_HOST_PASSWORD = 'google app key' -
trying to get the messages frame work to display message if valid and invalid
For some reason django displays both success message and failure message when I'm trying to display messages on form creation and update. Here I'm copy pasting the code for only the form creation. The view I'm using is: #function based views def post_create(request): form = PostForm(request.POST or None) # if request.method == "POST": # # print(request.POST) # print("title: ", request.POST.get("title")) # print("content: ",request.POST.get("content")) if form.is_valid(): instance=form.save(commit=False) print(form.cleaned_data.get("title")) instance.save() #a success message messages.success(request, "Successfully Created") return HttpResponseRedirect(instance.get_absolute_url()) else: messages.error(request, "Post Not Created") context= { "form":form } return render(request, "post_form.html",context) and the Post model is also very basic: class Post(models.Model): title = models.CharField(max_length=120)#; content = models.TextField()#: updated = models.DateTimeField(auto_now = True, auto_now_add=False)#; save and update everytime change is done timestamp = models.DateTimeField(auto_now = False, auto_now_add = True)#; auto_now_add = save and set one time def __unicode__(self): return self.title #python3 def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"id":self.id}) the form template is: <html> <head><title>new page</title></head> <body> <h1>Form</h1> <form method="POST" action=""> {{ form.as_p }}{% csrf_token %} <input type="submit" value="Create Post"/> </form> </body> </html> and the page where the message gets displayed is: <!DOCTYPE HTML> <html> <head> <title> index.html </title> </head> <body> {% if messages %} <ul class="messages"> {% for message in messages %} … -
Django: django.urls.exceptions.NoReverseMatch: Reverse for 'update' with arguments '('',)' not found
When I'm trying render template after login I get django.urls.exceptions.NoReverseMatch: Reverse for 'update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['users/(?P[0-9]+)/update/$'] My line in urls.py: app_name="users" ... path("users/<int:pk>/update/", view=user_update_view, name="update"), And line in template: <a href="{% url 'users:update' pk=request.user.pk %}">Update user</a> I see that request.user.pk not giving value, but I don't know why. -
Django - UserManager(BaseUserManager)
Within the Django file /django/contrib/auth/models.py , in the class class UserManager(BaseUserManager): , have inserted the prints as seen below . Now creating new users - nothing gets printed in the terminal . My Question - Why wont the email and username print into the terminal ? Is the _create_user method not being used , when creating a new user? class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email, and password. """ print("--PlaceHolder----") # Doesnt Print in Terminal if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) print(email) # Doesnt Print in Terminal username = self.model.normalize_username(username) print(username) # Doesnt Print in Terminal I understand that the class class UserManager(BaseUserManager) is being called with the line of code objects = UserManager() within the class class AbstractUser(AbstractBaseUser, PermissionsMixin): , in the same file . This question is a follow-up to my earlier question here - Django - UserModel - How to create Custom Text Field within the django/contrib/auth/forms.py -
How do I get a context variable into a template tag in django - modifying Wagtail Menus template tag
I'm modifying the Wagtail Menus flatmenu template tag to accept a context variable instead of a string for the handle. The use case is that I want to pull in a specific menu based on a slugified version of a user's group name. The template looks like this: {% for group in user.groups.all %} {% with handle=group.name|slugify %} {% utility_flat_menu handle %} {% endwith %} {% endfor %} The templaet tags looks like: @register.simple_tag(takes_context=True) def utility_flat_menu( context, handle, max_levels=None, show_menu_heading=False, apply_active_classes=False, allow_repeating_parents=True, show_multiple_levels=True, template='', sub_menu_template='', sub_menu_templates=None, fall_back_to_default_site_menus=None, use_absolute_page_urls=False, add_sub_menus_inline=None, *args, **kwargs ): validate_supplied_values('flat_menu', max_levels=max_levels) if fall_back_to_default_site_menus is None: fall_back_to_default_site_menus = settings.FLAT_MENUS_FALL_BACK_TO_DEFAULT_SITE_MENUS if not show_multiple_levels: max_levels = 1 menu_class = settings.models.FLAT_MENU_MODEL return menu_class.render_from_tag( context=context, handle=context, fall_back_to_default_site_menus=fall_back_to_default_site_menus, max_levels=max_levels, apply_active_classes=apply_active_classes, allow_repeating_parents=allow_repeating_parents, use_absolute_page_urls=use_absolute_page_urls, add_sub_menus_inline=add_sub_menus_inline, template_name=template, sub_menu_template_name=sub_menu_template, sub_menu_template_names=split_if_string(sub_menu_templates), show_menu_heading=show_menu_heading, **kwargs ) That tag is a replacement for teh Wagtail Menus Flat Menu template tag found here: https://github.com/rkhleics/wagtailmenus/blob/1a938576adb801c455bea4b64906fb135c89f65f/wagtailmenus/templatetags/menu_tags.py#L46 So, what I'm trying to do is allow the handle to accept a context variable. I can for the life of me figure out how to get that to work. What you see for the handle = context is my guess at where the change needs to go, but I'm guessing. -
How to send sms messages with django and AWS SNS with phone numbers stored in a database
I am making an application with django that does the following, when a user presses a physical button , the button sends a POST request to django-rest which then creates a ticket , at the same time it creates the ticket it sends a sms notification to a phone stored in an SQL database . The phone number corresponds to someone who can help with the problem the user that pressed the button is having. I have tried to think how while handling the POST request in the server I can query the table that has the phone numbers and then with the phone number send the sms but I cant think of a way. I expect that when the user presses the physical button a support ticket is created and the person responsible for helping with the ticket recieves a sms notification on the phone. -
problem with passing parameter between two django template using include
I have created a 'more_btn' component like this. <div> <a href='{% url link %}' >{{ text }}</a> </div> and I want to reuse this component in two-parent components like bellow. {% include "util_components/more_btn.html" with link="job1" text="s1" %} {% include "util_components/more_btn.html" with link="job2" text="s2" %} the problem is that the URL block in 'a' tag in 'more btn' component wants an ID, not a string. How can I solve this? -
getting stats from relationship of django model
I have django model where i have requests and workers who working with this requests. So how i can get the all the requests of every worker for making stats here is my model class workers(models.Model): firstName = models.CharField(max_length=50, verbose_name="имя") lastName = models.CharField(max_length=50, verbose_name="фамилия") surnameName = models.CharField(max_length=50, verbose_name="отчество", blank=True) position = models.CharField(max_length=250, verbose_name="должность") class Meta: verbose_name = "работник" verbose_name_plural = "работники" def __str__(self): return "%s %s - %s" % (self.firstName, self.lastName, self.position) class requests(models.Model): name = models.CharField(max_length=50, verbose_name="название") description = models.CharField(max_length=300, verbose_name="описание") statusChoice = ( ("got", "Заявка получена"), ("processing", "Оброботка заявки"), ("started", "Выполняется работа"), ("ended", "Работа завершена"), ) status = models.CharField(max_length=30, verbose_name="статус", choices=statusChoice) client = models.ForeignKey(clients, on_delete=models.CASCADE, verbose_name="клиент") workers = models.ManyToManyField(workers, verbose_name="работники") requirements = models.ManyToManyField(requirements, verbose_name="требования") class Meta: verbose_name = "заявка" verbose_name_plural = "заявки" def __str__(self): return "%s %s - %s" % (self.name, self.description, self.status) -
And operator in a Django filter
I created a Django Rest Framework API endpoint. I would like this endpoint to retrieve all the records with the Status field set to Free, so i did this: queryset = tst.objects.using('screener').filter(Status=Free) Now, i want to retrieve not only the fields with the field set to Free, but also those with the status set to Pending. I tried this: class tstList(generics.ListCreateAPIView): criterion1 = Q(Status="Free") criterion2 = Q(Status="Pending") queryset = tst.objects.using('screener').filter(criterion1&criterion2) For some reason, this view will retrieve nothing. If i try the queries individually, though, they will work: queryset = tst.objects.using('screener').filter(criterion1) #works -
Autoposting to Facebook page from django-rest-framework app
I have a simple Django Rest Framework app running. I want to auto post to app's Facebook page whenever new item is saved in the db. I was wondering if Django management commands is the best solution. The other option is google cloud functions to make a request at specified time and post to Facebook if there are new items (could be expensive and unnecessarily complex). Any suggestions would be appreciated. -
Run bash script with Django on external Linux server
Good Guys, I am building an application with Django (Python), I really need a help to run a bash script on an external Linux server from my django web application. Can someone help me ? My django view is below, but only runs on the internal server. I need a view that runs to another external server. def teste(request): if request.POST: subprocess.call('/home/user/test.sh') return render(request,'teste.html',{})