Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best Way to Perform Addition and Multiplication on Django Fields
I have a model 'Manifests' and a form 'CreateManifestForm'. The user enters multiple lines of data in the CreateManifestForm and these are saved to the Manifest model (on a line by line basis, not using ajax or anything). There are 3 fields of concern in the model and form - 'Cases', 'FOB', 'CNF'. Both FOB and CNF are dollar amounts, so I'll use one as an example. How could I take the user entered FOB price, multiply it by cases and then store that number? Additionally, when the user enters another line, how could I do the same and then add that to the original number so I can get a total value. MODELS.PY class Manifests(models.Model): reference = models.ForeignKey(Orders) cases = models.IntegerField() product_name = models.ForeignKey(Products, default=None, blank=True, null=True) count = models.IntegerField() CNF = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True) FOB = models.DecimalField(max_digits=11, decimal_places=2, default=None, blank=True, null=True) def __str__(self): return self.description VIEWS.PY def add_manifest(request, reference_id): form = CreateManifestForm(request.POST or None) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) try: order = Orders.objects.get(id=reference_id) instance.reference = order except Orders.DoesNotExist: pass instance.save() form = CreateManifestForm(initial={'reference': Orders.objects.get(reference=reference_id)}) reference = request.POST.get('reference') manifests = Manifests.objects.all().filter(reference=reference) context = { 'form': form, 'reference_id': reference_id, 'manifests' : manifests, } return … -
working with {% if %} {% else %} in Django
how can I hide user name from login page with If-Statement. Im using this code to show the user name in the main page after login in, and it's working {%if request.user.first_name%}{{request.user.first_name}}{%else%}{{user}}{%endif%} but the problem is that it's shown in the login page too as "AnonymousUser". how can I hide this Any Idea? -
The joined path is located outside of the base path component
There was a project on Django 1.9. I rewrote it on 1.11. But when I deploy to the server and collectstatic, I get an error django.core.exceptions.SuspiciousFileOperation: The joined path (/var/www/vhosts/finbee.freshlimestudio.com/assets/fonts/finbeeFont/fonts/finbeeFont.eot) is located outside of the base path component (/var/www/vhosts/finbee.freshlimestudio.com/static) All traceback here: PROJ_MODULE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) ROOT = os.path.normpath(os.path.join(PROJ_MODULE_ROOT, "..")) root_path = lambda *args: os.path.join(ROOT, *args) path = lambda *args: os.path.join(PROJ_MODULE_ROOT, *args) STATIC_URL = '/static/' STATIC_ROOT = '' STATICFILES_DIRS = ( path('static'), ) STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) -
django updating user profile with custom form + display group name
I've got 2 questions: 1) I'm displaying a list of users w/ their group,and for the group name I got: ]> using {{instance.groups.all}} in my template. Any ideas to have only mygroup displayed? 2) For my update user form, I got an error and I don't know how and where to resolve it. error: updateUserView() got an unexpected keyword argument 'id' forms.py class UpdateForm(UserChangeForm): is_active = forms.BooleanField() Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ] group_name = forms.ChoiceField(choices=Group) class Meta: model = User fields = ('email', 'is_active', 'group_name', ) views.py def updateUserView(request): if request.method == 'POST': form = UpdateForm(request.POST, instance=request.user) if form.is_valid(): user = form.save() group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) return redirect('accounts:users') else: form = UpdateForm(instance=request.user) return render(request, 'accounts/update_user.html', {'form': form}) class UserView(LoginRequiredMixin, GroupRequiredMixin, ListView): template_name = 'accounts/display_users.html' group_required = ['Creators'] queryset = User.objects.filter(is_active=True) -
Django Channels dont sent message to Android App
I wanted to apply the official django channels tutorial from https://channels.readthedocs.io/en/latest/tutorial/part_2.html to a simple android app. At https://medium.com/@ssaurel/learn-to-use-websockets-on-android-with-okhttp-ba5f00aea988 I found a simple project but that uses the Echo WebSocket Server available at http://www.websocket.org/echo.html. I copy-pasted the same project but replaced the Echo WebSocket Server with my own websocket server using django channels. Here is the code: public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private Button start; private TextView output; private OkHttpClient client; private final class EchoWebSocketListener extends WebSocketListener { private static final int NORMAL_CLOSURE_STATUS = 1000; @Override public void onOpen(WebSocket webSocket, Response response) { Log.d(TAG, "onOpen() is called."); JSONObject obj = new JSONObject(); JSONObject obj2 = new JSONObject(); try { obj.put("message" , "Hello"); obj2.put("message", "Goodbye!"); } catch (JSONException e) { e.printStackTrace(); } webSocket.send(obj.toString()); //webSocket.send("What's up ?"); //webSocket.send(ByteString.decodeHex("deadbeef")); webSocket.close(NORMAL_CLOSURE_STATUS, obj2.toString()); } @Override public void onMessage(WebSocket webSocket, String text) { Log.d(TAG, "onMessage() for String is called."); output("Receiving : " + text); } @Override public void onMessage(WebSocket webSocket, ByteString bytes) { Log.d(TAG, "onMessage() for ByteString is called."); output("Receiving bytes : " + bytes.hex()); } @Override public void onClosing(WebSocket webSocket, int code, String reason) { Log.d(TAG, "onClosing() is called."); webSocket.close(NORMAL_CLOSURE_STATUS, null); output("Closing : " + code + " … -
Is it possible to combine the delete view with view which show posts in django?
I am in the process of creating an application in django and so far I have followed the "basic" paths of application development. But now I started to wonder if there is a way to combine the view showing the posts with the delete posts view. I thought that when the delete button was pressed, a window would appear on the page (eg using Bootstrap Modals) which would approve the deletion of the post. Delete View: class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/about' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False View showing the post: class ShowView(generic.DetailView): model = Post template_name = 'blog/post_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.object.numbers_of_entries = self.object.numbers_of_entries + 1 self.object.save() return context If you need sth more just write! -
How to use Django packages with the same name?
There are two Django packages with the same option that I must add to the settings: Add "captcha" to the INSTALLED_APPS in your settings.py But it is not possible to add "captcha"to the settings two times because I will get the next error: django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: captcha So how can I use two packages with the same name in my Django project? PS: Please do not confuse "packages" and Django "apps". It described in official documentation about using apps with the same name, but there is nothing about packages. -
Python Django PWA paths
I was trying to make my site build with Django for python capable for mobile devices making a Progressive Web App. I have added to my base.html the following codes and it works, but when I click a link inside my page, it redirects to the page in Safari and not in the frame of the PWA. <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="apple-mobile-web-app-title" content="MyApp"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="default"> The other pages extends the base.html with the codes so I think, every file needs to have the codes on the but it doesn't work. Any clue of what this happens? -
Call prefetch_related_objects with arguments depend on an iterable
I have a list of objects to prefetch. And I need to use different order_by keys depend on the object. I wrote a function prefetch_iterable which return Prefetch object I call prefetch_related_objects function on iterable and pass prefetch_iterable() prefetch_related_objects(iterable, prefetch_iterable()) Can I somehow use different Prefetch objects for different elements of my list? -
how to fix reverse for logout not found in django python
i m customizing my admin page but getting this error Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name i have created admin directory creted the urls added base site and login templates. also created a view for logout in common directory class LogoutView(RedirectView): def dispatch(self, request, *args, **kwargs): auth_logout(self.request) return super(LogoutView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): return HttpResponseRedirect(reverse('login')) rlpatterns = [ path('admin/', include(('jat_admin.urls', 'jat_admin'), namespace="admin")), path('admin/', admin.site.urls), path('common/', include(('common.urls', 'common'), namespace="common")), path("login/", views.LoginView.as_view(), name="login"), path("logout/", auth_views.LogoutView.as_view(), name="logout"), path('social-auth/', include('social_django.urls', namespace="social")), path("", views.HomeView.as_view(), name="home"), -
Using same methods in two models
i am customizing slug method for auto generating and i am using like this models.py class Category(TimeStamp): name = models.CharField(max_length=255) slug = models.SlugField(max_length=100, unique=True) def __str__(self): return self.name def _get_unique_slug(self): slug = slugify(self.name) unique_slug = slug num = 1 while Category.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() super().save(*args, **kwargs) I am using this _get_unique_slug method in another model. But I wander if there is beautiful way to right this in mixins. I mean without writing get_unique_slug for each model. How do I this? Thank you? -
how to return value from database using django and ajax
i have a dropdown list that display the data from the database. i need to make dynamic using jquery and ajax where it will hide some values based on the user input on another field. my question is how to hide the required option based on the returning ID. the error that i get is : Could not parse the remainder: '=="dep D"' from 'sources.source_name=="dep D"' views.py def getSource(request): sources = Source.objects.all() return render(request,'create_folder.html',{'sources':sources}) create_folder.html <div class="formSelect" id="mouresaleMasdarDiv"> <select id="mouresaleMasdar" name="gender" required> <option value="">-- soource--</option> {% for source in sources %} <option val="{{ source.source_name }}"> {{ source.source_name }} </option> {% endfor %} </select> </div> <script type="text/javascript"> $('#mouresaleMasdar option[value="{{sources.get(pk = 1)}}"]').hide() </script> It gives an error so how to make this value hidden based on the id. -
Right way to get CreateView with modelformset_factory with multi forms
I have a skill model whose instances belong to different categories (eventually around 10). I will use 2 categories to reduce the code. For example, 2 categories: frameworks: django, angular etc. language: python, java etc. I need the user to add all the information about himself on one page at once. I made two forms with different querysets that only give Skills instances belonging to a separate group and two Formset forms.py class SkillBaseCreateForm(forms.ModelForm): YEAR_CHOICES = [(r, r) for r in range(1, 11)] LAST_YEAR_CHOICES = [(r, r) for r in range(1980, datetime.datetime.now().year + 1)] year = forms.CharField( widget=forms.Select(choices=YEAR_CHOICES), ) last_year = forms.CharField(widget=forms.Select(choices=LAST_YEAR_CHOICES)) class Meta: model = Skill fields = ['technology', 'level', 'last_year', 'year'] class SkillCreatePLanguageForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreatePLanguageForm, self).__init__(*args,**kwargs) self.fields['technology'].queryset = Technology.objects.filter(group_id='3') class SkillCreateFrameworkForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreateFrameworkForm, self).__init__(*args,**kwargs) self.fields['technology'].queryset = Technology.objects.filter(group_id='2') formset SkillFrameworkFormSet = modelformset_factory(Skill, form=SkillCreateFrameworkForm, extra=4, max_num=4, can_delete=False) SkillPLanguageFormSet = modelformset_factory(Skill, form=SkillCreatePLanguageForm, extra=4, max_num=4, can_delete=False) views.py class SkillTestCreateView(AuthorizedMixin, CreateView): model = Skill form_class = SkillCreatePLanguageForm template_name = 'skill_create.html' def get_context_data(self, **kwargs): context = super(SkillTestCreateView, self).get_context_data(**kwargs) context['formset_framework'] = SkillFrameworkFormSet() context['formset_planguage'] = SkillPLanguageFormSet() return context def post(self, request, *args, **kwargs): self.object = None formset_framework = SkillFrameworkFormSet(request.POST) formset_planguage = SkillPLanguageFormSet(request.POST) if formset_framework.is_valid() and formset_planguage.is_valid(): return self.form_valid(formset_framework, formset_planguage) else: … -
Set model field set default to iterator
I'm trying to set reportNr field default to a number that iterates every time a report has been added. Is there any way to do this? In models.py: from django.db import models class RapportQuerySet(models.query.QuerySet): def active(self): return self.filter() class RapportManager(models.Manager): def get_queryset(self): return RapportQuerySet(self.model, using=self._db) def all(self): return self.get_queryset().active() class Rapport(models.Model): objects = RapportManager() reportNr = models.TextField(blank=True, default="?") avd = models.TextField(max_length=10, null=True, blank=True) ritningNr = models.TextField(max_length=20, null=True, blank=True) enhetsNr = models.TextField(max_length=40, null=True, blank=True) atgard = models.TextField(max_length=100,null=True, blank=True) namn = models.TextField(max_length=100,null=True, blank=True) anstNr = models.TextField(max_length=100,null=True, blank=True) date = models.DateTimeField() file = models.FileField(null=True, blank=True) def __str__(self): return self.reportNr -
Django APPEND_SLASH doesn't work properly
if i write example.com/example-example it is working. However if i write example.com/example-example/ it doesn't work APPEND_SLASH=True in settings.py path('<slug:slug>',post_detail,name="post_detail"), -
How can I troubleshoot issues with a circus socket?
Environment: NGINX Django Python Circus I have a website that was returning 504 errors on various pages. In the nginx error log I was getting the following errors: [error] 30117#0: *280231 upstream timed out (110: Connection timed out) while reading response header from upstream, client: xxx.xxx.xxx, server: www.website.com, request: "GET /en/path/page/ HTTP/1.1", upstream: "http://unix:/tmp/glp-circus.sock/en/path/page/", host: "www.website.com" I increased the execution timeout for the server and these pages appear to be loading, however they are very slow. According to the browser, the TTFB is over 2 minutes. Presumably the socket for GLP is still causing the issue. How can I go about troubleshooting sockets which are managed by Circus? I have checked that the GLP socket is active. https://circus.readthedocs.io/en/latest/ -
Django 2.2 admin actions not displaying after adding materialize css
i'm learning how to customize the admin interface , my problem now is that the action select form ( where u can select an action and perform it clicking "GO" button) is not displaying at all it is because i added materialize and it's not respecting materialize structure , i wanted to EDIT the html but it seems to be PRE-RENDERED somehow somewhere ( what i tried : i checked the docs , i searched inside the admin app ), any clue on how to make my custom SELECT FORM while keeping the default functionality? any suggestions are highly appreciated. -
Live refresh of data in the admin site
I am working with Django mostly in the admin site. I use a background thread to connect with an another application, which long story short, manages to make some changes in the database (periodically) so in some model fields as well. What I want is when there is a change to be updated in the admin page as well without having to manually refresh it. I am trying to use channels (v2) to do that but I don't seem to really understand how to do that. To be more precise I tried to follow this tutorial. What I have so far is: settings.py ASGI_APPLICATION = 'myapp.routing.channel_routing' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('localhost', 6379)], }, } } routing.py channel_routing = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^myapp/mymodel/", MyConsumer), ] ) ) ) }) asgi.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") django.setup() application = get_default_application() consumers.py class MyConsumer(AsyncConsumer): async def websocket_connect(self,event): await self.send({ "type": "websocket.accept" }) await self.send({ "type": "websocket.send", "text": "This is a test" }) async def websocket_receive(self, event): print("receive", event) async def websocket_disconnect(self, event): print("Disconnected", event) And finally my JS code in my template extension: {% extends 'admin/change_list.html' %} {% load i18n admin_urls %} {% block object-tools-items %} <script> … -
Refresh Django template while maintaining scroll position
I have a Django template where I call a view by clicking a button. The view function returns a HttpResponseRedirect to the same page. I want the page to return/refresh to the same scroll position as when the user clicked the button. Here's what I've tried so far: Attempt 1: Based on this and this, I added an onsubmit to the form as follows: <form action="{% url 'buy' market.id %}" method="post" onsubmit="return refreshToSameScroll()"> ...calling location.reload() through the following script: <script type="text/javascript"> function refreshToSameScroll() { location.reload(); } </script> But that didn't work. Attempt 2: I then tried the following combination, reworked from this: <form action="{% url 'buy' market.id %}" method="post" onsubmit="return saveScroll()"> ...with this script: <script type="text/javascript"> function saveScroll () { var page_y = document.getElementsByTagName("body")[0].scrollTop; window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y; } window.onload = function () { if ( window.location.href.indexOf('page_y') != -1 ) { var match = window.location.href.split('?')[1].split("&")[0].split("="); document.getElementsByTagName("body")[0].scrollTop = match[1]; } } </script> The idea here being that clicking the button saves the scroll position, which then gets picked back up once the page reloads/refreshes. But that didn't work either. Any idea what I'm doing wrong? -
Passing a jira object from django view method to another unique to that session
All in the Django Views I have a login method which takes the username/password and logs a user in using the python ldap method Also the same credentials authenticate and make a jira object (Can be done as both are based on the same Active Directory) in login method def login(request): .... conn = ldap.initialize(....) conn.simple_bind_s(username, password) <-- user params jira = JIRA('server' , basic_auth=(username,password)) this jira object needs to be sent to a different view unique to that logged in session where that object has work done to it and avoids the user having to put in the creds again I tried global variables but that isnt unique to the session I tried Django's session variable request.session['jira'] = jira but i get a non serializable error How would i get this object from the login method to the desired view method -
Retrieving answered (not empty/null) questions from one_to_one relationship
I created a website where a User can create a project. Once the project is created, the user can answer 10 macroquestions (named: Firstquestion, Secondquestion...). Each of this macroquestion, contains a sub question (named: first_one, first_two...). For example: Project.Firstquestion.first_one will result in the first answered subquestion for the macroquestion Firstquestion Project.Secondquestion.second_one will result in the first answered subquestion for the macroquestion Secondquestion The user is not obliged to answer any of the subquestion. It can leave them blank. I want to do some calculation on how many subquestions the user has answered over the total of subquestions. Therefore, to retrieve if the user answered the questions I tried the following: def project_first_questions(request, project_id): answered_first = 0 not_answered_first =0 project = get_object_or_404(Project, pk=project_id) projects = Project.objects.all() first_one = project.firstquestion.first_one first_two = project.firstquestion.first_two first_three = project.firstquestion.first_three first_four = project.firstquestion.first_four first_five = project.firstquestion.first_five first_six = project.firstquestion.first_six first_seven = project.firstquestion.first_seven first_questions = [first_one, first_two, first_three, first_four, first_five, first_six, first_seven] for answer in first_questions: if answer: answered_first = answered_first + 1 else: not_answered_first = not_answered_first + 1 percentage_answered_first = round(float(answered_first / len(first_questions)), 2) percentage_not_answered_first = round(float(not_answered_first / len(first_questions)),2) return percentage_answered_first, percentage_not_answered_first The above does work HOWEVER I think there is an easier way using the … -
Upon logout i m still able to access the page (which is after login) without login required (by typing URL)
Problem Description : - When i login (i m redirected to the page required page) and after that when i logout and then type the URL of the page (present after login) i m still able to access the page (present after login without login required) i tried deleting session, cookies, even set_expiry() and also i read the documentation that logout() does that but all in vain. here's the code i tried:- In views.py def login_view(request): context = {} if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user: login(request, user) return HttpResponseRedirect(reverse('IP form')) else: messages.error(request,'Please provide valid credentials') return render (request,"first_app/login.html", context) del request.set_session['username':username] del request.session['password':password] del request.delete_cookie['username': username] del request.delete_cookie['password':password] else: return render (request,"first_app/login.html", context) @login_required def user_logout(request): if request.method == "POST": logout(request) del request.session['username':username] del request.session['password':password] del request.delete_cookie['username': username] del request.delete_cookie['password':password] #auth.logout(request) return HttpResponseRedirect(reverse('login')) @login_required def form_name_view(request): if not request.user.is_authenticated: response = HttpResponseRedirect('') response.delete_cookie('username') response.delete_cookie('password') del response.session['username'] del response.session['password'] return response # del request.session['username'] # del request.session['password'] # return HttpResponseRedirect(reverse('login')) if request.method == "POST": form = CmdForm(request.POST) settings.py SESSION_EXPIRE_SECONDS = 2 SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True thnx to those willing to help.! :-) -
Reloding <div> element without refreshing page
I'm working with Django. I have a voting app where people propose topics so the topics have to be automatically refreshed to every user every 5 seconds. I know I have to use an Ajax request to reload my div class = "topics" so I tryied many different codes: </script> <script type="text/javascript"> $('.topics').setTimeout(function(){ $.ajax( { type:"GET", url: "/mylogin/{{both.0.id}}/{{both.1.id}}", success: function( data ) { $("/mylogin/{{both.0.id}}/{{both.1.id}}" ).load(".topics"); $("todo.html" ).load(".topics"); $(".topics" ).load("todo.html"); $(".topics" ).load("/mylogin/{{both.0.id}}/{{both.1.id}}"); $("/mylogin/{{both.0.id}}/{{both.1.id}}" ).reload(".topics"); $("todo.html" ).reload(".topics"); $(".topics" ).reload("todo.html"); $(".topics" ).reload("/mylogin/{{both.0.id}}/{{both.1.id}}"); $('topics' ).load(); } }) }, 1000); And I have also tried this: window.setTimeout(function () { $(".topicos" ).load("/mylogin/{{both.0.id}}/{{both.1.id}}"); }, 1000); And also this: window.setTimeout(function () { $(".topicos" ).load("todo.html"); }, 1000); </script> none of these pieces of code reload anything and I can´t understand if maybe in django we need to code differently -
how to import import_module using importlib?
C:\Users\admin\Desktop\projects\quote>python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 2, in <module> from importlib import import_module ImportError: cannot import name import_module -
Django DRF - add a sub view/url?
I am wanting to create a sub view (if this is the right term?) under a view that alters the query set for example parent URL mysite.com/api/sites Child URL mystic.com/apit/sites/open and also each one of those URLS could be searched so parent URL mysite.com/api/sites/search=London Child URL mystic.com/api/sites/open/search=London my parent View, serialiser, and URL already exists class SiteROView(viewsets.ReadOnlyModelViewSet): queryset = Site.objects.all() serializer_class = SiteSerializer permission_classes = (IsAdminUser,) filter_class = Site filter_backends = (filters.SearchFilter,) search_fields = ('location','postcode','state') so I think I need to somehow add the suburl to that class SiteROView(viewsets.ReadOnlyModelViewSet): queryset = Site.objects.all() serializer_class = SiteSerializer permission_classes = (IsAdminUser,) filter_class = Site filter_backends = (filters.SearchFilter,) search_fields = ('location','postcode','state') def url_open: queryset = Site.objects.filter(state='open') Is this possible, and how would I achieve it? Thanks