Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
Django Multiple Record Insert CreateView ( not enough values to unpack (expected 2, got 1))
i am getting the following message while saving the record. not enough values to unpack (expected 2, got 1) I am getting a Acquisition ID and attaching qoutations(single or multiple ) and once saving the record the system pops out the error. there is no error if i select the ACQID from createview itself but when i am getting foriegn key from listview then error is coming. i am getting a foriegn key from listview and inserting qoutations for it in the create view if template is required please let me know even if i save a single record the system is giving error as mentioned above. views.py class QoutationAttach(SuccessMessageMixin, CreateView): template_name = "ePROC/Acquisition/qoutation_add.html" model = QoutationSelection form_class=QoutationAdd success_message = "Record was created successfully" success_url = reverse_lazy('ePROC:qoutattach-list') def form_valid(self, form): form.instance.AcqID=CreateACQModel.objects.get(self.kwargs['pk']) return super(QoutationAttach, self).form_valid(form) class QoutationAttachListView(ListView): template_name = "ePROC/Acquisition/qoutationattach_list.html" model = QoutationSelection queryset = QoutationSelection.objects.all() context_object_name = 'query_results' paginate_by = 10 def get_context_data(self, **kwargs): context = super(QoutationAttachListView, self).get_context_data(**kwargs) context['range'] = range(context["paginator"].num_pages) return context forms.py class QoutationAdd(forms.ModelForm): class Meta: model = QoutationSelection labels = { "Status":"Status", "AcqID":"Acquisition ID", "QoutID":"Qoutation ID", } fields=['QoutID','Status'] QoutID=forms.ModelMultipleChoiceField(queryset=QoutationModel.objects.all()) models.py class CreateACQModel(models.Model): RequestItem=models.ForeignKey(CreateReqModel,on_delete=None,related_name='CreateReqID') ACQProcDate=models.DateTimeField(auto_now_add=True) ACQStatus=models.CharField(default='Procure',max_length=40) def __str__(self): return '%s' %(self.RequestItem) def get_absolute_url(self): return reverse('request-list', kwargs={'pk':self.id}) class QoutationModel(models.Model): … -
Wrong URL for Django filefields download link
I'm currently doing a web app that would store files. I have my class lobby like this : class Lobby(models.Model): (...) id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular lobby across whole database") pdf = models.FileField(upload_to='./documents/',blank=True, null=True) (...) def file_link(self): if self.pdf: return "<a href='%s' download>Download</a>" % (self.pdf.url) else: return "No attachment" file_link.allow_tags = True file_link.short_description = 'file_link' (...) When I'm instanciating a lobby I can easily upload my pdf and it goes to the right place (at the root of my app in file named 'documents'). But here's the problem, when I'm trying to download the file thanks to a link by calling: <p><strong>File:</strong> {{ lobby.file_link|safe}}</p> I'm not getting document, but a file not found error Firefox doesn't find the file http://127.0.0.1:8000/catalog/lobby/73d5aede-96af-445e-bec9-8c4522d37ce7/documents/the document.pdf It's like the file_link doesn't send the place the file is stored, but the name the url to go to the page a a specific lobby, then the URL. What did I do wrong?? Thanks. -
Is there a project for Django management utils?
I have just been forced to write some decorators that can be used to require login and do permission checking on Django management commands. I am thinking this is so general purpose that it should be available to the public. Is there a PyPI package where this would make sense to include, or should I start my own project? I have tried searching for "management", but I wondering whether there is something that is named differently, that I don't know off. -
Django models, how to convert existing UUID field to Foreign Key?
I have and existing database where I have models.py as follows: class basicData(models.Model): companyId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) companyName = models.CharField(max_length=1000,null=True) emailIdCompany = models.EmailField(max_length=1000,blank=False,null=True) numberOfEmployees = models.CharField(max_length=1000,null=True) contactNumberCompany = models.CharField(max_length=1000,null=True) class extraData(models.Model): companyId = models.UUIDField(default=uuid.uuid4, editable=False) interaction = JSONField(db_index=True,null=True) I want to update the models.py as follows: class basicData(models.Model): companyId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) companyName = models.CharField(max_length=1000,null=True) emailIdCompany = models.EmailField(max_length=1000,blank=False,null=True) numberOfEmployees = models.CharField(max_length=1000,null=True) contactNumberCompany = models.CharField(max_length=1000,null=True) class extraData(models.Model): companyId = models.ForeignKey(globalcompaniesbasicdatabase) interaction = JSONField(db_index=True,null=True) How should I do this without loss of data. -
Serializer Extend User field by same level with Main User in Django Rest Framework
I write a Extend User serializers in Django like this: File Models.py Extend User App: class Profile(models.Model): user = models.OneToOneField(User, unique=True) nickname = models.CharField(max_length=50, null=True, blank=True) gender = models.CharField(max_length=100, choices=GENDER_CHOICES, blank=True, null=True, default='MALE') File serializers.py Extend User App: class ProfilePatchSerializer(ModelSerializer): languages = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='EN') gender = serializers.ChoiceField(choices=GENDER_CHOICES, default='1') class Meta: model = Profile fields = [ 'gender', 'language', ] This serializer in order to extend for Main User Serializers: class UserCreateUpdateSerializer(ModelSerializer): profile = ProfilePatchSerializer() class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'profile', ] As a result, my API will render into this: { "id": 1, "username": "feedgit", "first_name": "Feed Git", "profile": { "gender": Male, "languages": English } } But now I want to API in same level with main User like this: { "id": 1, "username": "feedgit", "first_name": "Feed Git", "gender": Male, "languages": English } Please help me to do this. Thanks in advance! -
Define a self kwarg argument within a FORM request
Here is what I am trying to solve. In my app I invite users to join a team. So I created a form that ask only for a mail, generate a random password, create a user and then send a mail to the user. The user go to the mail and finish his registration by providing first name last name and update his password and is finally part of the team. I gave it a try, but my code was bad : def ApplicantRegister2(request, pk1=None): InviteFormSet = formset_factory(ApplicantForm2) if request.method == 'POST': formset = InviteFormSet(request.POST) if(formset.is_valid()): for i in formset: mail = i.cleaned_data['Email'] user = MyUser(email = mail) password = MyUser.objects.make_random_password() user.set_password(password) user.is_active = False user.is_candidate = True user.save() u1 = user.id #get user id a1 = MyUser.objects.get(email = request.user.email) #get HRuser email a2 = Project.objects.filter(project_hr_admin = a1) #get all project created by the HRuser a3 = a2.latest('id') # extract the last project a4 = a3.team_id # extract the team linked to the project a4.applicant.add(u1) # add the member to the team current_site = get_current_site(request) message = render_to_string('acc_active_email.html', { 'user':user, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail_subject = 'You have been invited to SoftScores.com please sign in to get access … -
Django content type for both static and dynamic content
we're using Django 1.11 (soon moving to 2.0, so it's OK to answer for that as well). We are solving the following problem: We have a Ticket model with several fields, some of them are ForeignKey and some of them are ChoiceField. We have a Condition model with which we want to target a specific value of some of the Ticket fields. If there were just ForeignKey fields in Ticket, we would use GenericRelation (ContentTypes). However there are also "static" values of ChoiceField. One of our colleagues proposed a solution that for every Condition we create a hidden instance of Ticket that is never used anywhere else and is just there to hold the information about the ChoiceField value - and this Ticket is then linked to Condition through GenericRelation. But this sounds like a really bad idea. I was thinking that many developers had to solve this. Is there any good and easy way how to do this? Thank you. -
How to load the webpack bundles created in 'ng build --prod' in django templates?
I am using Angular 4 for client side/frontend and using django 1.11 for backend. I edited .angular-cli.json to redirect the bundles output directory to django app assets ./.angular-cli.json { ... "apps":[ .., "outDir": "django_app/assets/webpack_bundles/", .... ], ... } when building ng build --dev (which for development environment), will create the webpack bundles under assets ./django_app/assets/webpack_bundles django_app/ - assets/ -- webpack_bundles/ --- inline.bundle.js --- main.bundle.js --- polyfills.bundle.js --- vendor.bundle.js then running python3 manage.py collectstatic to migrate in static files and to import it in django templates ./django_app/templates/sample.html {%load static %} <script src="{% static 'webpack_bundles/inline.bundle.js' %}"></script> <script src="{% static 'webpack_bundles/polyfills.bundle.js' %}"></script> <script src="{% static 'webpack_bundles/vendor.bundle.js' %}"></script> <script src="{% static 'webpack_bundles/main.bundle.js' %}"></script> The question is, how can I load webpack bundles on a django templates if building for production ng build --prod? Which will create bundles in minified version and with hash for caching purposes. ./django_app/assets/webpack_bundles django_app/ - assets/ -- webpack_bundles/ --- inline.[hash].bundle.js --- main.[hash].bundle.js --- polyfills.[hash].bundle.js --- vendor.[hash].bundle.js Tried the solution of having ng build --prod --output-hashing none, but this is not a best practice because of caching. Tried using django_webpack_loader, but it is not applicable for angular 4 webpack.config.js -
what is the best way for Database Archiving using django
I have a database with 30 tables which has primary keys and foreign keys. I wish to archive the 1 year data from tables. Could any one please suggest me the best way to Archive the related data of all the tables. Thanks in advance Sridhar.