Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Card-flip functionality in Django Quiz website.
I am building a quiz web app in Django, using tomwalker's quiz app? I would like to present the questions on a card, when a user answers the question the card shall flip and show the explanation of question and correct answer. I am new to Django. This is technically my first project.I am not sure how will i populate backside of card with answer explanation, after the user submits he answer. -
Get column data based on foreign key and manytomanyfield in django admin
I am new in Django. I have the following models in Django Category id category_name 1 A 2 B Module (category_id is the foreignkey) id module_name category_id 1 X 1 2 Y 2 category_user (user_id is ManyToManyField with category_id) id category_id user_id 1 1 23 2 2 23 So I want to display data X & Y from module in admin category edit page if that category id 1 & 2 is assigned to user 23. admin.py class categoryAdmin(admin.ModelAdmin): list_display = ('category_name','category_desc') filter_horizontal = ('user',) readonly_fields = ('allowed_module_names',) def allowed_module_names(self, instance): modules = [] module_names = instance.category.values_list("module_name") print(module_names) The query returns blank. Any help is highly appreciated. Thanks in advance. -
Django - access class attributes of a class-based view in middleware
I have a couple of views and each of them must be accesed by no more than one user at a time. Therefore I use a locking service for this. My idea is as follows: - Declare each view like this class DummyView(View): lock = Lock() def dispatch(self, request, *args, **kwargs): ... - In a middleware, do something like this class Middleware: ... def __call__(self, request): # lock = view.get_lock_if_it_has_one (this is what I need help with) lock.acquire() response = self.get_response(request) lock.release() return response How can I access the lock attribute of the view as described? -
Passing Unique Variable when Sending E-Mail with Django
In my Django project I have leads which belong to an organization. One of my views filters these leads by organization and then e-mails them a message. This message is in the form of an html template. Currently this is how I do it: # FIRST: get a list of all the emails leads_email = [] leads = Lead.objects.filter(organization=organization) for lead in leads: if lead.email != None: leads_email.append(lead.email) # SECOND: Django email functions msg = EmailMessage(subject, get_template('email_templates/campaign_email.html').render( { 'message': message, } ), from_email, bcc=to_list) msg.content_subtype = "html" msg.send() However each lead has a unique code associated with them, this field is found under lead.code. I would like to include this code in the email. For example if test@mail.com's unique code is "test123", then I want to include that in the email to test@mail.com alone. I am currently doing this by passing though a variable called message, however this is not unique and every lead gets the same thing. Any idea on how I can accomplish this? Thanks -
How to create a local variable in a html template in django project?
I am a beginner to python and django. Here I am trying to build a website. I have created a class named cluster which actually mean a town or city. As a subclass I have created schools for cluster. Schools have a field school_strength to get strength for each school. Now I have to display the total strength of all the schools that belong to each cluster. This is how I am trying to do that in html template for cluster details by creating a local variable strength to calculate sum from all schools. <div class="col-sm-4 col-md-3"> <div class="panel panel-default"> <div class="panel-body"> <a href="{% url 'music:cluster_detail' state.id region.id cluster.id %}"> {% if cluster.cluster_logo %} <img src="{{ cluster.cluster_logo.url }}" class="img-responsive"> {% else %} <h3>No image to display</h3> {% endif %} </a> <h2>{{ cluster.cluster_name }}</h2> <h4>{{ cluster.cluster_coordinator }}</h4> <h4>{{ cluster.cco_number }}</h4> <h4>{{ cluster.cco_email }}</h4> {% for school in cluster.school_set.all %} {% strength = strength + school.school_strength %} {% endfor %} <h4>{{ strength }}</h4> </div> </div> </div> Please help me in this. -
django web app deployment gunicorn + aws ECS issue
I have working django REST API docker image with following dependencies python 3.5.2, django 1.10.6, djangorestframework 3.6.2, gevent 1.2.2 In my dockerfile, port 5000 is exposed docker command: /usr/local/bin/gunicorn --log-level=DEBUG --worker-class gevent --timeout=300 config.wsgi -w 4 -b :5000 In ECS task definition 5000 container port is forwarded to port 80 of the host. the security group has inbound rule allowing everyone at port 80. When I ran the ECS task with this ECS task definition, following are the application logs, which seems fine. [2017-09-13 16:45:34 +0000] [9] [INFO] Starting gunicorn 19.6.0 [2017-09-13 16:45:34 +0000] [9] [INFO] Listening at: http://0.0.0.0:5000 (9) [2017-09-13 16:45:34 +0000] [9] [INFO] Using worker: gevent [2017-09-13 16:45:34 +0000] [12] [INFO] Booting worker with pid: 12 [2017-09-13 16:45:34 +0000] [13] [INFO] Booting worker with pid: 13 [2017-09-13 16:45:35 +0000] [15] [INFO] Booting worker with pid: 15 [2017-09-13 16:45:35 +0000] [16] [INFO] Booting worker with pid: 16 but I am unable to access the service endpoints using the EC2 instance's public IP/Public DNS address. I tried to get into the running container and curl the application url curl localhost:5000 following are the logs I see (the connections are closed) [2017-09-13 17:42:42 +0000] [14] [DEBUG] GET / [2017-09-13 17:42:42 +0000] … -
Build a list of values from queryset list (pk__in) in special order
i have a model with rating, the results of a filter query must be in a special order for charity (comparing ratings for trainee's) but I can't find the right way to do it. (ok I'm new to Django and python ;) class Bewertung(models.Model): auffassung = models.PositiveSmallIntegerField() interesse = models.PositiveSmallIntegerField() arbeitsabw = models.PositiveSmallIntegerField() aufmerksamkeit = models.PositiveSmallIntegerField() arbeitsgenauigkeit = models.PositiveSmallIntegerField() verhalten = models.PositiveSmallIntegerField() ausb_sach = models.PositiveSmallIntegerField(null=True, blank=True) ausb_fuehr = models.PositiveSmallIntegerField(null=True, blank=True) the query: qs = Bewertung.objects.filter(pk__in=pk_list) i want to compare the integer values in a multi bar chart e.g. auffassung_from_pk(1,2,3) interesse_from_pk(1,2,3) .. n but every try ends in a list with a lot of unordered values (Auffassung_from_pk(1), interesse_from_pk(1), Auffassung_from_pk(2) ..) I can't find a way to solve it nice and efficient in an python way. so I need a little help, can you help? thanks! -
Class based views: How to access variable from form_valid() in success_url()
I have a simple email form that works fine but I want to access recipient in success_url() so I can have a simple "email has been sent to recipient" message in the success template. class FullEmailView(FormView, MyCustomMixin): form_class = EmailForm template_name = 'my_app/email_form.html' def form_valid(self, form, **kwargs): x = MyModel.objects.get(pk=self.kwargs['pk']) recipient = form.cleaned_data.get('email_address') subject = "My Email Subject" sender = "me@myemail.com>" html_message = render_to_string('my_app/email.html', { 'x': x, 'recipient': recipient, }) message = render_to_string('my_app/email.html') send_mail( subject, message, sender, [recipient], html_message = html_message ) return super(FullEmailView, self).form_valid(form) def get_success_url(self, form, **kwargs): x = MyModel.objects.get(pk=self.kwargs['pk']) recipient = #???? <<<--- what do I put here to access recipient from from_valid()? return super(FullEmailView, self).reverse_lazy('email_sent', self, kwargs={"pk": x.pk}) -
How to access multiple image URL from one app to another app in django
I have two apps in my project. They are: Blog app Accounts app In accounts app contains user profiles like Images, Bio, DOB etc, In blog app each user has their own blog page and Each page must have comments so any user can comment any blog. In comments section, it shows username and his unique profile URL.Now my problem is I can't load their profile images. models.py class comments(models.Model): blogger= models.ForeignKey(blog,on_delete=models.CASCADE) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) comment = models.TextField() def get_absolute_url(self): return reverse('blog:comments',args = [ self.id]) views.py commentz = comments.objects.filter(blogger= id).all().order_by('-created')[:10] for pic in commentz: image = UserProfile.objects.filter(user = pic.user) I know this is insane :-/ -
AWS ECS Docker task definition Exit Code 0 Working directory
I've been working to translate my docker compose file into a ecs task definition. Im not sure what exit code 0 refers to nor do I see anything useful when I launch the agent shell in the container. This is the task as it stands. my Django container should be launch using unicorn on port 8000, then nginx should reverse proxy and use port 80 for the frontend. can anyone spot anything or point me in the right direction to debug? Thanks { "requiresAttributes": [ { "value": null, "name": "com.amazonaws.ecs.capability.docker-remote-api.1.17", "targetId": null, "targetType": null }, { "value": null, "name": "com.amazonaws.ecs.capability.ecr-auth", "targetId": null, "targetType": null } ], "taskDefinitionArn": "arn:aws:ecs:eu-west-1:********:task-definition/it-app-task:7", "networkMode": "bridge", "status": "ACTIVE", "revision": 7, "taskRoleArn": null, "containerDefinitions": [ { "volumesFrom": [], "memory": 300, "extraHosts": null, "dnsServers": null, "disableNetworking": null, "dnsSearchDomains": null, "portMappings": [ { "hostPort": 8000, "containerPort": 8000, "protocol": "tcp" } ], "hostname": null, "essential": true, "entryPoint": null, "mountPoints": [], "name": "it-app", "ulimits": null, "dockerSecurityOptions": null, "environment": [], "links": null, "workingDirectory": "/itapp", "readonlyRootFilesystem": null, "image": "*******.dkr.ecr.eu-west-1.amazonaws.com/itapp", "command": [ "bash", "-c", "", "python manage.py collectstatic --noinput && python manage.py makemigrations && python manage.py migrate && gunicorn itapp.wsgi -b 0.0.0.0:8000" ], "user": null, "dockerLabels": null, "logConfiguration": null, "cpu": 0, "privileged": null, "memoryReservation": … -
Displaying the local time for datetime attribute of a model object in Django
I'm trying to make it so the datetime field attribute of a model object is displayed in the template as the local time of the timezone of the current user. The default timezone in my settings is UTC. Here is an example model: models.py class Basic(models.Model): name = models.CharField(max_length=128) created_at = models.DateTimeField(auto_now_add=True The data I want to display is in a table made with django-tables2. However, I already tried two methods and both of them did not work: tables.py attempt 1: class ShipperDataFileDocumentTable(tables.Table): created_at = tables.TemplateColumn(''' {% load tz %} {% localtime on %} {{ record.created_at }} {% endlocaltime %} ''') class Meta: model = Basic fields = ('name', 'created_at') tables.py attempt 2: class ShipperDataFileDocumentTable(tables.Table): created_at = tables.TemplateColumn(''' {% load tz %} {{ record.created_at|localtime }} ''') class Meta: model = Basic fields = ('name', 'created_at') Both of these methods ended up not changing the time at all. For example, I made an object at 12:00 PM. Normally, the template would display it as 4:00 PM in UTC. However, even with those edits, it still displayed the time as 4:00 PM. I'm not sure what I'm doing wrong. -
How can Django recognize language changes in a multilingual web page implemented in Django?
I have already implemented a web page in English using Django. I now have a question when I'm trying to create a web page in Chinese. Pages in Chinese will be separated by prefix(/ch/). I plan to implement a button to change the language, but the question is how Django remembers the changed page. Assuming my domain is 'domain.com', if the language is set to Chinese via the button I would like to have 'domain.com/ch' open when users access 'domain.com'. However, clicking on a button does not seem to be able to control the urlpatterns of Django(urls.py), and it seems necessary to store the variable corresponding to language in javascript. I would appreciate your advice. -
Django Shared database
I have a database on a server "A" with tables : IP, Server and roles. And I wanna ask this database from mulltiple other servers if there is an available ip. I was thinking with a webservice but I'm not sure if it's a good idea. I wanted to use in a loop every 5 secondes asking the server A until there is one but I think it's a bad idea. What kind of solution there is for that, multiple databases and accessing directly? Thanks -
Django save image in folder
I´ve got a piece of code that creates an image using matplotlib in Django and saves it to the root directory. I need to change the folder where matplotlib saves the image to /static/img folder. if (len(funcion) == 2): plotter = plot_regions([ [(lambda x: (matrizRestricciones[0][2]-matrizRestricciones[0] [0]*x)/matrizRestricciones[0][1],True), (lambda x: (matrizRestricciones[1][2]-matrizRestricciones[1] [0]*x)/matrizRestricciones[1][1],True)]], xlim=(0, 10), ylim=(0,10)) plt.grid() plt.savefig("/static/img/imagen.png") plt.close() Any idea how to save them there? Thanks in advance. -
Django Tastypie API Response
I have 2 model classes AppContacts and Contacts as given below - AppContacts Model- class AppContacts(DecoupledModel): app_contact_id = models.AutoField(primary_key=True) uaid = models.ForeignKey(Applications, db_column='uaid', blank=True, null=True) contact_type = models.CharField(max_length=45, blank=True) modified_on = models.DateTimeField(auto_now=True) #contact = models.ForeignKey(Contacts) #modified_by = models.ForeignKey(Contacts, related_name='%(class)s_modified_by') contact_id = models.IntegerField(db_index=True) modified_by_id = models.IntegerField() Contacts Model - class Contacts(DecoupledModel): contact_id = models.AutoField(primary_key=True) employee_id = models.CharField(max_length=20, blank=True, null=True,db_index=True) email_address = models.CharField(max_length=255, blank=True, null=True) userid = models.CharField(max_length=45, blank=True, null=True,db_index=True) modified_on = models.DateTimeField(blank=True,null=True) modified_by_id = models.IntegerField() name = models.CharField(max_length=100, blank=True, null=True) I have created an API to fetch the response but the response format is not as expected. Code - Dehydrate method def dehydrate(self, bundle): if bundle.obj.contact_id: con = Contacts.objects.filter(contact_id=bundle.obj.contact_id).values('name','contact_type', 'last_name', 'email_address', 'userid')[0] if con['contact_type'] == 'group': bundle.data['contact'] = con['last_name'] else: bundle.data['contact'] = con['name'] bundle.data['email_address'] = con['email_address'] bundle.data['userid'] = con['userid'] return bundle Get response method def get_temp(self, request, **kwargs): try: #import pdb; pdb.set_trace() request_method = request.method.lower() result = {} if request_method in ['get']: res_json = CONTACTS_GET_RESPONSE return self.create_response(request, res_json) elif request_method in ['post']: input_data = json.loads(request.body.decode()) logger.info("Input Request: {0}".format(input_data)) return super(CustomContactsResourceBulk,self).get_list(request, **kwargs) else: return http.HttpNotImplemented() except Exception, e: logger.error('Error occurred Custom Application resource search: ' + str(e)) return self.create_response(request, {'error':'Error occurred during search '+str(e)}) Response - [ { "app_contact_id": 33, "contact": "XYZ", … -
Getting pk_set value in django signal runs into an atomic error
This is my signal def my_signal(instance, action, pk_set, **kwrags): instance.animal_count = instance.animals.all().count() instance.save() if action == 'post_add': print pk_set #works print pk_set[0] #no work The weird thing is, if I just print pk_set I get set([1]) but if I try and get the actual value using [0] I run into: TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. Is there any way to just get the pk_set number? I literally only need the id. Note: This happens during test cases. -
Change the order of fields in normal serializer response
Using django rest framework i want to change the serializer response fields order dynamically by a list of given field names output from DRF is the following, {"items": [{"name": "John", "age": 25, "id": 3}, {"name": "Sam", "age": 20, "id": 8}]} My filed order list is: order_list = ['id', 'age', 'name'] What I want is: {"items": [{"id": 3, "age": 25, "name": "John"}, {"id": 8, "age": 20, "name": "Sam"}]} -
View in django launched twice
all my views in Django are launched twice each time i'm calling them with a url. Here is one example: urls.py urlpatterns = [ url(r'^$', views.HomePageView.as_view(), name='home'), # Notice the URL has been named url(r'login/', views.login, name='test'), # Notice the URL has been named url(r'login_click/', 'polls.views.login_click', name='login_click'), url(r'^profiler1_click/', views.profiler1, name='profiler1'), ] views.py def login (request): print("testpagelogin") return render(request, "login.html", {}) The print("testloginpage") is printed twice and i don't understand why. Thanks very much in advance. -
Implement scroll down menu
I am really not an expert with html, css and javascript. I would like to create a scroll like scroll down menu. Instead of 'Pop' in the image, it could be just 'Total customers' or being blank. Could I do that with django-crispy-forms? What is the best way to implement such scroll? -
Django:Find no of days between 2 dates and compare with sysdate and return if it matches
I want to know who is on leave today based on end_date and start_date which are DatetimeField by comparing values between end_date and start_date with sysdate and returning if it matches with sysdate. models.py class leave(models.Model): employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1') start_date = models.DateField() end_date = models.DateField() -
How do I associate the post to a comic in custom form
My model looks like this: class ComicSeries(models.Model): """Model definition for ComicSeries.""" # TODO: Define fields here user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Uploaded by: ' ) title = models.CharField(verbose_name='Series Title', max_length=500) cover = models.ImageField(verbose_name='Series cover', upload_to='comic_series', height_field=None, width_field=None, max_length=None ) description = models.TextField(verbose_name='Description') artist = models.CharField(verbose_name='Artist(s)', max_length=500) date_uploaded = models.DateTimeField(auto_now_add=True) slug = models.SlugField(default='') class ComicIssue(models.Model): """Model definition for ComicIssue.""" # TODO: Define fields here user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Uploaded by: ' ) title = models.ForeignKey(ComicSeries, on_delete=models.CASCADE, verbose_name='Series Title') issue = models.CharField(verbose_name='Issue Number', max_length=500) issue_title = models.CharField(verbose_name='Issue Title', max_length=1000) issue_cover = models.ImageField(verbose_name='Issue cover', upload_to='comic_issues', height_field=None, width_field=None, max_length=None) issue_description = models.TextField(verbose_name='Description') issue_file = models.FileField(verbose_name='Issue file', upload_to='comic_issues_files', max_length=100, help_text='File in pdf or as single image' ) is_favorite = models.BooleanField(default=False) issue_slug = models.SlugField(default='') views.py : class ComicIssueCreate(LoginRequiredMixin, CreateView): model = ComicIssue fields = ['issue_title', 'issue_cover', 'issue_description', 'issue_cover', 'issue_file'] def form_valid(self, form): form.instance.user = self.request.user return super(ComicIssueCreate, self).form_valid(form) I am able to select to which ComicSeries a ComicIssue belongs to in Django admin. But I have a problem doing this in a custom form. Is there a way I can determine to which series an issue belongs to in a custom form using CreateView? -
Django postgres : Is their any way to reference jsonfield of one model into another?
I have a jsonfoeld in a model now I want to use that jsonfield into another model . Is their any way to referrence jsonfield of one model into another? -
Django on Digital Ocean
So I am beginner Django Developer and have been learning by developing local apps. I am looking to finally deploy something so people can use it. I have been looking around at various hosting providers and I am wondering what it's like using Digital Ocean for Django hosting. Specifically what exactly is involved/required with managing a Django app on Digital Ocean. Hostgator, which is another host I've been looking at, does not offer any "one-click" install for stuff like Nginx or anything else which I noticed Digital Ocean does have, so I would have to install that that as well as anything else I'd need myself. I guess my question is after that one click install what is involved with managing a Django app on Digital Ocean? Do I have to learn how to do a ton of other stuff regarding managing a server and dealing with Nginx (I would have to do that on HostGator) or does that One-click install for Django handle all that? Also other than Django, are there any skills that I have to learn in order to be able to do this? -
Is there a way to apply django filters only if the screen has a certain size?
I was wondering if there is a way to apply a filter of Django in a template only if the screen has a certain size. Just like a media query does with Css. -
Docker compose with multiple Dockfiles and images (Django+Angular)
I'm building an app that uses Django and Angular that is split up into two different repositories and docker images. My file structure is: . docker-compose.yml djangoapp/ DockerFile manage.py ... angularapp/ DockerFile ... I've been unable to get it to work properly, all documentation I found on this seem to expect you to have the docker-compose.yml file together with the DockerFile. I've tried multiple different variations but my current (not working) docker-compose.yml file looks like this: version : '3' services: web: build: djangoapp command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" This gives me error can't open file 'manage.py': [Errno 2] No such file or directory. If I go into the djangoapp/ directory and create a docker-compose.yml file there according to the offical Docker docs, it works fine. So it's nothing wrong with the actual build, the issue is accessing it from outside like I'm trying to do.