Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Get status of subprocess (running/finished) initiated from one view and display it to another view
I want to start a subprocess from a specific url (say eg: 'localhost:8000/start'). The status of subprocess (ie., subprocess is running or finished) should be showed on another url (say eg: 'localhost:8000/status'). I already started the subprocess. But I am struggling to display the status in other url. Is there any way to achieve this? -
Redirect from bootstrap tab to another Django
I have two tabs in a template.In one tab I can create attendance(tab1) in another tab I can view attendance(tab2) that was created previously.Now when I create a attendance successfully I want to check if the attendance is valid and if valid I want to redirect from tab 1 to tab 2. How can I achieve this in Django? Here's my template and view snippet https://gist.github.com/quantum2020/c55adeb3b8c2ee0ac2d99ff46f5699e8 https://gist.github.com/quantum2020/2cb28233608c3a219ff97762e1fd62be -
Django admin exclude in proxy model
Currently i have this user proxy model: class UserProxy(User): class Meta: verbose_name = 'Staff' verbose_name_plural = 'Staffs' proxy = True And on the admin side i have the following admin like so: class StaffAdmin(UserAdmin): def get_queryset(self, request): qs = super(StaffAdmin, self).get_queryset(request) return qs.filter(is_staff=True) exclude = ('first_name', 'last_name',) def save_model(self, request, obj, form, change): if request.user.is_superuser: obj.is_staff = True obj.save() admin.site.register(UserProxy, StaffAdmin) When i go to any form of the proxy model on admin it return the following error: "Key 'first_name' not found in 'UserProxyForm'. Choices are: date_joined, email, groups, is_active, is_staff, is_superuser, last_login, password, user_permissions, username." I figured that was weird and i tried to only exclude is_staff and now it return: "Key 'is_staff' not found in 'UserProxyForm'. Choices are: date_joined, email, first_name, groups, is_active, is_superuser, last_login, last_name, password, user_permissions, username." Why is this happening ? isn't the proxy model should have all the fields from base model ? -
How to integrate my django app with django cms properly?
Here I am trying to integrate my app with django cms. First I created a new page from cms with some title and provided a template for this page.Now in this template generated by cms I want to display dynamic objects from database so I created new django app with writing models and views like this.Bu it is not displaying any objects from database in this cms template. What I am missing here ? But If I put this view url in some other template like this <a href={% url '..' %} then it works but not with the cms template. settings.py 'djangocms_video', 'project', 'myapp_cms_integration', 'myapp', myapp/views.py def view_objects(request): objs = Model.objects.all().order_by('-created') return render(request, 'template', {'objs': objs}) myapp_cms_integration/cms_apps.py from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool @apphook_pool.register # register the application class MyApphook(CMSApp): app_name = "myapp" name = "MY Application" def get_urls(self, page=None, language=None, **kwargs): return ["myapp.urls"] app/template {% for obj in objs %} {{obj.title}} {% endfor %} -
Create superuser using python manage.py customize the message in Django
In a project requires the user name is autogenerated code. For that, I made a custom user model as described requirements. All is working fine but the problem is when I am trying to create superuser using python manage.py createsuperuser As I described the username is an auto-generated field. But the console asking me for the user name. After creating a superuser account the user code will need to print out as I need code for login along with superuser is created successfully. How can I gain this functionality? I search on google but I can't find any suitable solution. Here is my model: class User(AbstractBaseUser, PermissionsMixin): """Custom user model""" code = models.CharField(max_length=20, unique=True, blank=False) email = models.EmailField(max_length=255, unique=True, null=True) name = models.CharField(max_length=255) address = models.CharField(max_length=255, blank=True) nid = models.CharField(max_length=30, blank=True) profile_pic = models.CharField(max_length=255, blank=True) gender = models.CharField(max_length=10, choices=[('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other')]) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'code' REQUIRED_FIELDS = ['name'] Here is my Custom User manager: class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, password, **extra_fields): """Create new user with auto-generated code and password""" if 'name' not in extra_fields.keys(): raise ValueError('Name must be needed') code = code_generator.generate_employee_code(extra_fields['name'][:2]) user = … -
Django dbbackups : ModuleNotFoundError: No module named 'django.utils.six'
I am upgerading my Django app from 1.11 to v3 and I get the following error: (python 3.8) File "/env/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/env/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/env/lib/python3.8/site-packages/dbbackup/apps.py", line 15, in ready from dbbackup import checks File "/env/lib/python3.8/site-packages/dbbackup/checks.py", line 3, in <module> from django.utils.six import string_types ModuleNotFoundError: No module named 'django.utils.six' My requirements.txt has the following entry: Django~=3.0 django-dbbackup==3.2.0 django-guardian==2.2.0 django-nose==1.4.5 humanfriendly requests Any help would be much appreciated. Thanks. -
Including models inside Inline Models in Django
Is it possible to add models inside inline models in Django? I have 3 models as below class Platform(models.Model): platformId = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) class Partner(models.Model): platform = models.ForeignKey(Platform,on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.TextField() class Inventory(models.Model): partner = models.ForeignKey(Partner, on_delete=models.CASCADE) display = models.BooleanField(default=False) In admin, I added Partner as inline in Platform as below from django.contrib import admin from .models import Platform, Partner, Inventory class PartnerInline(admin.StackedInline): model = Partner extra = 1 class InventoryInline(admin.StackedInline): model = Inventory extra = 1 class PlatformAdmin(admin.ModelAdmin): inlines = [ PartnerInline ] Now what I want is to add the InventoryInline as part of the partner. Is it Possible? That means when I add a partner I want to add inventory for each partner. Inline inside and inline. Is this possible? Or is there any other way to achieve this? I am new to Django -
I am trying to show up the media files on the page, in django ,that has been uploaded by the user but it is showing this error?
The error that it is showing. While i want to show the product through prduct id -
how to validate users entry to make user a user doesn't add a 'space' in django
here's my code class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name=_('email address'), max_length=255, unique=True ) username = models.CharField(_('username'), max_length=30, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) am trying to prevent a user from typing space when filling the username field -
django : py manage.py runserver command doesnt work
I installed python 3.8.1 and django 3.0.3 Following tutorials I already created project but couldnt run server PS D:\Study\django> django-admin startproject mysite PS D:\Study\django> py --version Python 3.8.1 PS D:\Study\django> py -m django --version 3.0.3 PS D:\Study\django> cd .\mysite\ PS D:\Study\django\mysite> py .\manage.py runserver PS D:\Study\django\mysite> py .\manage.py runserver PS D:\Study\django\mysite> I read similar questions here, nothing doesnt help. What's the issue? -
nginx: [emerg] open() "/etc/nginx/sites-enabled/leptitox_pro" failed (2: No such file or directory) in /etc/nginx/nginx.conf:62
I am practicing to host a Django website on digitalocean. I am facing this issues: john@ubuntu1:~/pyapps/Leptitox-Project$ sudo nginx -t nginx: [emerg] open() "/etc/nginx/sites-enabled/leptitox_pro" failed (2: No such file or directory) in /etc/nginx/nginx.conf:62 and when I navigate to /etc/nginx/sites-enabled/ I see this: john@ubuntu1:/etc/nginx/sites-enabled$ ls /etc/nginx/sites-enabled/ leptitox-Project btre_project default leptitox_pro lexptitox_pro Since, it is my first time deploying a website I made some mistakes and made bunches of folders, however I only want to use Leptitox-Project and want to delete all others and don't use them. So I tried to remove btre_project and leptitox_pro with rm -rf leptitox_pro but I get a permission denied. Please help me solve this. Thank You! -
In django, hashtag is not matching with the urls
My urls is not matching with the hashtags. it says 404 url not found. this is my base.html with hashtag: $(document).ready(function() { $("p").each(function(data) { var strText = $(this).html(); console.log('1. strText=', strText); var arrElems = strText.match(/#[a-zA-Z0-9]+/g); console.log('arrElems=', arrElems); $.each(arrElems, function(index, value){ strText = strText.toString().replace(value, '<a href="/tags/'+value+'">'+value+'</a>'); }); console.log('2. strText=', strText); $(this).html(strText); }); }); my hshtag models.py: from django.db import models from blog.models import post # Create your models here. class HashTag(models.Model): tag = models.CharField(max_length=120) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tag def get_postss(self): return post.objects.filter(content__icontains="#" + self.tag) this is my hashtag view: from django.shortcuts import render from django.views import View from .models import HashTag # Create your views here. class HashTagView(View): def get(self, request, hashtag, *args, **kwargs): obj, created = HashTag.objects.get_or_create(tag=hashtag) return render(request, 'hashtags/tag_view.html', {"obj": obj}) i put the url intothe primary url of my site: from hashtags.views import HashTagView from django.urls import path, re_path, include urlpatterns = [ re_path(r'^tags/(?P<hashtag>.*)/$', HashTagView.as_view(), name='hashtag'), ] -
Standalone Django Api & React (CSRF)
After reading most of the post about react and django. I decided to create a standalone Django Api(Backend) & React (Frontend) When both of these is standalone, how should I get CSRF token from the Django Api? Do I need to construct a dedicated url for React to call and get the token and store it in the cookies? What is the best practice for this case? -
jquery is not picking up the input values which are from django form
I have a django form which I'm using to post the data of the item, status and id class TemplateDataForm(forms.ModelForm): item = forms.CharField(widget=forms.TextInput(attrs={'id':'temp_item'})) status = forms.ChoiceField(label='', choices=CHOICES, widget=forms.Select(attrs={'id':'status'})) class Meta: model = TempData fields = ['item','status'] I"m passing the attrs like id to the fields in the forms <form method='post' id='js-temp-data'> {% csrf_token %} {% for hidden_field in temp_data_form.hidden_fields %} {{hidden_field.errors}} {{hidden_field}} {% endfor %} <div class="form-row align-items-center"> {% for field in temp_data_form.visible_fields %} <div class="col-auto"> {{field.label_tag}} {{field.errors}} {{field}} {{field.help_text}} </div> {% endfor %} <div class="col-auto"> <input type="hidden" id='js_template_id_new' name="" value="{{temp_obj_for_template.id}}"> <!-- <input type="image" src="{% static 'components/plus1.png'%}" width=15 heigth=15 name="submit" alt='Submit' value="Add"> --> <input type="submit" id='js-temp-data-submit' value="submit" name=""> </div> </div> </form> I"m using the css id of the input tags in below Jquery but it's not picking up the input values and posting empty response for title and id <script type="text/javascript"> $(document).ready(function(){ $('#js-temp-data-submit').click(function(e) { e.preventDefault(); $.ajax({ type:'POST', url:'{% url "checklist" %}', data:{ item:$('#temp_item').val(), //not working id:$("#js_template_id_new").val(), //I'm passing the object to template from view which is working for other form but not for this status:$('#status').val(), //working csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), //working action:'post' }, success: function(response){ $("#js-temp-data").trigger('reset'); $('#js-temp-data').focus(); }, error: function(response){ alert(response["responseJSON"]["error"]) } }); }); }); </script> The below is the output of the … -
In my model positive_keywords,negative_keywords,neutral_keywords are stored in model as json how to decode it into python objects
This is my model class Review(models.Model): def __init__(self, id, comment, *args, **kwargs): super().__init__(*args, **kwargs) self.review_id = id self.review_data = comment review_id = models.CharField(max_length=100, default="", editable=False) review_data = models.CharField(max_length=1000) sentiment_score = models.FloatField() positive_keywords = models.TextField(null=True) negative_keywords = models.TextField(null=True) neutral_keywords = models.TextField(null=True) finding sentiment_score code class review_sentiment_analysis: def cleanAndProcessData(sentence): print('analysing sentence ' + sentence); comment = sentence.lower(); keywords = word_tokenize(comment) keywords = [c for c in keywords if c not in string.punctuation] keywords = [w for w in keywords if w not in stopwords.words('english')] lematizer = WordNetLemmatizer() keywords = [lematizer.lemmatize(w) for w in keywords] stemmer = PorterStemmer() keywords = ' '.join([stemmer.stem(w) for w in keywords]) return keywords; def sentiment_score(review): print("SENTIMENT...") # check feedback already exist or not if Review.objects.filter(review_id = review.review_id).exists() == False: keywords = review_sentiment_analysis.cleanAndProcessData(review.review_data) analyser = SentimentIntensityAnalyzer() sentiment_dictionary = analyser.polarity_scores(keywords) review.sentiment_score = sentiment_dictionary['compound'] bigramExtraction.bigram_sentiment_analysis(review) review.save() return review else: print("value is already exixt in database....") Review.objects.filter(review_id=review.review_id).update(sentiment_score=review.sentiment_score, positive_keywords=review.positive_keywords, negative_keywords=review.negative_keywords, neutral_keywords=review.neutral_keywords).save() -
Have the first article from a model at the top displayed
I am creating a Django blog app and I was wondering if it was possible to have the first blog post as pictured in this design. What I have done so far is that I have been able to get the bottom three articles but I have been confused on how to approach the top post. This is my template code so far: <div class="row"> <!-- Blog Entries Column --> {% for article in articles %} <div class="col-lg-4 mt-4 "> <div class="card mb-4"> <div class="card-body"> <h2 class="card-title">{{ article.title }}</h2> <p class="card-text text-muted h6"> <img class="image-size radius-of_image" src="article/{{ article.upload_image }}"> | {{ article.author }} | {{ article.created_on | date}} </p> <p class="card-text">{{article.content|slice:":200" }}</p> <a href="{% url 'Article' article.slug %}" class="btn btn-primary">Read More &rarr;</a> </div> </div> {% if forloop.counter|divisibleby:"3" and not forloop.last %} <div class="row"> {% endif %} </div> {% endfor %} </div> </div> -
How to move Django password/secret key to Windows Vault/credentials?
I have a web app developed in Django. The password and the secret key are visible inn settings.py file. I would like to hide them or store them somewhere to read it into Django. One option is Windows credentials. How can I connect the windows vault to Django? Or is there any better --more secure way to do it? -
Cómo establecer un valor por defecto a un objeto tipo DateFromToRangeFilter en django [closed]
Estoy usando un filtro de fechas en django 1.11.11, es de un proyecto de hace dos años, el filtrado se realiza correctamente, sin embargo el filtro no muestra los valores que se enviaron desde el front-end, en ves de eso muestra los "inputs" correspondientes al rango de fechas vacíos. Quiero poder asignar valores por defecto desde el backend si es posible en la views.py pero hasta ahora no he podido. Más o menos tengo lo siguiente: filters.py class PolicyNewActivesFilter(django_filters.FilterSet): ini_between = django_filters.DateFromToRangeFilter(name='start_date', label='Fecha de inicio (rango)') class Meta: model = Policy fields = ['ini_between',] views.py def policy_new_active_view(request) data = request.GET.copy() pol_filter = PolicyNewActivesFilter(data) pol_filter.form.fields["ini_between"].widget.widgets[0].value = ["01/01/2020", "02/02/2020"] ... return render(request, 'operation/policy_list.html', {'table': table, 'policy_filter': pol_filter}) Y en el template puedo acceder a los valores del filtro así: policy_list.html {{policy_filter.form.ini_between.value}} Y lo que muestra es: [None, None] Quiero saber si hay alguna forma de hacer esto(aunque lo que yo pongo aquí no me funcionó): pol_filter.form.fields["ini_between"].widget.widgets[0].value = ["01/01/2020", "02/02/2020"] -
how to use: RequestContext and context processor in django 3.0.2 i want to use contextrequest in django 3.0.2 in my code:
from django.shortcuts import render_to_response from django.template import RequestContext def custom_proc(request): "A context processor that provides 'app', 'user' and 'ip_address'." return { 'app': 'My app', 'user': request.user, 'ip_address': request.META['REMOTE_ADDR'] } def view_1(request): # ... return render_to_response('template1.html', {'message': 'I am view 1.'}, context_instance=RequestContext(request, processors=[custom_proc])) def view_2(request): # ... return render_to_response('template2.html', {'message': 'I am the second view.'}, context_instance=RequestContext(request, processors=[custom_proc])) -
Django- [WinError 10013]
I have started to learn Django and I am using my Employer's laptop, when I execute python manage.py runserver in Anaconda prompt, I am getting the following error, Thanks in Advance for any help or suggestion. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. February 11, 2020 - 09:08:16 Django version 2.2.3, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Error: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions``` -
Return true doesn't work for jquery on button click
I have a Javascript code that returns true if a certain checkbox is checked. document.getElementById("accept").addEventListener("click", function(event){ if(document.getElementById('hck').checked == false){ event.preventDefault(); } else { return true; } }); This is the Javascript code <input class="btn btn-success btn-lg mx-auto btnac" type="submit" id="accept" name="accept" value="Accept"> This is the button and it's inside a form. I had put in two print statements earlier to see if it enters the clauses, and it does, but it doesn't go to the Django function and return the appropriate page on return true. -
Rendering a Django HTML template to a PDF using the primary key for just one object in the model
I have a model that I want to generate a detail view for to create a PDF and can not seem to get it working to render just one object from the database using the primary key from the request. I think it has something to do with how I am generating my data variable in the view. I can get the PDF to create but I can't seem to get the details to render for a single object. my code views.py class GeneratePdf(DetailView): model = Runs def get(self, request, pk, *args, **kwargs): runset = Runs.objects.get(pk=self.kwargs.get('pk')) data = { 'runset': runset, } pdf = render_to_pdf('Runs/pdf.html', data) return HttpResponse(pdf, content_type='application/pdf') pdf.html <p>{{ object.run }}</p> <p>{{ object.driver }}</p> <p>{{ object.truck }}</p> <p>{{ object.trailer1 }}</p> render to pdf function from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None -
Cant create CSV file with django although already copaste from the documentation
So i try to follow the documentation from django itself how to create CSV file, i copaste the code but it didnt work , it should be the browser download the somefilename.csv when it success , is there anything wrong? or do i need to set something in settings.py? import csv def export_script(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' print("halo") writer = csv.writer(response) writer.writerow(['First row', 'Foo', 'Bar', 'Baz']) writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) return response -
Pre-populate edit view with multiple Images?
Hey everyone i'm working on an edit view. I have a Listing form and an Image form. My image model has a ForeignKey to the Listing model. class Images(models.Model): image = models.ImageField(upload_to=get_image_filename, verbose_name='Image') listing = models.ForeignKey(Listing, on_delete=models.CASCADE) My View looks like this def listhome_update(request, pk): listing = get_object_or_404(Listing, pk=pk) listing_form = ListingForm(request.POST or None, instance=listing) image_form = ImageForm(request.POST, request.FILES) the actual listing info is populating, But how am i able to get the images to populate as well, so my image form is not null, which is causing errors to occur? -
Render a view with arguments from a HTML form
I would like to query using a HTML form from a template, for example: index.html, and render the data in a different template, results.html. This was the solution for this same problem but in 2011 (I'm working with the newest version of Django so this is not working anymore) <form class="body_form" method="GET" action="{% url 'results' 'var_name' %}" autocomplete="off"> <input name="var_name" type="text"> Post: Django - is not a registered namespace Is the syntax in the form field or in the input field right or this is an obsolet? I have the following error when I try this: Reverse for 'results' with arguments '('var_name',)' not found. 1 pattern(s) tried: ['results'] views.py def results(request,var_name): context = {'var': var_name,} return render(request, 'results.html', context) urls.py url(r'^results', results, name="results"), Also, can I parse more than 1 variable using this method?