Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Test input message text and answer in Django custom admin command
I want to test user input confirmation answer in a custom management command. The test is for message displayed to user and answer that she enters. The commands' code is: class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('id', type=int) def handle(self, *args, **options): try: experiment = Experiment.objects.get(pk=options['id']) except Experiment.DoesNotExist: raise CommandError( 'Experiment with id "%d" does not exist' % (options['id']) ) answer = input('Are you sure? (Y/n)') if answer == 'Y': experiment.delete() This accepted answer suggests to use mocking, but it's in a lonely context. I want to test the user input as well other things that I could add to the custom command. What would be an efficient approach? -
Comparing dataframe object with string value in django
I'm implementing machine learning model and using training dataset from MySQL table and all this is built upon Django. So basically all the calculations are done by converting entire data from MySQL table to dataframe. df = pd.read_sql("select * from naivebayes_player",connection) However, I'm facing problem in comparing dataframe column value with a string. So I have a column named classification in MySQL table which has 2 fixed values 'RS' or 'NRS' stored in varchar(10) format. Since I've converted an entire table into dataframe whenever I calculate the count of 'RS' values in classification column in dataframe it always returns 0. But actually, there are 63 entries of 'RS'. total_RS = df['classification'][df['classification']=='RS'].count() In above line of code I'm trying to find out all records where classification is 'RS' which should be 63 but I'm getting 0. What am I doing wrong? I have tried above code when reading data from CSV instead of MySQL table and everything worked fine. -
Django admin action delete_selected to be the last option in the drop-down list
I would like to display the delete_selected action in the drop-down list in the admin screen as the last option just for one model. -
Pass argument to Django form
There are several questions on stackoverflow related to this topic but none of them explains whats happening neither provides working solution. I need to pass user's first name as an argument to Django ModelForm when rendering template with this form. I have some basic form: class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.first_name = ??? super(MyForm, self).__init__(*args, **kwargs) class Meta: model = MyModel fields = [***other fields***, 'first_name'] Here's my sample class-based view: class SomeClassBasedView(View): def get(self, request): some_value = 'foo' user_first_name = request.user.first_name form = MyForm(???) return render(request, 'my_template.html', {'form': form}) What do I pass to MyForm when initialising it and how do I access this value inside the __init__ method? I want to use 'first_name' value as a placeholder for one of the fields in template by updating self.fields[***].widget.attrs.update({'placeholder': self.first_name}). -
The size of checkbox django is very huge
I am creating a checkbox for subscribing using forms.py in Django. The size of the checkbox is very huge I don't why. Models.py: receive_notification = models.BooleanField('Receivenotification',default=True) Forms.py: receive_notification = forms.BooleanField(required=False) The CSS file: h8 { width: 320px; padding-left: 20px; margin-top: 710px; position: absolute; } The HTML file: <h8> {{ field.label }} {{ field }} </h8> -
custom field value forgets values
Apologies for a long complicated question. I've done my best to make it concise and easy to understand, but still, I think it will require some deep Django knowledge to answer. I'm trying to create a custom field type which stores my Lifts class. Here is the class that I want stored: class Series(object): """Series is a list of AbstractSerie objects""" def __init__(self, series, serie_class): self.series = [] for serie in series: if type(serie) != serie_class: raise TypeError("List passed to constructor should only contain "+serie_class.__name__+" objects.") self.series.append(serie) class Lifts(Series): def __init__(self, series): """ Series is a list of LiftSeries """ super().__init__(series, LiftSerie) And here is the LiftSerie class and its parent AbstractSerie that are stored in a Lifts object: class AbstractSerie(object): def __init__(self, activity): """activity is an Activity""" self.activity_name = activity.name def pre_json(self): """ A function that returns a dict version of the serie. Should be implemented in subclasses. """ raise NotImplementedError class LiftSerie(AbstractSerie): """Represents a lift and the number of reps and weight for each set of it.""" def __init__(self, lift_activity, setlist): """ lift should be an instance of LiftActivity. setlist is a list containing (weight, reps) for each set that has been performed. """ if not (isinstance(setlist, collections.Sequence) … -
NoReverseMatch at /judge/judge-timeslot.html Reverse for 'sub' with arguments '('',)' not found
Running Django 2.0.1. Getting the following error: NoReverseMatch at /judge/judge-timeslot.html Reverse for 'sub' with arguments '('',)' not found. 1 pattern(s) tried: ['judge\/(?P[0-9]+)$'] Request Method: GET Django Version: 2.0.1 Exception Type: NoReverseMatch urls.py: from django.urls import path from django.conf.urls import url from . import views app_name = 'judge' urlpatterns = [ path('judge-home.html', views.index, name='index'), path('judge-score.html', views.score, name='score'), path('judge-timeslot.html', views.timeslots, name='timeslots'), path('results.html', views.results, name='results'), path('<int:choice_id>', views.sub, name='sub'), ] sub view in views.py: def sub(request, choice_id): template = loader.get_template("judge/judge-timeslot.html") c = get_object_or_404(Choice, pk=choice_id) try: selected_choice = c.choice_set.getlist(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, template, { 'choice': c, 'error_message': "You didn't select a choice.", }) else: # selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('judge/judge-timeslot.html', args=(c.id,))) Here is the judge-timeslot.html: <form action="{% url 'judge:sub' choice.id %}" method="post"> {% csrf_token %} <table class="table table--bordered table--highlight"> <tbody> {% for slot in slots %} <tr> <td> <label class="checkbox"> <input type="checkbox", name="choice" id="choice {{forloop.counter}}" value="{{choice.id}}"/> <span class="checkbox__input"></span> </label> </td> <td>{{slot}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> <button class="btn btn--primary">Select</button> </form> It is referring to this line: … -
Non-overlapping constraint on Django postgres IntegerRangeField
I found that Django has support for Postgres' range fields and also found that in Postgres, we can have non-overlapping constraint (exclusion constraint) as described here at section 8.17.10. Can anyone tell me how can I apply this constraint in Django in Field iteself not in migration file. I am using django 1.8 and postgres 9.4 Your help will be highly appreciated. -
how to display data from a text file in my templates using django
I have a text file with 3 columns separated by /t I want to write an index view who display the first column into a combobox. This is my view def index(request): //opening my file myfile = open("myfile.txt", "r") //read file and get the first column, i dont know how myfile.read() context = { first_column : first_column} return render(request,myapp/mytemplate.html,context) -
Django REST Framework join table results in attribute exception
I am building an API in Django using REST Framework but am running into an issue. Serializers: class SquadSerializer(serializers.Serializer): class Meta: model = Squad fields = ('name') id = serializers.IntegerField(read_only=True) name = serializers.CharField(style={'base_template': 'textarea.html'}) class MembershipSerializer(serializers.Serializer): class Meta: model = Membership fields = ('employee_id', 'squad_id') squad = SquadSerializer() employee = EmployeeSerializer() class EmployeeSerializer(serializers.HyperlinkedModelSerializer): habitat = HabitatSerializer() class Meta: model = Employee fields = ('id', 'first_name', 'last_name', 'function', 'start_date', 'end_date', 'visible_site', 'habitat') Models: class Employee(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) function = models.CharField(max_length=50) start_date = models.DateField() end_date = models.DateField(null=True, blank=True) visible_site = models.BooleanField() habitat = models.ForeignKey(Habitat, on_delete=models.SET_NULL, null=True, blank=True) class Squad(models.Model): name = models.TextField(max_length=40) class Membership(models.Model): class Meta: unique_together = (('employee', 'squad')) employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=False, blank=True, default=1) squad = models.ForeignKey(Squad, on_delete=models.CASCADE, null=False, blank=True, default=1) The problem is that I keep running into this error: AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `SquadSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Membership` instance. Original exception text was: 'Membership' object has no attribute 'name'. I've seen multipe people with the same issues here on Stack Overflow but the often suggest solution (to add many=True to … -
Video and photo Gallery from S3 Bucket
im new in python and django, could you please help me to create a simple App that would be Galley for amazon S3 photos and videos. i have already saved objects in s3. but how can i call and showing them as easiest way in my page. im using Django==1.11.2 python 3.5 your helps means to me alot -
Django: Possibilites in writting in LDAP
Is it possible to change attributes of a user in LDAP via django? As of now, I can't find any solution in the Internet. i.g. I have the django-auth-ldap backend and i can loggin as a user (GUI). But I can't change any of there attributes (i.g. change the name). What do I have to write or extend? If you have any idea let me know. Do I have to write in my views, models, forms or whatever?? If you need code don't hesitate to ask. Thanks for your help! -
'DownLinkAdmin' object has no attribute 'request'
im currently working on an upgrade for the django package called "django-dynamic-link", a very cool but outdated project. I want to this project to be able to run with newer Django Versions (>=1.11.7). As you can see, I fixed already some little parts in my github fork, that allows you to enter the admin site and configure the dynamic link section. But when i try to create a dynamic link, ill get the following error message: File "/django-dynamic-link/dynamicLink/admin.py", line 84, in link sitelink = siteurl.get_site_url(self.request) AttributeError: 'DownLinkAdmin' object has no attribute 'request' Here is the code of the admin.py file: from django.contrib import admin from models import Download from django.utils.translation import ugettext_lazy as _ import api import presettings class DownLinkAdmin(admin.ModelAdmin): def queryset(self, request): """catch the request object for list pages""" self.request = request return super(DownLinkAdmin, self).queryset(request) list_display = ('slug', 'active', 'file', 'valid', 'clicks', 'timestamp_creation', 'link') actions = ['make_link'] search_fields = ['slug', 'file_path', 'timestamp_creation', 'link_key'] list_per_page = 50 fieldsets = ( (_(u'Link'), { 'fields': ('slug', 'file_path') }), (_(u'Additional values'), { 'classes': ('collapse',), 'fields': ('active', 'current_clicks', 'timeout_hours', 'max_clicks') }), ) def valid(self, obj): """Shows time stamp expired or active time""" diff = unicode(obj.get_timout_time()).split('.')[0] if obj.timeout_time(): if obj.active: # set active to false … -
Getting error in displayig data from sqlite in the HTML template
I am trying to display the images from databse to HTML template,but I am getting an import error: return Database.Cursor.execute(self, query) django.db.utils.OperationalError: no such table: Image here are the files:models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Image(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.FileField(upload_to='post_image', blank=True) views.py: from django.shortcuts import render from django.db import connection from accounts.models import Image from django.contrib.auth.models import User # Create your views here. def home(request): cursor = connection.cursor() cursor.execute('''SELECT image FROM Image where 'user'="admin"''') row = cursor.fetchone() print (row) args = {'row':row} return render(request, 'accounts/home.html', args) home.html: {% extends 'base.html' %} <h1>Home</h1> <html> <head> <title>HOME</title> {% block head %} <title>HOME</title> {% endblock %} </head> <body> <h2 align="center"> SQL Queries display </align> </h2> {% block content %} {{ row }} {% endblock %} {% block body %} <h1>Base</h1> {% endblock %} </body> </html> I am storing data on the file system, I have uploaded two images for the user 'admin'. -
Django: Views: class vs function
I'm working on a small Django project and I noticed there are different ways to write a view. What's the difference between a view created with a class and a view created with a function? When should I use which one? Thanks! -
NoReverseMatch on context Data
I am trying to access my context data but for some reason I get an error. ..................................... {% extends 'base.html' %} {% load static %} {% block body %} <div class="container paddingtop80 marginbottom30"> <div class="jumbotron greenback"> Test <a href="{% url 'registration:applicant_register3' pk1=project.id %}" class="btn btn-success" role="button"><span class="glyphicon glyphicon-plus"></span> Add Applicants</a> </div> </div> I am trying to use pk1 = project.id My views should allow me to access it .. class RecruitmentPage(generic.ListView): #import pdb; pdb.set_trace() template_name = "recruitment_index.html" model = Project def get_object(self, queryset=None): return get_object_or_404(Project, id=self.kwargs['pk1']) def get_context_data(self, **kwargs): context = super(RecruitmentPage, self).get_context_data(**kwargs) return context I guessed that by providing the model in the generic view I could access it but it seems that I cannot .. Can someone give me a hand ? thx -
Try to pass the initial data in the form with the field ManyToMany
My problem is that I can not save the form. I think the problem lies in the event field in the Register model. I do not want the user to choose an Event from the list, I want it to happen automatically, hence the code: form.cleaned_data['event'] = kwargs['pk'] This part of code kwargs['pk'] is from url. Please any hint if this is good approch to dealing with forms and hint to solve my problem. Below is my code. Thanks :) Models: class Event(models.Model): title = models.CharField(max_length=500) date = models.DateField() text = models.TextField() image = FilerImageField(null=True, blank=True) flag = models.ForeignKey(Flag) free_places = models.IntegerField() class Meta: ordering = ['-date'] def __str__(self): return self.title @property def slug(self): return slugify(self.title) def get_absolute_url(self): return reverse('events:detail', args=[self.slug, self.id]) class Register(models.Model): event = models.ForeignKey(Event) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) company = models.CharField(max_length=30, blank=True) street = models.CharField(max_length=50, blank=True) post_code = models.CharField(max_length=30, blank=True) city = models.CharField(max_length=30, blank=True) email = models.EmailField() phone_number = models.IntegerField() def __str__(self): return self.first_name def get_event_name(self): return self.event View: class EventDetailView(DetailView, ModelFormMixin): model = models.Event form_class = forms.RegisterForm def get_success_url(self): return reverse('events:list') def post(self, request, *args, **kwargs): form = self.get_form() print(kwargs['pk']) print(self.form_class) if form.is_valid(): print(form.cleaned_data['event']) form.cleaned_data['event'] = kwargs['pk'] form.save() return self.form_valid(form) else: return self.form_invalid(form) My … -
Django missing 1 required positional argument
I am trying to make a view that i can use in multiple apps with different redirect urls: Parent function: def create_order(request, redirect_url): data = dict() if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect(redirect_url) else: form = OrderForm() data['form'] = form return render(request, 'core/order_document.html', data) Child function: @login_required() def admin_order_document(request): redirect_url = 'administrator:order_waiting_list' return create_order(request, redirect_url) When i'm trying to call admin_order_document function i'm getting: Traceback (most recent call last): File "/home/project/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/project/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/project/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: create_order() missing 1 required positional argument: 'redirect_url' If i remove redirect_url from both functions and manually add 'administrator:order_waiting_list' to redirect() it works, but i need to redirect to multiple urls. So, why am i getting this error? -
How to put arguments in a jchart.Chart class
I am trying to make a chart in Django using the jchart module and to be able to chose which rows i want to retrieve from the db using the variable hosp from my views.py to HomeTotalStudies() (below) views.py from charts.chartsclass import HomeTotalStudies def home(request): hosp = request.user.userprofile.hospital chart = HomeTotalStudies() return render ..... here is the /charts/chartsclass.py from jchart import Chart from jchart.config import (DataSet, Axes, rgba, ScaleLabel, Tick, Tooltips, Legend, LegendLabel, Title, Hover, InteractionModes, ElementLine, ElementPoint, ElementRectangle) class HomeTotalStudies(Chart): chart_type = 'pie' responsive = False def get_labels(self,**kwargs): return ["CT","MG","RF","DX"] def get_datasets(self,**kwargs): modality = ['CT','MG','RF','DX'] count = [] if hosp=='somestring' #this is the variable i want to get from the views.py studies = GeneralStudyModel.objects.all() else: studies = GeneralStudyModel.objects.filter(equipmentattributes__institution_name__exact=hosp) for mod in modality: cc = studies.objects.filter(modality_type__exact=mod).count() count.append(cc) data = [count[i] for i in range(len(count))] colors = [ rgba(255,99,132,1), rgba(54,162,235,1), rgba(255,159,64,1), rgba(255,206,86,1) ] return [DataSet(label="My DataSet", data=data, borderWidth=1, backgroundColor=colors, borderColor=colors)] So, my question is, how can I pass this variable hosp from the view to the chart class so that i can make the query to the db table GeneralStudyModel and i retrieve only the rows needed? Any one has any suggestion / idea / solution? Thanks -
How to add custom transition effect to modal opening and closing?
Am using reactjs + reactstrap with django, i built a bootstrap modal, and i need to give css transition or transform or animation effects(dont know actually), so that modal should open from 'top left' corner. -
The best way to store constants in Django
I have a Django application and use GitHub for CI. Now I run into the problem that I have a merge conflict with constants import every time I merge. Another developers are importing constants vary often, so do I. Directories tree looks like that: main_app > ...main_app ...api ...aws_lambda ...billing ...utils ...and many other directories Each sub-application has its own file constants.py. Constants import looks like that: from utils.constants import const1, const2, const3, const4 from billing.constants import const5, const6 How I need to rewrite those imports to decrease merge conflicts in future? Is a better way than the one below? import utils.constants as utils_const import billing.constants as billing_const ... var = utils_const.const1 What is the best practice to store constants in Django app? -
Django persistent database connections in development
I want persistent database connections in my Django project so that a new connection is not created for every request. I have already configured CONN_MAX_AGE': None for my database backend and it works fine in production. However, I read here that: The development server creates a new thread for each request it handles, negating the effect of persistent connections. Don’t enable them during development. Is there a way to persist connections during development? NOTE: I'm using a custom backend for a db for which an external connection pooler doesn't exist and the connection overhead is quite high. It makes development really painful. Thanks! -
Cannot write mode RGBA as JPEG
I'm trying to resize & reduce quality of image before upload in project. Here's what I tried, def save(self): im = Image.open(self.image) output = BytesIO() im = im.resize(240, 240) im.save(output, format='JPEG', quality=95) output.seek(0) self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(Model, self).save() It's working fine if I upload a jpeg file but if I upload a png or any other file type, it's not working it's raising errors like cannot write mode RGBA as JPEG & cannot write mode P as JPEG etc. How can we fix that? Thank You! -
Queryable django admin panel
Is there any admin panel in django that is queryable. I mean a django admin panel in which I can write my SQL queries. -
how to Django dumpdata nested models in yaml
So I have this awesome Django app which gives me satisfaction and such. But now the problem, I want to use dumpdata (or something that does the same) to export a model with a nested other model in yaml format. Lets say I have two models, Project and Questions. Each Project can have it's owns set of Questions. The code looks something like this: Project Model: class Projects(SortableMixin): """ Some docstring """ slug = models.SlugField( _('slug'), help_text=_('Short name to address this projects from templates.')) # Basic fields object_id = models.PositiveIntegerField(blank=True, null=True) name = models.TextField(_('name'), help_text=_('The question.')) # Some other fields... question = models.ForeignKey(Question, null=True, blank=True) Questions Model: class Question(SortableMixin): """ Some docstring """ slug = models.SlugField( _('slug'), help_text=_('Short name to address this question from templates.')) # Basic fields object_id = models.PositiveIntegerField(blank=True, null=True) name = models.TextField(_('name'), help_text=_('The question.')) input = models.TextField() The Project model has his own app and so has the Questions. The structure looks like this: - Django - Apps - Project - Questions Whenever I want to export my database I'll do the following: ./manage.py dumpdata --indent 4 --format yaml > dbdump.yaml Although this works, and I can later import it with LoadData, its not what I want, …