Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access the dynamic key in Django template?
Please see the following the code: {% for row in df_src.iterrows %} <tr > <td><input type="checkbox"></td> {% for col in columns %} <td class="redrow">{{row.1.col}}</td> {% endfor %} </tr> {% endfor %} Here in {{row.1.col}} where col can be any value like NAME, PHONE, etc. When I access it like {{row.1.PHONE}} I get the value in html, however when I access it like {{row.1.col}} nothing is shown in html. -
Post create with multiple images using FBV
Hi everyone I am new to Django I'm trying to add multiple images to my post and I am having issues. I have 2 models. One post model and One image model. My post model already has 1 imagefield. Then I have another related model which allows multiple images. Below is how my models look like class Post(models.Model): user = models.ForeignKey(User, related_name='posts') title = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) message = models.TextField() post_image = models.ImageField() class Image (models.Model): #(Images) post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', blank=True, null=True) image_title = models.CharField(max_length=100) image_description = models.CharField(max_length=250) def __str__(self): return self.post.title + " Image" Below is how my views look like. When the form loads. It has the multiple image fields. Its just not saving those images when my post is created. I get a post that completely ignores the formsets and multiple images. It only shows the Post model aspects and 1 image of the Post model. Even in the Admin there are no multiple images. Can someone point me to what is the error in my code. views.py @login_required def post_create(request): ImageFormset = modelformset_factory(Image, fields=('image', 'image_title', 'image_description'), extra=7) if request.method == 'POST': form = PostForm(request.POST, request.FILES) formset = ImageFormset(request.POST or … -
Trying to pass url in form action
I'm new in django and i'm stuck now. I'm trying to pass the url in form [action] attribute that would go to my edit function defined in [views.py] file and do it's job but whenever I try to pass the url [NoReverseMatch] is shown. This is what i tried to do: <form action="{% url 'studentapp:editrow' rowid=id %}" id="editform" method="POST"> In my urls.py I've used the following url: url(r'^editrow/(?P<rowid>[0-9]+)/$', views.editrow, name='editrow'), My [editrow] view looks something like this: def editrow(request, rowid): What i'm doing in crud is: 1) make an [edit] button in table through for loop. 2) when i click [edit] button a pre-populated form shows up(which i'm getting). 3) After i click the pre-populated form i want to edit that form and save it and updated data is reflected in my django db. -
Adding and Fetching tuples values from Django model Column
I am new to Django/DRF I am using DRF along with MySql for creating Rest APi how can i achieve below mentioned points ? Can anyone please help I had two table Booking - >> id, data, desc, services Services - >> sid, service_name, type There are two type of services Type1 and Type2 Note: there are fixed 10 services in both the Type which customer can choose while booking i had two doubt. Booking can have multiple service. so in services column i wanted to store array. [1,2,3] or comma separated services id. Now when fetching records.i want get booking id details along with services name. for example {id,data, services: [{sid,service_name}} {id:1, data:"text", services: [{1,"text1"},{2,"text2"]} -
How to add multiple users to a single auth_group in Django
I have a list of users and an auth group called 'group1'. These users are created through the bulk_create method in Django. Now I need to add all these users to group 'grop1'. I can achieve this with a for loop like: group1 = Groups.objects.get(name='group1') for user in users: group1.user_set.add(user) but I am wondering if there are any easy and better ways without using the for loop. -
Do i have to run migrate in django if i don't need admin?
I'm building small website where i will display pages as static pages not from data base. Do i have to run migrate when starting a Django project if i don't need to use Django admin interface? -
Django: output video file associated with a specific user
I have customuser model name Profile and VideoFile models with relative fields to User. There are many users account and each of them can add a lot of video files. I need to show at templates.html user.nickname and all of him videofiles. user.models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) nickname = models.CharField(max_length=30, blank=True, verbose_name="Никнэйм") userpic = models.ImageField(upload_to='userpics/', blank=True, null=True) videofile.models.py class VideoFile(models.Model): name = models.CharField(max_length=200,blank=True) file = models.FileField(upload_to="vstories/%Y/%m/%d", validators=[validate_file_extension]) date_upload = models.DateTimeField(auto_now_add = True, auto_now = False, blank=True, null = True) descriptions = models.TextField(max_length=200) reports = models.BooleanField(default=False) vstories = models.ForeignKey(User, blank = True, null = True) views.py def vstories (request): users = User.objects.all() vstories = VideoFile.objects.all() return render(request, "vstories/vstories.html", {'users':users, 'vstories':vstories}) templates.html {% extends "base.html" %} {% block content %} {% if users %} {% for user in users %} <p>{{ user.profile.nickname}}</p> {% for vstorie in vstories %} <p>{{ vstorie.vstories.url }}</p> {% endfor %} {% endfor %} {% endif %} {% endblock content %} With the video, I'm confused. Or maybe I chose the wrong way to communicate models? -
Using LetsEncrypt / Certbot with django dev server?
I'm trying to implement SSL on my dev server, purely just so I can see it working. I see from the Certbot page that Certbot works with Apache, Nginx, Haproxy and Plesk. How would I go about implementing this with Django's dev server? I'm not working in a production environment of any kind yet. -
Django 2 - reverse not found
I know there are already a hundred of these, but I have one app that I made, that works, and a new one I'm trying to make, that doesn't work. I can't redirect to my 'detail' view from my create view. If I put a number into the address, it works, it is just the redirect that doesn't work. I've tried a couple of things to no avail. I'm sure it is something simple, I just can't see it. urls.py from django.urls import path from . import views app_name = 'service' urlpatterns = [ path('', views.create_employee_profile, name='create_employee_profile'), path('<int:pk>/', views.customer_employee_profile_detail, name='detail'), ] view.py from django.shortcuts import render, redirect from service.forms import EmployeeNameForm def create_employee_profile(request): if request.POST: name_form = EmployeeNameForm(request.POST) if name_form.is_valid(): new_name_form = name_form.save() return redirect('service:detail', pk=new_name_form.pk) else: return render(request, 'service/create_or_update_profile.html', {'name_form': name_form}) else: name_form = EmployeeNameForm() return render(request, 'service/create_or_update_profile.html', {'name_form': name_form}) def customer_employee_profile_detail(request, pk): name = get_object_or_404(CustomerEmployeeName, pk=pk) return render(request, 'service/customer_employee_profile_detail.html', {'name': name} ) I've tried both 'detail' and 'service: detail' as well. Error is: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. -
In Django how i restrict is_staff member to access a url
In my web user and admin user both login from frontend. Now i want to do that some of urls are only accessed by public user only. Is_staff user not access that url. How i do that... -
From django 1.6 to 1.11: AppRegistryNotReady exception
In my REST-like API, I have a mechanism to allow users to customize models (add custom fields and add custom models). This relies on a set of models describing the customizations. Here is a simplified version of my code to show the concept. + myproject + customization . models.py class CustomModel(django.db.models.Model): # […] class CustomField(django.db.models.Model): # […] and + myproject + entities . models.py class RootEntityModel(django.db.models.Model): name = CharField(…) # […] from myproject import customization from myproject.customization.models import CustomField # Here apply the custom filters on the root entity type for custom_field in CustomField.objects.filter(entity__name='RootEntityModel').all(): customize.build_field_and_apply(custom_field, RootEntityModel) # Here instantiate custom models, etc # […] In Django 1.6, I have no problem making everything work. Now, transitionning to Django 1.11, I've had some cleanup to do, mainly because it's impossible to import a model inside the root package of an application. (see also this answer). I've eleminated every AppRegistryNotReady exception that I had, but for the one in myproject.entity.models module. You see, to build my Entities, I have to query to the CustomField and CustomModel tables, but as I'm currently building my models, Django forbids me to do so. I am stuck in this kind of circular dependency. Any thought towards … -
django - creating an instance of a model by looping through all fields and assigning a value
Suppose I have this model Person with these attributes: foo1, foo2 and foo3 Can you do something like this? fields = ['foo1', 'foo2', 'foo3'] p = Person() for field in fields: p.field = 5 p.save() -
How can i query a Primary key objects in django 2 template
after querying my database, my template doesn't display anything. Please find attached my model, url, templates MODEL class ScrumyUser(models.Model): userRole = ( ('O', 'Owner'), ('A', 'Admin'), ('Q', 'Quality Analyst'), ('D', 'Developer'), ) fullname = models.CharField(max_length=100) role = models.CharField(max_length=1, choices=userRole) class GoalStatus(models.Model): goalStatus = ( ('P', 'Pending'), ('V', 'Verified'), ('D', 'Done'), ) status = models.CharField(max_length=1, choices=goalStatus) class ScrumyGoals(models.Model): goalType = ( ('WG', 'Weekly Goal'), ('DT', 'Daily Task'), ) user_id = models.ForeignKey(ScrumyUser, on_delete=models.CASCADE) status_id = models.ForeignKey(GoalStatus, on_delete=models.CASCADE) goal_type = models.CharField(max_length=2, choices=goalType) goal_description = models.TextField() date_created = models.DateTimeField('dateCreated') date_updated = models.DateTimeField(null=True, blank=True) VIEWS from django.views import generic from .models import ScrumyGoals, ScrumyUser, GoalStatus class IndexView(generic.ListView): template_name = 'greyscrumy/index.html' context_object_name = 'goals' def get_queryset(self): return ScrumyGoals.objects.all() TEMPLATE INDEX <!-- {% if goals %} --> <!-- <h1>{{ object_list.fullname }}</h1> --> <!-- <ul> {% for goal in goals.scrumygoals_set.all %} <li><a href="{% url 'greyscrumy:index' goal.id %}">{{ goal.goal_type }}</a></li> {% endfor %} </ul> {% else %} <p>No goals are available.</p> {% endif %} --> THE SECOND DISPLAYS BUT I DON'T KNOW HOW TO ACCESS SCRUMYUSER AND GOALSTATUS PLEASE I WOULD REALLY LOVE TO UNDERSTAND THIS, I HAVE MADE SEARCHES ON GOOGLE SINCE YESTERDAY AND COULDN'T FIND ANYTHING {% for goal in goals %} {% for innergoal in goals … -
Is it overkill to use Pandas only to read excel file and convert into python dictionary?
In my Django(2.0.1), I want to read spreadsheets(excel, csv, ods) and convert it into python dictionary for processing. I was looking into django-excel but it doesn't support Django 2. Hence, I am planning to use Pandas. I want to know is it overkill to use Pandas in this scenario. I understand opinion based questions are discouraged on SO, but answer to this question can't be found in tutorial or docs. -
Dynamically created Input box value updating miss mach
I am having an application in which i am having a functionality to dynamically adding table rows on button click. Each row includes a date picker from where the user selects the particular date. please see the image here in which user selects the date from event date column using jquery datepicker. And next two fields are buy date and sell date. this is read only fields and the value of this field is set using a criteria. ie user will enter number of days in buy date and sell date on top of the box please see the image here if buy date is 5 days and sell days is 10 days , 5 days will be added to event date and printed the value in buy date field inside the rows column(ie buy date ) and 10 days are added to event date and printed in sell date column inside the table rows(ie sell date). now it is working fine. And when a user adds more than 2 rows and tries to change the date in second row again sell date and buy date of 3 rows gets updated instead of second row. Please help me to fix … -
In Django REST framework。How to control serializer does not automatically remove spaces?
model.py class Msg(models.Model): content = models.CharField(max_length=1024, null=True) serializer.py class MessageSerializer(serializers.ModelSerializer): class Meta: model = Msg fields = ["content"] have data: {"content": " space test "} and print(data) serializer = MessageSerializer(data=data) if serializer.is_valid(): serializer.save() print(serializer.data) return True, serializer.data else: return False, serializer.errors first print is {'content': ' space test '} second print is {'content': 'space test'} So the spaces in the database disappeared. How do I keep spaces? -
Formation a custom widget value to look like custom date
I have a custom widget, and I want to format the value as Date. The widget value from database(is a DateField) is the following format: 2018-04-10 and I want to be shown to user like this: Tue Apr 03 2018 I tried using a template filter: {% if widget.value != None %} value="{{ widget.value|date:'M d, Y'}}"{% endif %} but the field value gets empty. -
Django can't deploy through mod_wsgi error [AWS]
I'm facing an error while trying to deploy my django app through Elastic Beanstalk service. Locally everything works correctly. I also try to modify my code based on answers Django stops working with RuntimeError: populate() isn't reentrant and this Target WSGI script '/opt/python/current/app/ … /wsgi.py' cannot be loaded as Python module without success. [:error] [pid 3519] mod_wsgi (pid=3519): Target WSGI script '/opt/python/current/app/diamond/wsgi.py' cannot be loaded as Python module. [:error] [pid 3519] mod_wsgi (pid=3519): Exception occurred processing WSGI script '/opt/python/current/app/diamond/wsgi.py'. [:error] [pid 3519] Traceback (most recent call last): [:error] [pid 3519] File "/opt/python/current/app/diamond/wsgi.py", line 16, in <module> [:error] [pid 3519] application = get_wsgi_application() [:error] [pid 3519] File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [:error] [pid 3519] django.setup(set_prefix=False) [:error] [pid 3519] File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/__init__.py", line 24, in setup [:error] [pid 3519] apps.populate(settings.INSTALLED_APPS) [:error] [pid 3519] File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/apps/registry.py", line 81, in populate [:error] [pid 3519] raise RuntimeError("populate() isn't reentrant") [:error] [pid 3519] RuntimeError: populate() isn't reentrant Moreover my wsgi.py file : import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "diamond.settings") application = get_wsgi_application() and my django.config included into option_settings: aws:elasticbeanstalk:container:python: WSGIPath: diamond/wsgi.py Thanks in advance -
Django Form conver to Django Rest Framework Serializer
I am creating a html signup form using Django Rest Framework views and serializers. Previously i have created signup form using Django views and forms. In Django its Usercreation form is ready made available but not in DRF. I found the following code of Usercreationform from Django source code: class UsernameField(forms.CharField): def to_python(self, value): return unicodedata.normalize('NFKC', super().to_python(value)) class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = User fields = ("username",) field_classes = {'username': UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self._meta.model.USERNAME_FIELD in self.fields: self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True}) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def _post_clean(self): super()._post_clean() # Validate the password after self.instance is updated with form data # by super(). password = self.cleaned_data.get('password2') if password: try: password_validation.validate_password(password, self.instance) except forms.ValidationError as error: self.add_error('password2', error) def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return … -
django password hash different everytime
if I create a hash using django's django.contrib.auth.hashers.make_password of the same string I get different hash every time. I don't understand how is this legal because as far as I know, hash functions must generate the same hash every time since by definition its a function. What am I missing? from django.contrib.auth.hashers import make_password password = "helloworld" h1 = make_password(password) h2 = make_password(password) print h1, h2 h1 = u'pbkdf2_sha256$20000$Tr6NV5MewXYl$X+sezT6WRqBwYmJR/RZmZHLP6/l6ntSaBke0RKU1/v0=' h2 = u'pbkdf2_sha256$20000$05rEmxChtXlI$NdZGfTKH+kqt1viuFng3GmvBp6eJcsstxV4JcDlBGIs=' I suspect that different algorithms are used to hash every time and hence the hash is also different. Am I correct? -
Django join query with related key
I have this model: class Role(models.Model): role_name = models.CharField() class RolePriviledge(models.Model): role = models.ForeignKey(Role, related_name='role_priviledge' ) module_name = models.CharField() priviledge_level = models.CharField() class UserRole(models.Model): user = models.ForeignKey(User) role = models.ForeignKey(Role) What I am trying to do is to find all the priviledges for a specified user. In sql, this would be: SELECT t3.* FROM UserRole t1 JOIN Role t2 on t1.role_id = t2.id JOIN RolePriviledge t3 on t2.id = t3.role_id (I can also skip the join with Role and just do an inner join between UserRole and RolePriviledge) How would I do this join with Django ORM? UserRole.objects.filter(user_id=USER_ID).select_related('role') would join UserRole with Role. How do I join it with RolePriviledge? -
Django REST Framework: Serializer to update object if it exists (by unique together)
I have model Run. It represents a time period measurement of data: class Run(models.Model): start_time = models.DateTimeField(db_index=True) end_time = models.DateTimeField() chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) class Meta: unique_together=(('start_time', 'chamber'),) Here is an example of a POST request data blurb for this endpoint: { "start_time": "2018-11-11T12:00:00Z", "end_time": "2018-11-11T12:00:01Z", "chamber": "My Test Chamber" } A Run belongs to a Chamber and has a start_time and end_time A Run cannot share the same Chamber and start_time. If I get the same start_time and Chamber in my request data blurb, that means the Run is still ongoing and needs to be updated. When the request comes through the first time, I create a Run object, that works fine. The sensor that is sending the requests will then send the same POST request data blurb, changing only the end_time of the data blurb, as long as a "Run" is ongoing. The sensor does not send PUT or PATCH, it only sends POST, this may be a problem, but it's unfixable so I have to make do with POST requests. The behaviour I desire is: The first time a Run data blurb is sent, create a new Run object As long as I receive the same Chamber … -
not getting the webpage to enter the input details
all i am new to webdevelopment i am trying to give the details like first_name,last_name,email,phone_number in a webpage after giving inputs it has to show the results in another page below is my views.py file from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from first.core.forms import SubmitForm def submit(request): if request.method == 'POST': form = SubmitForm(request.POST) if form.is_valid(): form.save() first_name= form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') email=form.cleaned_data.get('email') phone_number=form.cleaned_data.get('phone_number') user = authenticate(first_name=first_name,last_name=last_name,email=email,phone_number=phone_number) submit(request, user) return redirect('wewebapp/signup.html') else: form = SubmitForm() return render(request, 'signup.html', {'form': form}) below is my url.py code from django.conf.urls import url from django.contrib.auth.views import submit from first.core import views as core_views urlpatterns = [ url(r'^wewebapp/$',core_views.wewebapp, name='wewebapp'), ] below is my forms.py file from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') phone_number = forms.IntegerField(max_length=10) class Meta: model = User fields = ('first_name', 'last_name', 'email', 'phone_number') and below is my signup.html code {% extends 'base.html' %} {% block content %} <div class="container"> <h2>details</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> </div> {% endblock %} after running the server i am getting … -
django import error - from . import views in urls under app
I did declare like "from . import views" at urls.py. To use TemplateView, this urls.py is needed. urls.py from django.urls import path, re_path from . import views app_name = 'scheduler' urlpatterns = [ re_path(r'^service/(?P<status>\w+)', views.SchedulerView.as_view(), name='schedule-service') ] I think nothing but normal implementation. Error occurs like the below. from . import views ImportError: cannot import name 'views' Older versions django did work. But it's not working in django 2.0 App Structure - server - scheduler - templatetags schedule_status.py - urls.py - main settings.py urls.py - manage.py I just guess 'scheduler' app's path is incorrect to work "from . import views" Is there anyone who solved or check more things. these problem after django 2.0. -
Migrating Django model field from TextField to ArrayField
I'm migrating an existing PostgreSQL database to Django and a lot of the fields are TextFields but include lists encoded as JSON (which is what the previously used ORM used). So naturally when inspectdb was used on the database the created models use TextField. I'd like to actually turn these into Django's ArrayField, a PostgreSQL-specific field. The generated migration doesn't seem to handle this well and crashes with: django.db.utils.DataError: missing dimension value Also, would the text actually be decoded as a list and stored that way or would it simply take the JSON-encoded string and store it as a single value list?