Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form initialization issue - how to set localize in superclass?
I have a model form where I mix imperial and metrics units (e.g. m/s and fps) depending on locale of user, so the form is a mix of using form-fields added manually and referencing the model. Now, we do this in many forms so have created a super-class LocalizedModel form that simply iterates over the sub-class fields and if decimal, then sets localized = True for all field. The expected outcome is that when generating the form in template; all decimal fields should be localized (, or .) and use text-input and not number. The strange thing is that; when using the super-class that iterates over fields and sets thing, form is not localized and number-input is still used. BUT when setting localize = True directly in the field it works (text and decimal separator is set correctly) Python 3 and Django 2.0.6 and USE_L10N is True. Any idea why this is the case? See code-snippets below # -- example -- class RecipeForm(LocalizedModelForm): cost = forms.DecimalField(label='Cost', initial=0, min_value=0, localize=True) cost_2 = forms.DecimalField(label='Other Costs', initial=0, min_value=0) # cost has manually set - works in template # cost_2 and weight - expected that LocalizedModel for should set them, but no class Meta: … -
Django Static Files via S3
I have been trying to setup S3 to serve my static files. The files appear to be in a bucket and the links to the files seem to be comming through OK in my templates but the files are not actually applied. When I look at the inspector of my browser I see script tags like these <script src="https://mybucket.s3.amazonaws.com/static/js/jquery.js?AWSAccessKeyId=REDACTED&amp;Signature=REDACTED&amp;Expires=00000000"></script> Note: I have changed the values in the links to REDACTED and 00000000 When I go to just https://mybucket.s3.amazonaws.com/static/js/jquery.js I can actually see the code. But when I go to https://mybucket.s3.amazonaws.com/static/js/jquery.js?AWSAccessKeyId=REDACTED&amp;Signature=REDACTED&amp;Expires=00000000 I get the following message This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>InvalidRequest</Code> <Message> The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. </Message> <RequestId>REDACTED</RequestId> <HostId> REDACTED </HostId> </Error> -
Django many-to-many field in template and view
In my models there are some manytomany fields. I've been struggling to make them appear in the template. One is a regular ManyToMany field, the other one uses through. The problem is that the amount is not shown. I understand that currently the itteration is only defined for component in pcbuilds.components.all. How to manage the amount in there as well? models.py: class Component(models.Model): name = models.CharField(max_length=100, unique=True,help_text='Component name') manufacturer = models.IntegerField(blank=True,null=True,choices=MANUFACTURERS) model = models.CharField(max_length=100,unique=True,blank=True,null=True, help_text='model') class Tag(models.Model): title = models.CharField(max_length=100,unique=True,blank=True,null=True, help_text='tagname') class PCBuilds(models.Model): title = models.CharField(max_length=50, help_text='PC build title') components = models.ManyToManyField(Component,help_text='Pick your components from the list or create and add them.',through='Componentlist') subtitle = models.CharField(blank=True,max_length=80, help_text='Subtitle') def __str__(self): return self.title class Componentlist(models.Model): component = models.ForeignKey(Component, on_delete=models.CASCADE,related_name='components') pcbuild = models.ForeignKey(PCBuilds, on_delete=models.CASCADE,related_name='pcbuilds') amount = models.FloatField(null=True,help_text='amount') template: <div class="card-deck"> {% for pcbuilds in object_list|slice:":3" %} <div class="card" style="width: 18rem;"> <div class="card-header"> <a href="{% url 'pcbuilds_detail' pcbuilds.pk %}"> <span class="font-weight-bold">{{ pcbuilds.title }}</span></a> &middot; <span class="text-muted">{{ pcbuilds.subtitle }}</span> </div> <div class="card-body"> <ul> {% for component in pcbuilds.components.all %} <li>{{ component.name}}{{ component.manufacturer}}{{ component.model }}{{ componentlist.amount }}</li> {% endfor %} </ul> </div> <div class="card-footer text-center text-muted"> {% for tag in recipe.tags.all %} Tags: {{ tag.title }} {% endfor %} </div> </div> <br /> {% endfor %} -
How to prevent recursive activation of form submit button when activating form once on page load with javascript?
I am creating a Django app that retrieves data from a database based on a form. The form is just a collection of checklists. The data is then used to create a plot using Bokeh. The app works. That is, when the submit button is pressed, the app accepts user input, collects relevant data and plots a graph. My problem is that I want to form to be submitted once as soon as the page loads, in order to display a graph with the default settings. The current behaviour is that no graph is displayed until the user presses the submit button. Here is an abstract example that kind of reproduces my problem. Please note that my problem isn't exactly reproduced by this example because my inexperience with html/javascript makes it difficult to make html/javascript equivalent of what Django is doing. However, here's an attempt. Just bear in mind that a graph should be dynamically produced when the button is pressed - which graph is shown depends on user input. <div id='form-container'> <form action='.' name='ctrl-panel' method='post' class='form-check-inline'> <ul> <li> <label id="label1"> <input id='label1' type='checkbox' name='checkbox1' value='A' checked='checked'>Checkbox 1 </label> </li> <li> <label id="label2"> <input id='label2' type='checkbox' name='checkbox2' value='A'>Checkbox 2 </label> … -
DRF ModelMultipleChoiceFilter - invalid value in one of many params results in empty list
I have a project that is built using Django REST Framework. I have models Item and Tag, between which there's a many-to-many relationship. When requesting a list of Item instances, I am using ModelMultipleChoiceFilter to filter Item list by tags. Here's my filters.py: import django_filters from .models import Item, Tag class ItemTagFilter(django_filters.FilterSet): tags = django_filters.ModelMultipleChoiceFilter(name='tags__text', to_field_name='text', queryset=Tag.objects.all(), conjoined=False,) class Meta: model = Item fields = ['tags'] As you may see, since the value conjoined is False by default, I expected any Item instance having any of the Tag texts I requested to be included in the resulting list. And it seems to be working for the existing Tag instances recorded in the database. The problem is, when I enter a non-existing Tag text, an empty list is returned, even if I have sent several Tag texts alongside it which do exist in the database. (i.e. I expected the filter to return the union of elements which have any of the tags I sent in my request) I looked into the Django REST Framework documentation and several relevant SO posts like this one, but I could find neither the root cause of the issue, nor a solution to it. I'd appreciate … -
Django - DetailView with FormMixin and initial
I have DetaiView for my post and I want to use a form in this view so I decided to use DetailView with FormMixin. I need to set some initial to this form and I don't know how to do it. Here is my code: models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField("Nick", max_length=80) email = models.EmailField() body = models.TextField("Treść") created = models.DateTimeField("Utworzono", auto_now_add=True) updated = models.DateTimeField("Zaktualizowano", auto_now=True) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ( "name", "email", "body" ) views.py class PostDetailView(FormMixin, DetailView): model = Post form_class = CommentForm template_name = "newspaper/post-detail.html" def get_success_url(self): return reverse("post-detail", kwargs={"slug": self.object.slug}) def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context["form"] = self.get_form() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): return super().form_valid(form) So I want to post in CommentForm to post of this DetailView. I hope you understand :D. Thanks in advance for the help! -
Django Photologue not uploading images
I have photologue setup with the included templates, and by all accounts it should be working fine. All included URLS work fine, all pages load and there are no error codes from the console (I am using runserver with manage.py). In settings.py, I have the following 2 lines: MEDIA_ROOT = '/root/jake/temp_uploaded_images' MEDIA_URL = '/root/jake/images/' Then, I have included the output from the console showing accessing the photologue pages, and then accessing the django admin interface to upload a photo. [24/Aug/2018 18:04:02] "GET /photologue/gallery/ HTTP/1.1" 200 3008 [24/Aug/2018 18:04:03] "GET /static/css/screen.css HTTP/1.1" 200 274 [24/Aug/2018 18:04:03] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 109518 [24/Aug/2018 18:06:55] "GET /admin HTTP/1.1" 301 0 [24/Aug/2018 18:06:56] "GET /admin/ HTTP/1.1" 200 9647 [24/Aug/2018 18:06:56] "GET /static/admin/css/base.css HTTP/1.1" 200 16225 [24/Aug/2018 18:06:56] "GET /static/admin/css/dashboard.css HTTP/1.1" 200 412 [24/Aug/2018 18:06:56] "GET /static/admin/css/responsive.css HTTP/1.1" 200 17976 [24/Aug/2018 18:06:56] "GET /static/admin/img/icon-deletelink.svg HTTP/1.1" 200 392 [24/Aug/2018 18:09:22] "GET /admin/photologue/photo/add/ HTTP/1.1" 200 9672 [24/Aug/2018 18:09:22] "GET /static/admin/css/forms.css HTTP/1.1" 200 8505 [24/Aug/2018 18:09:22] "GET /admin/jsi18n/ HTTP/1.1" 200 3185 [25/Aug/2018 09:49:32] "POST /admin/photologue/photo/add/ HTTP/1.1" 302 0 [25/Aug/2018 09:49:32] "GET /admin/photologue/photo/ HTTP/1.1" 200 8189 [25/Aug/2018 09:49:32] "GET /static/admin/css/changelists.css HTTP/1.1" 200 6170 [25/Aug/2018 09:49:32] "GET /static/admin/img/search.svg HTTP/1.1" 200 458 [25/Aug/2018 09:49:32] "GET /admin/jsi18n/ HTTP/1.1" 200 3185 [25/Aug/2018 09:49:32] … -
Set django running on VPS
I set my Django website on Ubuntu VPS. Everything works perfectly but when I close the Putty connection console, the website can't access. What things need to configure for django website running background on VPS. -
django get the parameters after oauth
Trying to make oauth with using django allauth. I want to perform some operations with the email of the user in pre_social_login method. But I am not sure how to get the details of the user. I can't find where the details of the user are stored. I want to get the email of the user and perform some operations with it. But I am not sure how exactly to do it ? my settings.py file code: ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = \ {'github': { 'SCOPE': ['user:email',], }, 'google': { 'SCOPE': ['https://www.googleapis.com/auth/userinfo.profile', 'email'], 'AUTH_PARAMS': {'access_type': 'online'} }, } Defined an adapter for it and it has a function def pre_social_login(self, request, sociallogin): print(requst.POST['email']) // email of the user //perform some operations with the email Presenlty I am getting an error of no attribute named email, how actually to get the mail of user? Thanks! -
Django Heroku: No Such File or Directory for image (image is in repo)
I'm using the following to attach a picture (which is committed with the Github repo) to an email: twitter_image = MIMEImage(open(get_static('img/twitter.png'), 'rb').read(), _subtype='png') twitter_image.add_header('Content-ID', '<{}>'.format('twitter.png')) get_static is defined as: from django.contrib.staticfiles.finders import find from django.contrib.staticfiles.templatetags.staticfiles import static def get_static(path): if settings.DEBUG: return find(path) else: return static(path) The same code is working in another project perfectly both in development and in production. But for some reason it's failing on Heroku with this project, when I run the email function on Heroku it returns an error like: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/app/notifications/models.py", line 75, in email_users twitter_image = MIMEImage(open(get_static('img/twitter.png'), 'rb').read(), _subtype='png') FileNotFoundError: [Errno 2] No such file or directory: '/static/img/twitter.6a4fa62e22f6.png' -
How to have the url format like xyz.com/template.html/?token=&uid=/ using django rest_auth
I am making the program, whenever the user forgets his password, he get's an email after entering the email id. This thing is working. It is even sending the url in the mail and everything is working. But currently my url in the email is like this. http://127.0.0.1:8000/account/reset/MTg/4z1-d4e4774f2d5b3cad07a9/ But I want my url to be in the format. htttp://127.0.0.1:8000/account/reset/?uid=xyz&token=bdfjkdbfkjdbf. This is just an example. Yeah I can change that account/reset to my template. That will be done. But what I want is it's format should be like this. It's just a rough idea. One of the most important thing, I want to use only django-rest-auth. I am not using anything else. Please help me ASAP. -
django forms print select values
I am trying to return the selected choice value from a dropdown menu in django. The option (in html) is dynamically populated from the database's model primary key. HTML <form class="student-ID-search" action="{% url 'new_coach_schedule' %}" method="post" > <select class="form-control" id="student_select"> <option>Select student ID</option> {% for student_data in students_data %} <option value="{{ student_data.pk }}">{{ student_data.pk }}</option> {% endfor %} </select> </form> <button class="btn" type="submit" name="search_result" value="select> <i class="fa fa-search"></i> </button> views.py students_data = Student.objects.all() search_result = NewStudentSearchForm(request.POST) if 'search_result' in request.POST: test_print_to_screen = search_result['student_select'] print(test_print_to_screen) args = {'students_data': students_data} return render(request, 'static/html/new_coach_schedule.html', args) else: return render(request, 'static/html/new_coach_schedule.html', args) forms.py class NewStudentSearchForm(forms.Form): search_field = forms.CharField(max_length=50) # This is for something else. student_select = forms.ModelChoiceField(queryset=Student.objects.all(), empty_label=None) When I make use of ModelChoiceField, test_print_to_screen does not print out the selected choice that I chose in the html select box.. It prints out everything instead. EG: <select name="student_select" id="id_student_select"> <option value="5">Student object (5)</option> <option value="6">Student object (6)</option> <option value="7">Student object (7)</option> <option value="8">Student object (8)</option> <option value="9">Student object (9)</option> <option value="10">Student object (10)</option> <option value="11">Student object (11)</option> <option value="12">Student object (12)</option> <option value="13">Student object (13)</option> </select> How can I go about in my forms.py so that when i select the value in my browser, it … -
Import error when using django with WSGI
I am working on a little hobby project which I want to publish under an open source license. I use the django framework 2.0 and I am now testing my application on the Apache web server. I use Anaconda3 to manage the virtual environment for the project. I already tested my application with SQLite as db backend, but if I use MySQL instead, the web server log says that mysqlclient can't import _mysql. I tried to run the dj development server on the python vm and it is working. Could you please help me? -
Django : shell plus --print-sql showing incomplete sql if the query is long
I am using DJango 2.0. I have the the following models: class SingleMeasurements (models.Model): MASS = 'kg' VOLUME = 'ltr' PIECES = 'pcs' MUNITS_CHOICES = ( (VOLUME, 'Liter'), (MASS, 'Kilogram'), (PIECES, 'Pieces'), ) name = models.CharField(max_length=200,unique=True,null=False) slug = models.SlugField(unique=True) formtype = models.CharField(max_length=10,choices=MUNITS_CHOICES,verbose_name="Units") quantity = models.DecimalField(max_digits=19, decimal_places=10) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) class Recipe(models.Model): MASS = 'kg' VOLUME = 'ltr' PIECES = 'pcs' MUNITS_CHOICES = ( (MASS, 'Mass'), (VOLUME, 'Volume'), (PIECES, 'Pieces'), ) name = models.CharField(max_length=200) slug = models.SlugField(unique=True) tags = models.ManyToManyField(Tag,related_name='recipes_recipe_tag',blank=True) primary_unit = models.CharField(max_length=10,choices=MUNITS_CHOICES,default=VOLUME,verbose_name="Preferred Display Units",null=True,blank=True) mass_unit = models.ForeignKey(SingleMeasurements,on_delete=models.PROTECT,related_name='recipe_singlemeasurement_mass_unit',blank=True,null=True) mass_quantity = models.DecimalField(max_digits=19, decimal_places=10,null=True,blank=True) volume_unit = models.ForeignKey(SingleMeasurements,on_delete=models.PROTECT,related_name='recipe_singlemeasurement_volume_unit',blank=True,null=True) volume_quantity = models.DecimalField(max_digits=19, decimal_places=10,null=True,blank=True) pieces_unit = models.ForeignKey(SingleMeasurements,on_delete=models.PROTECT,related_name='recipe_singlemeasurement_pieces_unit',blank=True,null=True) pieces_quantity = models.DecimalField(max_digits=19, decimal_places=10,null=True,blank=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) I have opened Django shell by the following command: python manage.py shell_plus --print-sql --ipython I am trying to run the following command Recipe.objects.select_related('mass_unit','volume_unit','pieces_unit').all() the output is: In [19]: Recipe.objects.select_related('mass_unit','volume_unit','pieces_unit').all() Out[19]: SELECT "recipes_recipe"."id", "recipes_recipe"."name", "recipes_recipe"."slug", "recipes_recipe"."primary_unit", "recipes_recipe"."mass_unit_id", "recipes_recipe"."mass_quantity", "recipes_recipe"."volume_unit_id", "recipes_recipe"."volume_quantity", "recipes_recipe"."pieces_unit_id", "recipes_recipe"."pieces_quantity", "recipes_recipe"."updated", "recipes_recipe"."timestamp", "single_measurements_singlemeasurements"."id", "single_measurements_singlemeasurements"."name", "single_measurements_singlemeasurements"."slug", "single_measurements_singlemeasurements"."formtype", "single_measurements_singlemeasurements"."quantity", "single_measurements_singlemeasurements"."updated", "single_measurements_singlemeasurements"."timestamp", T3."id", T3."name", T3."slug", T3."formtype", T3."quantity", T3."updated", T3."timestamp", T4."id", T4."name", T4."slug", T4."formtype", T4."quantity", T4."updated", T4."timestamp" FROM "recipes_recipe" LEFT OUTER JOIN "single_measurements_singlemeasurements" ON Execution time: 0.001236s [Database: default] And we can see the sql … -
How to ensure Django generate postgres table schema for "timestamp with time zone" with default "now()"
I have the following django data model class ApiLog(models.Model): name = models.TextField(blank=False, null=False) ts = models.DateTimeField(default=timezone.now, blank=False, null=False) ip_address = models.GenericIPAddressField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) It ends up with database django=# \d+ users_apilog Table "public.users_apilog" Column | Type | Collation | Nullable | Default | Storage | Stats target | Description ------------+--------------------------+-----------+----------+------------------------------------------+----------+--------------+------------- id | integer | | not null | nextval('users_apilog_id_seq'::regclass) | plain | | name | text | | not null | | extended | | ts | timestamp with time zone | | not null | | plain | | ip_address | inet | | | | main | | user_id | integer | | not null | | plain | | Indexes: "users_apilog_pkey" PRIMARY KEY, btree (id) "users_apilog_user_id_2eb2b1cf" btree (user_id) Foreign-key constraints: "users_apilog_user_id_2eb2b1cf_fk_users_user_id" FOREIGN KEY (user_id) REFERENCES users_user(id) DEFERRABLE INITIALLY DEFERRED Since, this table will also be accessed by non-django app. I need to make sure the auto timestamp generation (For column ts) is fully handled by postgres, not python. I don't expect to have Column | Type | Collation | Nullable | Default | Storage | Stats target | Description ------------+--------------------------+-----------+----------+---------+---------+--------------+------------- ts | timestamp with time zone | | not null | | plain | … -
Django mariadb error (1045, "Access denied for user 'myuser'@'localhost' (using password: YES)")
I am trying to connect my django application to mariadb, but getting error OperationalError at /blog/ (1045, "Access denied for user 'myuser'@'localhost' (using password: YES)") Here are the relevent settings I am using: [settings.py] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'testdatabase', 'USER': 'myuser', 'PASSWORD': 'dbpass', 'HOST': '', 'PORT': '' } } I used the following query to create DB user: [Logged in as root] MariaDB [(none)]> GRANT ALL PRIVILEGES ON testdatabase.* to 'myuser'@'localhost' IDENTIFIED BY 'dbpass'; MariaDB [(none)]> FLUSH PRIVILEGES; What am I missing here? It works fine when using root user to connect to database (I am messing up user privileges in some way). If someone could correct me? Note: I am able to login as myuser from terminal successfully. -
multiple images upload in Django
I have two models and two different forms. Tow forms are combined in a single view function. The two forms are combined in a single HTML form. Everything is working fine when I submit the HTML form except the images are not saved. Here are the tow models: class Posts(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE) post_category = models.ForeignKey(Post_Category, on_delete=models.CASCADE) post_title = models.CharField(max_length=256) post_detail = models.TextField(max_length=65536) def __str__(self): return "%s %s %s %s " % ( self.user, self.post_category, self.post_title, self.post_detail) class Meta: verbose_name_plural = "Posts" class Images(models.Model): post = models.ForeignKey(Posts, on_delete=models.CASCADE) images = models.ImageField(upload_to='images', blank=True, null=True ) def __str__(self): return "%s %s" % (self.post, self.images) class Meta: verbose_name_plural = "images" the forms are: class PostsForm(forms.ModelForm): class Meta: model = Posts fields = [ 'post_category', 'post_title', 'post_detail', ] class ImagesForm(forms.ModelForm): def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(ImagesForm , self).__init__(*args, **kwargs) self.fields['car_images'].widget.attrs.update({'class' : 'image', 'style':'display:none','id':'input-image-hidden', 'onchange':"document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" , 'type':'file', "name":"images", 'accept':'image/*'}) class Meta: model = Images fields = [ 'images', ] widgets = { 'images': forms.ClearableFileInput(attrs={'multiple': True}), } Here is the view function: from django.forms import inlineformset_factory from django.utils.translation import ugettext_lazy as _ def post(request): form = PostsForm() imagesForm = ImagesForm() template_name = 'path/to/template.html' success_url = 'user_profile.html' form = PostsForm(request.POST or None) imagesForm … -
Implementation of Django Direct-message framework
Hi I am trying use django direct-message. It's a framework to send user to user message. A part of the Documentation says:- Import the Message Management API on top of your views.py from directmessages.apps import Inbox Send message: Inbox.send_message(from_user, to_user, message) List all unread messages: Inbox.get_unread_messages(user) Read a message (and mark as read): Inbox.read_message(message) Print a message as : : Inbox.read_message_formatted(message) Print a list of all conversation partners for a user: Inbox.get_conversations(users) Get a conversation between two users: Inbox.get_conversation(user1, user2, _limit_, _reversed_, _mark_read_) How do I implement this functionality in my project? -
Django social app integration, auth namespace is not recognised?
I am having problem with facebook login app integration the problem is 'auth' is not a registered namespace the problematic part is the: <p> {% if user and not user.is_anonymous %} Hello {{ user.get_full_name|default:user.username }}! {% else %} I don't think we've met before {% endif %} </p> <a href="{% url 'social:begin' 'facebook' %}?next={{ request.path }}">Login</a> <a href="{% url 'auth:logout' %}?next={{ request.path }}">Logout</a> I got that auth is not recognized but in the tutorial there were no problem with that. I am using django versio 1.9.5. -
Django back button issue after logout
I am displaying same home page for both logged-in users and logged-out users. But the change is in navbar. Upon login there will be name of the user displayed. And upon logout nothing will be displayed. If I logout and click back button I see the back previous page getting displayed (i.e the one with the user name). I searched a bit about it and found even few questions about it. But there decorators are used to prevent logged out users to to come back. SO that that page will get prevented from loading again. But here as I am displaying the same page for both the users, how to accomplish it ?? How to prevent navbar from showing user name of users upon logout and clicking back button. My navbar code:: {% if request.user.is_authenticated %} <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">{{ request.user.username }}</a> <ul class="dropdown-menu" role="menu"> <li><a href="{% url 'profile' request.user.username %}">Profile</a></li> <li><a href="{% url 'logout' %}">Logout</a></li> {% else %} {% ifequal request.path '/accounts/login/' %} <li><a href="{% url 'signup' %}">Sign Up</a></li> {% else %} <li><a href="{% url 'login' %}">Login</a></li> {% endifequal %} </ul> </li> {% endif %} Thanks in advance! -
Creating a context object with values from three related models
I can't seem to figure this out. My view takes an argument for Team.id, and I want to return a context object with each User object with a certain value in User.profile.team and the associated date from Reports. I feel like I started on the right track, but am missing something. The output of my template contains all the data I'm trying to get, but not in a way that can be displayed logically. Basically, I'm using models similar to the following: class Reports(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.PROTECT) product = models.CharField(max_length=15) apps_activated = models.IntegerField(blank=True, null=True) prem_submitted = models.DecimalField(max_digits=30, decimal_places=2) class Team(models.Model): name = models.CharField(max_length=255) leader = models.ForeignKey(User,on_delete=models.PROTECT) Extended user profile: class Profile(models.Model): COORDINATOR = 1 LEADER = 2 ADMIN = 3 ROLE_CHOICES = ( (COORDINATOR, 'Coordinator'), (LEADER, 'Leader'), (ADMIN, 'Admin'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.PROTECT,null=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True) The closest I got in my view to return the desired data is with the following: team = 1 team_name = Team.objects.get(id=team) team_users = User.objects.filter(profile__team=team).all() team_stats = [] for user in team_users: team_stats.append(Reports.objects.filter(user_id=user.id)) With a template that looks like: {% block content %} <h1>{{ team }}</h1> <ul> {% for user in team_users %} <li><a href="/reports/user/{{ … -
PermissionError [Errno 13] Permission denied: 'After.png'
I built a Web site using the Django framework, one of which was to process images uploaded by the user and save them in a folder for download, but encountered an error ([Errno 13] Permission denied: After. png'). I use (python3 manage. py runserver) and it works, but it doesn't work when deployed with Apache 2. I knew it was a problem with the permissions of Ubuntu, but I couldn't fix it after modifying the permissions of the file. I hope someone can give me some advice. Thank you very much indeed. My code: from PIL import Image import numpy as np # use PIL.Image to save picture as 'After.png' Image.fromarray(im).save('After.png') # for download file=open('After.png','rb') response =HttpResponse(file) response['Content-Type']='application/octet-stream' response['Content-Disposition']='attachment;filename="After.png"' return response Error info PermissionError at /Text_embed/embedding_info/ [Errno 13] Permission denied: 'After.png' Error info 1 Permission -
Django migrations stuck on 'Applying...' (1.11)
I'm trying to apply a fairly large migration and it is stuck on 'Applying...' See photo of issue. At first I thought it was simply taking a long time, but leaving it overnight (8+ hours) and it's still stuck. Trying it on a different PC resulted in the same issue. There are no missing migrations in the app. As for the content of the migration, I was changing my CharField's from using null=True to default='', after reading the best practices stated here I am using Django 1.11 Here is what the migration file looks like: # -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-08-25 02:14 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('map', '0147_auto_20180824_2029'), ] operations = [ migrations.AlterField( model_name='listing', name='brokerage_remarks', field=models.CharField(default='', max_length=5500), ), migrations.AlterField( model_name='listing', name='client_remarks', field=models.CharField(default='', max_length=5500), ), migrations.AlterField( model_name='listing', name='coop_agent', field=models.CharField(default='', max_length=5100), ), migrations.AlterField( model_name='listing', name='extras', field=models.CharField(default='', max_length=5500), ), migrations.AlterField( model_name='listing', name='heat_source', field=models.CharField(default='', max_length=520), ), migrations.AlterField( model_name='listing', name='lease_term', field=models.CharField(default='', max_length=50), ), migrations.AlterField( model_name='listing', name='level', field=models.CharField(default='', max_length=4), ), migrations.AlterField( model_name='listing', name='listing_agent_custom_text', field=models.CharField(default='', max_length=500), ), migrations.AlterField( model_name='listing', name='listing_agent_from_mls', field=models.CharField(default='', max_length=5100), ), migrations.AlterField( model_name='listing', name='lot_size_code', field=models.CharField(default='', max_length=20), ), migrations.AlterField( model_name='listing', name='occupancy', field=models.CharField(default='', max_length=50), ), migrations.AlterField( model_name='listing', name='other_unit_number', field=models.CharField(default='', max_length=520), ), … -
Is there a better way to handle AJAX file downloads with Django?
I am pretty new to web development in general; I am kind of learning everything on the fly. I recently got a Django application up and running, but I feel pretty dirty/hacky the way I did things. Problem: User needs to input (potentially) a lot of data into an Excel-like spreadsheet on my webpage. I currently am using Handsontable for this. I then need to take the data, run some queries on it, process the results, and return an Excel sheet to the user. Since the Handsontable is rendered via Javascript on page load, and not by Django, I needed to figure out a work around for getting the data into my views.py (I also couldn't strictly use AJAX because I could not figure out how to send the file to the browser once the request was completed). Current solution: I have a Django Textarea hidden. When the user submits the form, I have a Javascript function dump the Handsontable into it in JSON form. Then in my views.py I parse the JSON, and do what I need to do with it, and return the Excel file to the user. Having a hidden field to get around all of this … -
Django: Refresh form page after x minutes?
So I'm making a web form for a kiosk that you can fill out data and then pay using Stripe, is there a way that I could set the page to refresh after 15 minutes or so (just in case someone started filling out the form and then walked away leaving it half filled)