Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get a queryset from another Model in a queryset in Django
V Model (id, title, d_id...) and D Model (id, name, ...) in a ModelViewSet I wrote like this: class index(viewsets.ModelViewSet): serializer_class = VSerializer queryset = V.objects.all() I have obtained those data through the API { "id": 1, "title": xxxxx "d_id": 8, ... ... } However, I wanna the d_id to be more specific, like this: { "id": 1, "title": xxxxx "d_id": { "id": 8, "name": xxx, .... } ... ... } So the data in the D Model has been fetched through the d_id=8 and attached into the original queryset. How could I do this? Need your help... -
Documenting django rest framework API using YAML
I'm following DRF 3. documentation and struggling with documenting my API I have the following class-based view class BizDay(GenericAPIView): """ Next business date --- parameters: - name: region required: true type: string description: Foobar long description goes here - name: base_date required: false type: date description: Foobar long description goes here - name: days_offset required: false type: integer description: Foobar long description goes here - name: cutoff_hour required: false type: integer description: Foobar long description goes here - name: cutoff_region required: false type: string description: Foobar long description goes here serializer: .serializers.BizDayReq """ serializer_class = BizDayReq #@add_query_parameters(BizDayReq) def get(self, request, version): serializer = BizDayReq(data=request.query_params) serializer.is_valid(True) data = serializer.validated_data regions = data['regions'] base_region = regions[0] days_offset = data['days_offset'] cutoff_region = data['cutoff_region'] cutoff_hour = data['cutoff_hour'] calendar = TradingCalendar(*regions) if data.get('base_date'): dt_now = convert.timestamp_to_datetime(data['base_date'], base_region) else: dt_now = convert.get_current_datetime(base_region) cutoff_dt = convert.get_current_datetime(cutoff_region) cutoff_dt = cutoff_dt.replace(hour=cutoff_hour, minute=0, second=0, microsecond=0) dt_next = dt_now if days_offset > 0: if dt_next < cutoff_dt: days_offset -= 1 for _ in range(days_offset): dt_next = calendar.next_business_day(dt_next) else: for _ in range(abs(days_offset)): dt_next = calendar.previous_business_day(dt_next) resp = { 'date': dt_next.strftime('%Y-%m-%d'), 'tz_region': base_region } return Response(resp) And the following serializer class BizDayReq(serializers.Serializer): base_date = serializers.IntegerField(required=False) regions = serializers.CharField(min_length=2) days_offset = serializers.IntegerField(required=False, default=1) … -
HttpResponseRedirect not working in django
HttpResponseRedirect not working it shows error as 'context must be dict rather than response' class FooterLinksView(TemplateView): template_name = 'pages/footerlinks.html' model = FooterLink def get_context_data(self, **kwargs): context = super(FooterLinksView,self).get_context_data(**kwargs) string_name = self.kwargs['string'] obj = FooterLink.objects.get(link_url=string_name) if obj.link_type == 'page': try: context['page_obj'] = obj return context except: pass else: pass print(obj.url_name) return HttpResponseRedirect(str(obj.url_name)) -
Avoid duplicate queries in Django
I am working with CSV data in my application. One of the columns in the CSV file contains a name. For each of the rows, I need to check to see if this name is already registered. If it is, I will store a variable and use that later on: data = [] with open(path) as f: reader = csv.reader(f) for row in reader: user = False check_user = User.objects.filter(name=row[0]) if check_user: user = check_user[0] # This will only return a single row so I want that one to be stored in the user variable instead of a list data.append({'name': row[0], 'age': row[1], 'phone': row[2], 'user': user}) Then in my view I will do something like: {% for info in data %} <td>{{ data.name }}</td> <td>{% if data.user %}} {{ data.user.name }} {% else %} No user {% endif %}</td> {% endfor %} The problem This all works well. However, the problem is that the list in the CSV file contains many duplicate names. So I can have 1,000 records, with only 10 different names. But in the current scenario, there will be 1,000 queries to the database. What I am trying to do, but I'm not sure how, is … -
How to access the columns of a table in django
I am creating a form with 2 fields, Output table and column name. On selection of the output table, I want to list all the columns in the selected table. I know how to create the drop down dependency, I just want to know how to access the column names in the table models.py class XYZ(models.Model): # this is the name of the table to be accessed Outputname = models.OnetoOneField(Output) column_name = # what do i do here? # -
How to query with ORDER BY Chinese USERNAME (Convert to gbk?) - Django, psql
when I create a score with CreateView, I want to make a query with order_by('username'), but the username is not English, most of them are Chinese Pinyin, I would like to sort them, I pasted my partial model, view and form are as below, thank you for any advice and assistance. class Score(models.Model): test = models.ForeignKey(Test, verbose_name="考试名称", null=True, blank=True, on_delete=models.CASCADE) user = models.ForeignKey(User, verbose_name="应考人", null=True, blank=True, on_delete=models.CASCADE) score = models.FloatField(default=0, verbose_name="考试分数(满分100)") pass_score = models.FloatField(default=0, verbose_name="通过分数(满分100)") add_time = models.DateTimeField(auto_now=True, verbose_name="添加时间") class ScoreCreateView(CreateView): model = Score form_class = ScoreForm template_name = '' def form_valid(self, form): testscore = form.save(commit=False) testscore.save() return redirect('', score.pk) class ScoreForm(forms.ModelForm): user = forms.ModelChoiceField(queryset=User.objects.order_by('department', 'username')) class Meta: model = Score fields = ('test', 'user', 'score', 'pass_score') -
Unable to Update One to One Django Models
I'm using the default Django 'User' model to create a user. After successful creation, this user is directed to a profile page where he is asked to fill up their profile. The profile has a OneToOneField with User. On the first save, the profile is successful because the first insert is with the request.user and the profile object had yet to be created. On future attempts to edit this form, I get an error that says django.db.utils.IntegrityError: UNIQUE constraint failed: app_profile.user_id. Here is my Profile model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) type = models.CharField(choices=( ('content-creator', 'Content Creator'), ('artist', 'Artist'), ), max_length=20) about = models.CharField(max_length=100, blank=True) birth_date = models.DateField(null=True, blank=True) location = models.CharField(max_length=30, blank=True) youtube = models.URLField(null=True, blank=True) instagram = models.URLField(null=True, blank=True) facebook = models.URLField(null=True, blank=True) twitter = models.URLField(null=True, blank=True) website = models.URLField(null=True, blank=True) other = models.TextField(null=True, max_length=100, blank=True) And here is the Profile view class ProfileView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to' form_class = ProfileForm template_name = 'app/profile.html' initial = {} def get(self, request, *args, **kwargs): profile = Profile.objects.get(user=request.user) if profile: form = ProfileForm(instance=profile) else: form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = ProfileForm(request.POST) if form.is_valid(): profile_obj = form.save(commit=False) profile_obj.user = … -
Is it possible to have connection to multiple clusters via django-cassandra-engine?
I'm using django-cassandra-engine python library to use cassandra database in django. I wanted to know is there a way to have connection to multiple cassandra clusters and specify connection for models. -
I am unable to understand it, so if anybody can find its solution then tell me
C:\Users\mindfreek\project_web\venv\Scripts\python.exe C:/Users/mindfreek/Desktop/Project_django/Project_django/urls.py Traceback (most recent call last): File "C:/Users/mindfreek/Desktop/Project_django/Project_django/urls.py", line 5, in url(r'^admin/', include(admin.site.urls)), File "C:\Program Files\Python36-32\lib\site-packages\django-2.1a1-py3.6.egg\django\utils\functional.py", line 213, in inner self._setup() File "C:\Program Files\Python36-32\lib\site-packages\django-2.1a1-py3.6.egg\django\contrib\admin\sites.py", line 526, in _setup AdminSiteClass = import_string(apps.get_app_config('admin').default_site) File "C:\Program Files\Python36-32\lib\site-packages\django-2.1a1-py3.6.egg\django\apps\registry.py", line 150, in get_app_config self.check_apps_ready() File "C:\Program Files\Python36-32\lib\site-packages\django-2.1a1-py3.6.egg\django\apps\registry.py", line 131, in check_apps_ready settings.INSTALLED_APPS File "C:\Program Files\Python36-32\lib\site-packages\django-2.1a1-py3.6.egg\django\conf__init__.py", line 57, in getattr self._setup(name) File "C:\Program Files\Python36-32\lib\site-packages\django-2.1a1-py3.6.egg\django\conf__init__.py", line 42, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
display value of a row Django Python
i need some assistance, i have a table and want to be able to only display the values of a particular row when ever a particular row is selected. For example if row one is selected only the values of that row will be display. -
EmailMessage class in google app engine python not working?
is the google app engine document not updated? It works fine (send email with attachment), when I do this: message = mail.EmailMessage( sender=EMAIL_SENDER, subject=subject,body=theBody,to=['test@gmail.com'],attachments=[(attachname, new_blob.archivoBlob)]) message.send() But When I use message.attach , it says'EmailMessage' object has no attribute 'attach' message.attach("certificate.pdf", new_file, "application/pdf") or message.Attachment("certificate.pdf", new_file, "application/pdf") both says :'EmailMessage' object has no attribute 'attach/attachment' In the documentation there are examples of "Attachment". https://cloud.google.com/appengine/docs/standard/python/refdocs/google.appengine.api.mail#google.appengine.api.mail.EmailMessage Please help! -
Error while running the django server in eclipse
Type 'manage.py help <subcommand>' for help on a specific subcommand. Available subcommands: [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate runserver sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver Note that only Django core commands are listed as settings are not properly configured (error: The SECRET_KEY setting must not be empty.). -
ImportError in Django REST Framework Tutorial 1: Serialization
I'm working in a virtual env using Django 1.8 and Python 2.7. I installed REST framework and created a new project and just finished editing the snippets/models.py file by following the tutorial. When I go to create an initial migration of the snippet model using the command: python manage.py makemigrations snippets I get the error: ImportError: No module named apps My setting.py file INSTALLED_APPS is as follows: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'snippets.apps.SnippetsConfig', ) What am I doing wrong? -
Django: How shouldI loop through Taggit tag's and list them alphabetically while at the same time seperating them in template?
I've seen this in a lot of sites actually, and I was wondering how I would go about replicating the functionality. Basically the tags follow this kind of pattern A | all tags that start with A Y | all tags that start with Y B | all tags that start with B Z | all tags that start with Z A, B, ... Y, Z would probably be in something like an <h5> tag and all the tags in <li> tags Essentially I want that tag list page to show all the tags used throughout the blog alphabeticalized. I have an idea how to do it, but it may not be pretty practical. I was thinking about going through all the tags, grabbing the first letter of each item, putting it in a new dictionary and then looping through that dictionary to display in my templates. Would that be a practical way to do it? I also do have 3rd party apps taggit and https://github.com/fizista/django-taggit-templatetags2 -
Django - Multiple instances of same form class in one view
In the context of Django Forms, I've seen many discussions of handling different kinds of forms on the same page (eg AForm and BForm on the same page), but I'm trying to figure how to handle multiple instances of the same form class on a page. I am able to display the forms alright, but I don't know how to handle them when the forms are POSTed. I've tried using Formsets as well, and have the same issue (can display, but don't know how to handle POST). So here's my question: let's say I'm displaying several instances of the same Form class on a page. How would I go about handling the POST data when these forms are submitted? -
where to put the server and client code on django
I'm new to django and I have coded a server and client code which is running perfectly on the python idle and I have establish 5 connections and able to send the proccessed data to the client,but I want to put my code in django.Can anyone guide me where to put the server code of idle in django and how to make the interaction between server and client through django? server.py import socket import sys sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('10.191.4.190', 8008) print 'starting up on %s port %s' % server_address sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(server_address) sock.listen(5) while True: print 'waiting for a connection' connection, client_address = sock.accept() try: print 'connection from', client_address while True: data = connection.recv(16) if(data): print 'received "%s"' % data else: connection.close() break finally: connection.close() -
How to get filter in serializers in REST Framework?
I have two tables, they have same column "maid", and some of (instad of all) maid's unitcode is "U", they have units in table dep. I want to get units when the address's maid is exist in dep. The result I want is like below: [ { "addline": "14075 110A Ave", "city": "Surrey", "unitcode": "U", "maid": 113091 }, { "addline": "14143 110A Ave", "city": "Surrey", "unitcode": "S", "maid": 113104, "unit": [ "A-101", "A-102", "A-103", "A-104"] } ] My views.py is as below: def list(self, request, city): if city is not None: queryset = address.objects.filter(city__icontains=city) serializer = ResultSerializer(queryset, many=True) return Response(serializer.data) My models is as below: class address(models.Model): maid = models.IntegerField(primary_key=True, unique=True) fulladdress = models.CharField(max_length=120) city = models.CharField(max_length=120) unitcode = models.CharField(max_length=120) class dep(models.Model): maid = models.ForeignKey(address, related_name='units', on_delete=models.CASCADE) Unit = models.CharField(max_length=120) And my serializers.py is as below: class DepSerializer(serializers.ModelSerializer): class Meta: model = dep fields = ('Unit', ) class ResultSerializer(serializers.ModelSerializer): units = serializers.SerializerMethodField('get_unit') def get_unit(self, queryset): queryset_unit = dep.objects.filter(maid=queryset) serializer = DepSerializer(instance=queryset_unit, many=True) return serializer.data class Meta: model = address fields = ('fulladdress', 'city', 'unitcode', 'units') It seems OK, but server response is 500. I have been afflicted by this problem for almost whole day, anyone can save me? -
default_if_none requires 2 arguments, 1 provided
I tried to use default_if_none in username <input type="text" class="form-control" id="username" value="{{ form.username.value|default_if_none: '' }}" name='username'> It throw error django.template.exceptions.TemplateSyntaxError: default_if_none requires 2 arguments, 1 provide I did not encounter such an error before. The documentation did not provide a hint to solve the problem. -
Cannot display value on web page by using Django
I want to display some values which is queried out from mysql in the method within views.py on the web page, but I cannot see that on the web page. see my method in views.py: def update_delete_customer(request, id): if request.method == 'POST': print("TODO") else: form = CustomerForm() if id is None: print("id is None") return HttpResponseRedirect('AddressTableMaintain/') print("----------------") print(id) customerList = Customer.objects.raw("select * from customers where customer_id = %s", [int(id)]) customer = list(customerList)[0] print(customer) form.customerId = customer.customerId form.first_name = customer.first_name form.last_name = customer.last_name print(customer.customerId) print(customer.first_name) print(customer.last_name) return render(request, 'EditCustomer.html', {'form': form}) return HttpResponseRedirect('AddressTableMaintain/') I can see the output information generated by the print function. Below is the contents of my EditCustomer.html: {% extends 'base.html' %} {% block title %} Remove or Update customer {% endblock %} {% block content %} <style> table, th, td { border: 1px solid black; border-collapse: collapse; } </style> <form action="{% url 'RU_customer_post' %}" method="post"> {% csrf_token %} <table width="50%" align="center"> <tr> <td>Customer ID</td> <td> {{ form.customer_id }} </td> </tr> <tr> <td>First Name</td> <td> {{ form.first_name }} </td> </tr> <tr> <td>Last Name</td> <td> {{ form.last_name }} </td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value = "OK" /></td> </tr> </table> </form> {% endblock %} My expected result is … -
Create model objects from custom Form/Formset in Django
I'm trying to create a simple Django app where I want to have a set of Question objects. Each question has it's own list of available answers. I want to display a number of these questions on a view and create objects based on the user data. It's the last part (create objects based on user-data) that I'm unable to achieve. Here's what I have: class BaseQuestionFormset(BaseFormSet): def __init__(self, question_list, *args, **kwargs): super(BaseQuestionFormset, self).__init__(*args, **kwargs) self.question_list = question_list def get_form_kwargs(self, index): kwargs = super(BaseQuestionFormset, self).get_form_kwargs(index) if self.question_list and index < len(self.question_list): kwargs['question'] = self.question_list[index] else: kwargs['question'] = None return kwargs class QuestionForm(forms.Form): def __init__(self, question, *args, **kwargs): super(QuestionForm, self).__init__(*args, **kwargs) if question: choice_list = [x for x in question.get_answers_list()] self.fields["answers"] = forms.ChoiceField(choices=choice_list, widget=RadioSelect) self.fields['answers'].label = question.content I'm creating the form as follows: question_formset = formset_factory(QuestionForm, BaseQuestionFormset, extra=len(questions)) formset = question_formset(question_list=questions) Then, when I get user-input, I'm creating the formset as follows: question_formset = formset_factory(QuestionForm, BaseQuestionFormset, extra=3) // 3 is for debug purposes formset = question_formset(question_list=None, data=request.POST) I'm left with an empty formset that doesn't have any of the data that the users input. I'd appreciate any pointers on what I'm doing wrong and how I can fix it. Thanks! -
Django get a single element from a queryset based on a filter in a loop
attributes is a queryset of attributes and the entity object has a many to many field called attributes. My goal is to fetch the attribute if its type exists in the many to many field. Currently this would populate the page with the queryset itself. But I'm trying to do something like <input type="text" class="validate" , value="{{ entity.attributes.filter|attribute_type:attribute_type }}"> i.e. If this attribute type exists as part of an attribute in the many to many field within this entity, fetch the Attribute object. {% for attribute_type in attribute_types %} <div class="row valign-wrapper"> <div class="col s4">{{ attribute_type }}</div> <div class="input-field col s8"> <input type="text" class="validate" , value="{{ entity.attributes.all }}"> </div> </div> {% endfor %} -
Error: "'NoneType' object has no attribute..." when utilizing method for a self-referential foreign key
I'm developing my first Django project for practice, and I'm running to a problem with self-referential foreign keys. I have an app called "units" in which there is a models.py: from django.db import models class Unit(models.Model): name = models.CharField( 'Unit', max_length=255, blank=True ) quantity_per = models.DecimalField( 'Quantity Per', max_digits=10, decimal_places=5, default=1 ) subunit = models.ForeignKey( 'self', blank=True, null=True, on_delete=models.SET_NULL, related_name='+', verbose_name="subunit" ) abbreviation = models.CharField( 'Abbreviation', max_length=255, blank=True ) def unit_factor(self): return self.subunit.quantity_per * self.quantity_per def __str__(self): return self.name And this is referred to in my rudimentary index template as so: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'units/style.css' %}"/> {% if unit_list %} <ul> {% for unit in unit_list %} <li>{{ unit.name }} - {{ unit.subunit }} - {{ unit.subunit.quantity_per }} - {{ unit.unit_factor }}</li> {% endfor %} </ul> {% else %} <p>No units are available.</p> {% endif %} When I runserver and navigate to the "units" url, I get the following error: 'NoneType' object has no attribute 'quantity_per' I think this has something to do with me creating the method within the same class as the self-referential foreignkey and the child instance not being completely instantiated yet? But I'm sure my lack of programming knowledge is … -
How to run python script on JS(button onclick)
How to run django script in js. I need to use IMDb API on onclick method to get id of movie user is searching. how can I do it? I am still begginer in django so dont judge me :) Here is my html for that part: <div class="form-inline mt-2 mt-md-0"> <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" id="search_movie_textField"> <button class="btn btn-outline-success my-2 my-sm-0" onclick="search_movie()" >Search</button> </div> Here is my JS I am trying to write: function search_movie(){ var sreach = document.getElementById("search_movie_textField").value; //GET IMDB ID FROM NAME window.location.href = '/movielist/movies/' + id; } -
Page 404 not found django
I was trying to do a 'add member' function. Basically,when you click on the button 'add button', member names will show somewhere in this page.But I got this error: Here is part of HTML looks like: project_detail.html {% extends 'base.html' %} {% block content %} <p>Project {{ project_id }} detail</p> <div class="btn btn-default oval" style="width: 10%"><a href="{% url 'project:project_edit' project_id=project_id%}">Edit</a></div> <div class="btn btn-default oval"style="width: 10%"><a href="{% url 'project:project_delete' project_id=project_id%}">Delete</a></div> <div class="btn btn-default oval"style="width: 10%">Members</div> <form action="" method="POST" id="selection-form"> {% csrf_token %} <select id="member_list"> {% for user in users %} <option value="{{user.id}}"> {{ user.username }} </option> {% endfor %} </select> <input type="button" value="Add member" id="selection-button"> </form> <div id="res"> </div> {% endblock %} {% block script %} var url = $( '#selection-button' ).attr( 'action' ); $("#selection-button").on('click', function(e) { e.preventDefault(); var value =$('#member_list').val(); $.ajax({ type:'POST', url:'add_member/'+value+'/', success:function (result) { $("#res").append(value); }, error:function (result) { alert('error'); } }); }); {% endblock %} urls.py urlpatterns = [ path('', views.project_index, name='project_index'), path('<int:project_id>/', views.project_detail, name='project_detail'), path('create/', views.project_create, name='project_create'), path('<int:project_id>/delete/', views.project_delete, name='project_delete'), path('<int:project_id>/delete_result/', TemplateView.as_view(template_name="project/delete_result.html"), name='delete_result'), path('<int:project_id>/edit/', views.project_edit, name='project_edit'), path('<int:project_id>/add_member/<int:user_id>', views.add_member, name='project_add_member'), path('<int:project_id>/task/', include('task_tracker.urls')), path('<int:project_id>/issue/', include('issue_tracker.urls',namespace='issue_tracker')), path('<int:project_id>/channel/', include('communication_channel.urls')), ] views.py def add_member(request,project_id): if request.method=='POST': members = User.objects.all() serializer = UserSerializer() return render(request,'project/project_add_member',{'project_id':project_id}) project_add_member.html {% extends 'base.html' %} {% block … -
Look up field from a different Django model given another model field
I have two models in Django: Room for offices, and Person for employees. One office could have multiple employees. I'm trying to make a detail-view html page that shows a person's details, like their name and office number. I can get the details from the Person model fine, but I'm having trouble doing a reverse look-up to the Room model. How can I get a person's office given the following code? #models.py class Room(models.Model): number = models.CharField('Room number', unique=True) persons = models.ManyToManyField('Person', blank=True) #... class Person(models.Model): name = models.CharField('Full name', max_length=200) #... #views.py from django.views import generic class PersonDetailView(generic.DetailView): model = Person #person_detail.html {% extends "base_generic.html" %} {% block content %} <h1>Name: {{ person }}</h1> <p>Room: {{ Room.number }}</p> {% endblock %} All that currently does is return a name, but "Room" is left blank.