Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is gunicorn toys_rent.wsgi actually doing in heroku?
I don't quite understand how this works, and I've been searching everywhere but didn't quite find the answer. So when I deploy a django app on heroku the other day I was using daphne with this in the Procfile : daphne app.asgi:application --port $PORT --bind 0.0.0.0 -v2 The app works just fine and it make sense (I heard that heroku dynamically assigns the port). But how does the following code knows how to bind it's port, isn't it always 8000 by default ? gunicorn app.asgi Sorry for the silly question. I'm a newbie in devops stuff -
For loop iterations for two objects in same loop
I am using models.py to submit one file with different attributes as month and year, when the user passes month and year, then it should match with the objects in database and return the file. I appended all the files in a dictionary and returned it to the HTML. But its not displaying the result #views.py from django.shortcuts import render from .models import Results def allresults(request): results = Results.objects.all() mon = request.POST['mahina'] yea = request.POST['saal'] if (mon == 'all'): pdf_url = {} for i in results: m = i.month y = i.year f = i.file u = f.url if (yea == y): pdf_url[f] = u pl = pdf_url.items() return render(request, 'results/allresults.html', {'y': yea, 'pl': pl}) #models.py from django.db import models class Results(models.Model): date = models.CharField(max_length=255) title = models.CharField(max_length=255) month = models.CharField(max_length=22) year = models.IntegerField() file = models.FileField(upload_to='file/') def __str__(self): return self.date {% for i,j in pl %} <div class="media text-muted pt-3 mb-2" style="background-color: #e6f2ff;"> <img src="{% static 'arrow.png'%}" width="36" height="36" alt="" style="margin-top: 8px;" class="mr-2 rounded"> <p class="media-body pb-3 mb-0 lh-125 border-bottom border-gray" style="text-indent: 1em; margin-top: 10px;"> <strong style="font-size: 16px; color: #990000;">@ result.date </strong><span style="color: #990000">&#8287;&#8287;&#8287;&#8287;&#8287;&#8287;&#8287;&#8287;&#8287;&#8287;<strong style="font-size: 18px; font-family: 'Hind', sans-serif;"> result.title </strong></span><span style="float: right;"><a href="{{ j }}"><img src="{% static 'pdf.jpg'%}" … -
I want to save dynamic data when moving to another page
I want to save dynamic data when moving to another page. What you are doing is drawing a graph on the canvas, and if you want to save the node and edge information in the canvas and write it out when you want, what method should you use? I use Django, Python, PHP, jQuery, etc. I use diagram-builder in Alloy-UI, I want save this canvas Data. <div id="yui_patched_v3_18_1_1_1557380115692_770" class="diagram-node-task yui3-widget yui3-overlay diagram-node yui3-widget-positioned yui3-widget-stacked diagram-node-selected diagram-node-focused" tabindex="1" data-nodeid="diagramNode_field_task780" style="height: 70px; width: 70px; left: 132px; top: 124px; z-index: 100;"> <div id="yui_patched_v3_18_1_1_1557380115692_772" class="diagram-node-content yui3-widget-stdmod yui3-widget-content-expanded"> <div class="yui3-widget-bd" style="height: 70px;" id="yui_patched_v3_18_1_1_1557380115692_987"> <div style="position: absolute; left: 0px; top: 0px; visibility: visible; width: 70px; height: 70px;" id="yui_patched_v3_18_1_1_1557380115692_986"> <svg:svg pointer-events="none" overflow="auto" id="yui_patched_v3_18_1_1_1557380115692_855" width="77" height="77" viewBox="-7 -7 77 77" style="position: absolute; top: -7px; left: -7px; overflow: auto; visibility: visible; width: 77px; height: 77px;"> <svg:rect id="yui_patched_v3_18_1_1_1557380115692_859" pointer-events="visiblePainted" shape-rendering="auto" width="55" height="55" x="0" y="0" fill="none" stroke-dasharray="none" stroke="transparent" stroke-linecap="butt" stroke-width="7" stroke-opacity="0" stroke-linejoin="round" transform="matrix(1,0,0,1,8,8)" style="left: 0px; top: 0px;" class="yui3-shape yui3-svgShape yui3-rect yui3-svgRect diagram-node-shape-boundary"> </svg:rect> </svg:svg> </div> </div> </div> <div class="diagram-node-label">task780</div> <div class="diagram-builder-controls"> <div id="yui_patched_v3_18_1_1_1557380115692_950" class="btn-toolbar-content yui3-widget component btn-toolbar"> <button type="button" class="btn btn-default"> <span class="glyphicon glyphicon-remove"> I want save node data, and load this data another page. -
Use one or more endpoints for 1 django app
Im working on a web application. single-page. There are different elements of the site, which reload data or do mathematical operation on it (in the backend). --> this data doas only appear as "meta-data" in the menu of the site. All received data shown in the menu are always used to create one or more charts/plots. Question: I get different type of data. Should I use multiple endpoints like .../get_data_type1/.... .../get_data_type2/... ... or should I use 1 general endoint .../get_data/... and use IF and ELSE in the code, to figure out, which data is requested? -
How to put a alert error message in django?
I have actually followed this tutorial to perform ajax request on error in form field. Then I performed the following: My models: class Company(models.Model): user = models.ForeignKey(User,related_name="Company_Owner",on_delete=models.CASCADE,null=True,blank=True) name = models.CharField(max_length=50,blank=False) financial_year_from = models.DateField(max_length=100,choices=financial_date,default=datetime.date((datetime.datetime.now().year),4,1), blank=False) gst_enabled = models.BooleanField(default=False) composite_enable = models.BooleanField(default=False) My views: def validate_gst_billing(request): data = { 'is_enable' : Company.objects.filter(gst_enabled = False,composite_enable = True) } if data['is_enable']: data['error_message'] = 'To enable composite billing GST should be enabled' return JsonResponse(data) In my html: <script> $("#id_composite_enable").change(function () { var form = $(this).closest("form"); $.ajax({ url: form.attr("data-validate-gst-billing-url"), data: form.serialize(), dataType: 'json', success: function (data) { if (data.is_enable) { alert(data.error_message); } } }); }); </script> I want to throw an error message to the users as an alert if they try to submit a form with the gst_enable field set to False and the composite_enable field set to True. Any idea what is wrong in my code? Thank you -
Custom fields in Custom User model not showing up while creating user in admin
I am using a custom user model with an extra field 'uid'. While i am trying to create a new user from the admin page, the uid field is not showing up. I've created a custom user create and update form.please see the code below. models.py from django.db import models # Create your models here. from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): uid = models.CharField(max_length=50) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): uid = forms.CharField(label = "uid") class Meta(UserCreationForm): model = CustomUser fields = ('username', 'password', 'uid') def save(self, commit=True): user = super(UserCreateForm, self).save(commit=False) user.uid = self.cleaned_data["uid"] if commit: user.save() return user Did i miss something or am i doing it wrong? please help. -
Does this `if` condition ever runs?
I am reading some codes and I am confused here: class PostListView(ListView): # compressed def get_context_data(self, **kwargs): session_key = 'viewed_topic_{}'.format(self.topic.pk) # <-- here if not self.request.session.get(session_key, False): self.topic.views += 1 self.topic.save() self.request.session[session_key] = True # <-- until here kwargs['topic'] = self.topic return super().get_context_data(**kwargs) so the if condition checks that if there is no session with that key then increment self.topics.view by one. I am confused here because whenever a user log in to the website their session will be created automatically and there are zero chances for being no session unless a user doesn't log in to the website. (Please notice that this project doesn't allow unauthenticated users to view the home page, sign in is a must.) Is this if condition will ever be executed? -
django setup in apache +centos 7
I tried to used Django in my dedicated server and I got few issues if anybody can help me to setup Django in apache server using centos 7 python run in y server and when I use "Django run server" in port 0.0.0.0:8000 after active source its work well but I cannot run Django in my apache server I thought the issue may be because I don't have WSGI but I don't know even how to set it up I run this comment in my root "pip install mod_wsgi" DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. Collecting mod_wsgi Using cached https://files.pythonhosted.org/packages/47/69/5139588686eb40053f8355eba1fe18a8bee94dc3efc4e36720c73e07471a/mod_wsgi-4.6.5.tar.gz ERROR: Complete output from command python setup.py egg_info: ERROR: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-f6NC1P/mod-wsgi/setup.py", line 168, in <module> 'missing Apache httpd server packages.' % APXS) RuntimeError: The 'apxs' command appears not to be installed or is not executable. Please check the list of prerequisites inthe documentation for this package and install any missing Apache httpd server packages. ---------------------------------------- ERROR: Command … -
Django celery crontab not working when CELERY_TIMEZONE='Asia/Calcutta'
I am tyring to schedule a task in Django using celery.Everything works fine when the CELERY_TIMEZONE='UTC' but doesnt work when I change the CELERY_TIMEZONE='Asia/Calcutta'. #settings.py CELERY_TIMEZONE='UTC' CELERY_ENABLE_UTC = True #tasks.py @periodic_task(run_every=crontab(day_of_month="1-31", hour=6, minute=8), name="newtask1") def elast(): print "test" This works just fine but when I change my settings to CELERY_TIMEZONE='Asia/Calcutta' CELERY_ENABLE_UTC = False #tasks.py @periodic_task(run_every=crontab(day_of_month="1-31", hour=11, minute=38), name="newtask1") def elast(): print "test" This doesn't work.I can't seem to figure out the issue.Am I missing something? Any help would be appreciated. -
User become Anonymous when Redirect to View with Method Decorator
I have an app in my Django project that checks with a user is authenticated before accessing a view and redirecting them to a login view if not. I am encountering an issue were users may cookies that designate them as special users who should be able to view the page. In my code for the login page, in first access they may not be authenticated, so a method decorator will be redirected to the login page, which will check for the tokens and then redirect them page to the requested page. The problem I am encoutering is that even after authenticating the user on the login page, when redirecting them they are appearing as anonymous user in the decorator. Can anyone explain why this is occuring. Code for review: def login_required(function=None, login_url='/login/', redirect_field_name='next'): actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator @method_decorator(login_required, name='dispatch') class DataViewSet(viewsets.ModelViewSet): pass class FormLoginView(FormView): # Form stuff omitted template_name = 'login.html' form_class = LoginForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if request.user.is_authenticated: context['JWT'] = self.request.user.get_token() return context def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated: try: # Find token request.user = auth.authenticate(request, token=token) except jwt.InvalidTokenError: token = None … -
Django - How do i check whether a date has expired inside filter condition
How do i check whether a date has expired or not with respect to today in filter condition. eg: task = Task.objects.filter(job=obj, status__in = ["in-progress","assigned"],Q(to_be_completed_by_date_until__gte =datetime.now()) This results in error, I want to know how to_be_completed_by_date has to be handled so that it will give the results to_be_completed_by_date<datetime.now() is True -
How to send file attachment on google drive using django?
I want upload large size file to google drive using django. Is it possible ? If not ,what is the solution ? -
After migration data is not saving correctly
I am using latest version of django, django-mptt. Here is the model in previous state: shop_options = ( ('grocery', _('Grocery')), ('medicine', _('Medicine')), ('electronics', _('Electronics')), ('fashion', _('Fashion')), ('garden', _('Garden')), ('gift', _('Gift')), ) class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) name_bn = models.CharField(max_length=50, unique=True) active = models.BooleanField(default=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.PROTECT) slug = models.SlugField(max_length=200, db_index=True) shop_type = models.CharField(choices=shop_options, max_length=40) class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = ('parent', 'slug',) verbose_name_plural = 'categories' def save(self, *args, **kwargs): if not self.id: # Newly created object, so set slug self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) Everything is working correctly at this point. Then I added two more shop_options shop_options = ( ('grocery', _('Grocery')), ('medicine', _('Medicine')), ('electronics', _('Electronics')), ('fashion', _('Fashion')), ('garden', _('Garden')), ('gift', _('Gift')), ('baby_care', _('Baby Care')), ('pet_care', _('Pet Care')), ) Then generated migration and successfully migrate this changes. Now when I want to change a previously saved category object from grocery/fashion (anything) to baby_care or pet_care it is saving as gift . Here is the auto generated migration file: # Generated by Django 2.2.1 on 2019-05-08 17:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0074_auto_20190425_2236'), ] operations = [ migrations.AlterField( model_name='category', name='shop_type', field=models.CharField(choices=[('index', 'Index'), ('grocery', 'Grocery'), ('medicine', … -
Is it possible to embed an ArrayModelField inside ArrayModelField?
I'm working on a project using django connecting to a MongoDB database using djongo. I have a few models and a few abstract models that I embed as ArrayModelFields. However when I try to use an ArrayModelField inside a model that is in-turn referenced as an ArrayModelField I get a 'nonetype' object is not iterable (not sure why). I've gotten the system to work by combining the two models (Grade & Detail) into one in this case (after realizing the Grade model didn't need to exist) but is it possible at all to do what I wanted to do initially? Before I've tried various embedding options for lists and arrays as listed in the djongo documentation but nothing else works. class Grade(models.Model): kihon_Grade = models.CharField(max_length = 2, null = True) kata_Grade = models.CharField(max_length = 2, null = True) kumite_Grade = models.CharField(max_length = 2, null = True) class Meta: abstract = True class Detail(models.Model): member = models.ForeignKey(to = Member, on_delete = None) rank = models.CharField(max_length = 10, null = True) grade = models.ArrayModelField(model_container = grade, null = True) result = models.CharField(max_length = 10, null = True) class Meta: abstract = True class Grading(models.Model): _id = models.ObjectIdField() examiner = models.CharField(max_length = 25, … -
Django REST framework: type object X has no attribute 'get_extra_actions'
Ubuntu LTS, Python 3.6.x, Django 2.2.1, DRF 3.9.3 I started with the DRF quickstart. Worked fine. Jumped into the DRF tutorial, step 3 on using generic class based views I'm getting this error when trying manage.py runserver File "/home/ubuntu/src/rasi/rais/instances/urls.py", line 11, in <module> path('api/', include(router.urls)), File "/home/ubuntu/.virtualenv/managed-research-prod/lib/python3.6/site-packages/rest_framework/routers.py", line 125, in urls self._urls = self.get_urls() File "/home/ubuntu/.virtualenv/managed-research-prod/lib/python3.6/site-packages/rest_framework/routers.py", line 386, in get_urls urls = super(DefaultRouter, self).get_urls() File "/home/ubuntu/.virtualenv/managed-research-prod/lib/python3.6/site-packages/rest_framework/routers.py", line 284, in get_urls routes = self.get_routes(viewset) File "/home/ubuntu/.virtualenv/managed-research-prod/lib/python3.6/site-packages/rest_framework/routers.py", line 200, in get_routes extra_actions = viewset.get_extra_actions() AttributeError: type object 'InstanceList' has no attribute 'get_extra_actions' I've only made the minimal changes to my code base in order to implement the recommendations by the tutorial. It's not obvious what I've done wrong, and there's not a lot of information around get_extra_actions when I read the ListCreateAPIView guide, and not a lot that seems obviously comparable when looking elsewhere urls.py from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'users',views.UserViewSet) router.register(r'instances',views.InstanceList) urlpatterns = [ path('', views.dash, name='dash'), path('api/', include(router.urls)), ] models.py class User(AbstractUser): email = models.EmailField() dept = models.CharField(max_length=400) display_name = models.CharField(max_length=200) class Instance(models.Model): name = models.CharField(max_length=200) flavour = models.CharField(choices=FLAVOUR_CHOICES, max_length=20) os = models.IntegerField(choices=OS_CHOICES) hostname = models.CharField(max_length=200) allocation_manager = models.ForeignKey( … -
How to create a tree-view in vue-js?
How to create a tree-view in vue-js? It is currently building a tree with a vue. You want to query the DB to get the data and create a tree structure in vue. DB data here vue section mounted: function() { axios.get('{% url "todo:get_todo" %}') .then(function (response) { for(var d in response.data) { var item = response.data[d]; console.log("test-1234=="+JSON.stringify(item)); if(item.isLeaf == 'false'){ var node = new VueTreeList.TreeNode({ name: item.name, isLeaf: false }) if (!vm.data.children) vm.data.children = [] vm.data.addChildren(node) console.log("test-9988=="); }else{ vm.data.push(item); } } }) .catch(function (error) { console.log(error); }) .then(function () { }); }, Result This is not the result I want. I want test1, test2 in the node. I want to be like the picture below. What should I do? -
Django Migrations won't create new table Store_item
I ran into an issue when I set a bad default to an array field in my Model called "Item" in app "store". Essentially, I made the default for the array field a word and it wanted brackets, I formatted it wrong. To fix this issue, because i could no longer migrate new migrations without receiving an error in regard to the issue above, I decided to manually remove store_item table from my postgres database, delete all migrations, and completely remove the array field in the item model. Problem solved.. I can not migrate and runserver fine... The new problem is when I run makemigrations, it tries to create a new table for Item called store_item, but it never actually creates the table in my database, once I run migrate successfully. # Generated by Django 2.0.8 on 2019-05-09 04:57 from django.conf import settings import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Item', fields=[ ('is_active', models.BooleanField(db_index=True, default=True, help_text='Designates whether this item should be treated as active. Unselect this instead of deleting data.')), ('created_time', models.DateTimeField(auto_now_add=True, verbose_name='created time')), ('modified_time', models.DateTimeField(auto_now=True, verbose_name='last modified time')), ('id', models.BigAutoField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=25)), … -
Can't display map on template using PointField django
Can we display map on template using django PointField. I have a model with one PointField and then after creating a model form I want to display the map in my template using that form. View def map_view(request): form = ShopForm() context = { 'form' : form } return render(request, 'ads/map.html', context) Template <html> <head> </head> <body> <div> <form method="post"> {{ form }} <input type="submit" > </form> </div> </body> </html> I was wondering is it possible to display the map using that or do I need to something extra. -
To test 500.html in Django dev, localhost environment
I am customizing 500.html and set Debug to False, so it renders 500 error but as Debug is set to False, it cannot render the static files correctly. How can I set it to the production mode and test the 500 error page correctly? or how can I set static files correctly when debug is false? -
The current path, post/1/{% url 'post_edit' post.pk}, didn't match any of these
I am learning Django and am currently trying to use a button to edit a form. I bought a book and coded exactly what the book says and even copied and pasted the code from the author's github and it still doesn't work. I get the error "The current path, post/1/{% url 'post_edit' post.pk}, didn't match any of these." from django.urls import path from .views import ( BlogListView, BlogUpdateView, BlogDetailView, BlogCreateView, ) urlpatterns = [ path('post/<int:pk>/edit/', BlogUpdateView.as_view(), name='post_edit'), path('post/new/', BlogCreateView.as_view(), name='post_new'), path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), path('', BlogListView.as_view(), name='home'), ] I am expecting this to open a page to edit a form of a blog that was posted. -
Can a model have a list of ForeignKey objects?
I want to create a relationship between Shops and Categories where a shop might have multiple categories and was thinking how possible it is to create a list of Category objects in a variable inside the Shop object. Or what is the better approach? class Category(models.Model): ... class Shop(models.Model): categories = list(models.ForeignKey(Category,...)) ... -
How can I call a Python function from a form in Django?
I'm trying to call a function from a form in one of my templates to calculate a value in a Django project. The function is in pyhton. This is the way I'm doing it. I am keeping myScript.py in the app folder where views.py is template.html ... <button type="submit" class="btn btn-primary" value="nonlBis" name="bisBtn">Submit</button> ... views.py from app.myScript import * ... def Functions(request): if(request.GET.get('nonlBis')): print(myScript.myFunction()) -
Making all words starting with "@" and "#" clickable
I'm creating a project that allows users click on words that start with "#" and "@" i managed to get the one for hashtag working but when i try to implement both at the same time there's a problem I used regular expression operations to return the value and mark_safe because its an html tag In the template tag_files i did this def create_hashtag_link(tag): url = "/hash/?hash={}".format(tag) # or: url = reverse("hashtag", args=(tag,)) return '<a href="{}">#{}</a>'.format(url, tag) @register.filter() def hashtag_links(value): return mark_safe( re.sub(r"#(\w+)", lambda m: create_hashtag_link(m.group(1)), escape(value))) def create_mention_link(mention): link = "/mention/?user={}".format(mention) return '<a href="{}">{}</a>'.format(link, mention) @register.filter() def mention_link(value): return mark_safe( re.sub(r"@(\w+)", lambda x: create_mention_link(x.group(0)), escape(value))) In the template i did this {{ post.content|truncatewords:"19"|mention_link|hashtag_links }} -
How do I modify my Django settings for AWS Static files to accoomade for django summernote
I am using django-summernote as a wysiwyg editor. The editor works fine in my development stage. Where my Django setting is using the below code STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' However the moment I switch to production where my static files are saved on AWS. I do not see the summernote wysiwyg editor. Infact the the entire text-field disappears. Also My static files are working perfectly with everything else. My style.css file on my aws is the exactly the same as my dev stage below are are my AWS settings AWS_DEFAULT_ACL = None STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] DEFAULT_FILE_STORAGE = 'aws_storage_classes.MediaStorage' AWS_STORAGE_BUCKET_NAME = 'khal-media-8axodgh6d' STATICFILES_STORAGE = 'aws_storage_classes.StaticStorage' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_DOMAIN = "%s.s3.amazonaws.com" % AWS_STORAGE_BUCKET_NAME STATIC_URL = 'https://%s/static/' % AWS_S3_DOMAIN MEDIA_URL = 'https://%s/media/' % AWS_S3_DOMAIN ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' How can I fix this. Please let me know if you need more info. I would be more than happy to provide -
POST object in form directly
Is it possible to save an object through django html form as a value in option tag directly? <select class="form-control" name="person"> <option selected disabled>Choose</option> {% for person in group %} <option value="{{ person }}">{{ person.name }}</option> {% endfor %} </select> class Group(models.Model): group_name = models.CharField(max_length=255, blank=True) person = models.ForeignKey(Person, on_delete=models.CASCADE) def __str__(self): return self.group_name Tried the above but I get "didn't return a HttpResponse object". I know I can pass an ID but is it possible to save the object directly instead of going to views.py and getting the object via an ID?