Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hide thumbnail after its object has been deleted
I am working for an open source Django project. They allow users to attach resources (i.e, image files by uploading them from their PC). Currently, while editing the resource file, the upload form looks like this: clicking on this remove button replaces it with the choose file option to upload a new file like so: Now, what I am supposed to do, is put the thumbnail of the previous file which I wanted to edit besides its file_name.jpg (Remove) and after clicking the remove, bring back the browse box like so: So, in order to achieve this, I include the thumbnail of the resource besides file_name.jpg (Remove) thing in my template, and for replacing it with the upload form on clicking the (Remove) button, i am asked to do something like: {% if form.original_file.value == none %} to determine if the "thumbnail" or "browse file option" should show, which will eliminate the need to add a script. So, I did this: <div class="row"> <div class="col-md-6"> {% csrf_token %} <div class="form-group{% if form.file.errors %} has-error{% endif %}"> --> {% if resource.original_file %} //check if the file exists, if so, display the thumbnail: <div class="panel-body"> --> <img src="{{ resource.thumbnail }}" class="thumb-128"> //the … -
Adding documentation to django app - conflict with angular
I have created documentation for my Django app using apidoc library. It creates docs using angular. App is running on Heroku. Docs are working nicely when I open index.html file, but I cannot open them via http://localhost:5000/docs. Firstly I got this error: "Variables and attributes may not begin with underscores: '__' " , which I was able to bypass by putting {% verbatim %} and {% endverbatim %} into the index.html file. (Which I'm not very happy with in the first place and would like to do it some other way). Then the page is stuck on the loading screen, but when I open it in Chrome I have the following error: "Uncaught SyntaxError: Unexpected token <" in polyfill.js:1 and require.min.js:1 And also 3 warnings: "Resource interpreted as Stylesheet but transferred with MIME type text/html" in vendor/bootstrap.min.cs, vendor/prettify.css and css/style.css We are using apidocs also in other project with Node where it works perfectly, so I think it's an issue with Django. Since the documentation is generated automatically, I would prefer to introduce changes into the app, not docs. I tried it on Chrome and Safari. My questions 1. What can I do to make it work? 2. How can … -
How can I access environment variables directly in a Django template?
I'm looking to do something like this non-working code in my Django template: {% if os.environ.DJANGO_SETTINGS_MODULE == "settings.staging" %} Is something like this possible? My workaround is creating a context processor to make the variable available across all templates, but wanted to know if there is a more direct way to achieve the same result. -
how to get pop-up for individual click?
I am using following code for popup after click on delete and main link of delete is given on permanent-delete button which is displayed on popup window. Html template is {% for obj1 in vastu %} {% if obj1.vastu_key.id == obj.id %} <div class="dropdown"> <button class="btn-menu btn dropdown-toggle pull-right menu" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> <span class="glyphicon glyphicon-option-vertical" aria-hidden="true" aria-label="Right Align"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a href="/dashboard/{{name}}/{{obj1.id}}/edit">Edit</a></li> <li><a class="btnShow">Delete</a></li> </ul> </div> <div class="dialog" style="display: none" align="center"> <form action="/dashboard/{{name}}/{{obj1.id}}/delete"> <input type="submit" value="delete" /> </form> </div> {% endif %} {% endfor %} jquery function is $(function () { $(".btnShow").click(function () { $('.dialog').dialog('open'); }); }); $(".dialog").dialog({ modal: true, autoOpen: false, title: "It will delete permanentaly", width: 300, height: 150, resizable:false }); my problem is that i have to show on popup that is div element of class="dialog" is seperately for each content contains in for loop. The link of edit is working properly and if i give main-delete link on delete which is below edit then it is working properly but i need that i have to popup div after click on delete and the main-delete link i have to give on that popup. currently, by using this code delete link is gets … -
Does it possible re-write `raw-sql` to `django-orm`?
I need to re-write raw-sql to django-orm. But unfortunately I can't do it. Does someone has ideas ?: HttcOrder.objects.raw('''SELECT httc_order.id, httc_order.price, httc_order.quantity, SUM(markedskraft_trade.qty) as positions_quantity FROM httc_order left outer join markedskraft_trade on httc_order.id = markedskraft_trade.httc_order_id WHERE httc_order.order_status in ('new', 'pending', 'confirmed') and httc_order.mk_contract_id = %s group by httc_order.id having positions_quantity is NULL or quantity - positions_quantity > 0 order by httc_order.price desc''', [contract.id]) Example of models: httc: class Order(models.Model): quantity = models.IntegerField(verbose_name=_('Qty')) order_status = models.CharField(max_length=10, choices=ORDER_STATUSES, default=NEW) price = models.IntegerField(verbose_name=_('Prc')) mk_contract = models.ForeignKey( Contract, related_name='httc_orders', verbose_name=_('Markedskraft contract') ) .... markedskraft: class Trade(models.Model): order_id = models.IntegerField(blank=True, null=True, db_index=True) httc_order_id = models.ForeignKey(HttcOrder, blank=True, null=True, db_index=True) qty = models.IntegerField() ....... -
Use select_related and prefetch_related
These are my two classes of the model class class UserProfile(models.Model): user=models.OneToOneField(User) profile_pic=models.ImageField(upload_to='profilepics/%Y/%m/%d/',default='\LoginPage\images\default.jpg') def __unicode__(self): return self.user.username def __str__(self): return self.user.username class Video(models.Model): username=models.ForeignKey(UserProfile,on_delete=models.CASCADE,default="",related_name='uservideos') video=models.FileField(upload_to='videos/%Y/%m/%d/',default='') videotitle=models.CharField(max_length=100) likes=models.PositiveIntegerField(default=0) dislikes=models.PositiveIntegerField(default=0) def __str__(self): return self.video.url This is my view function where I want to select and display all the videos of a particular user using select_related but I get an error saying 'FileDescriptor' object has no attribute 'select_related' def usermainview(request): username=request.POST['username'] tempuser=User.objects.get(username=username) videolist=Video.video.select_related('user').get(username=tempuser) return render(request,'AfterLogin/main.html',{'videolist':videolist}) -
How to display the edited profile picture in django
I am able to upload the profile picture but i am not able edit it I have the form populating with the image browse option, but when I click save, it doesn't actually update in template. but it is working fine in admin views.py def create_form(request): form = AlbumForm(request.POST or None, request.FILES or None) if form.is_valid(): album = form.save(commit=False) album.user = request.user album.image= request.FILES['image'] album.save() return render(request, 'about.html', {'album': album}) context = { "form": form, } return render(request, 'create_form.html', context) def profile_edit(request): if request.method == 'POST': form = AlbumForm(request.POST, instance=request.user.album) if form.is_valid(): album = form.save(commit=False) album.user = request.user form.save() return redirect(reverse('about')) else: form = AlbumForm(instance=request.user.album) args = {'form': form} return render(request, 'profile_edit.html', args) models.py class Album(models.Model): user = models.OneToOneField(User) image = models.FileField() forms.py class AlbumForm(forms.ModelForm): class Meta: model = Album fields = ['image'] profile_edit.html {% extends 'base.html' %} {% block content %} <form action="{% url 'profile_edit' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">save</button> </form> <div> <img src="{{ user.album.image.url }}" class="img-responsive"> </div> {% endblock %} -
Convert single quoted elements in list to double quotes using python
dictt = {'a':1,'b':2,'c':3} executing this code `tuple([i for i in dictt.keys()])` the result is `['a','b','c']` but i want output to be `("a","b","c")` -
Django forms: set intial value
This must be simple, but I'm stuck with it. I have a form that tries to set a str value if related fields in another model are available: forms.py class OtherModelChoiceField(ModelChoiceField): # custom lookup for fields in other model def label_from_instance(self, obj): return "%s" % obj.related_fieldname class ExampleForm(ModelForm): def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) if not self.fields['related_model_field']: self.fields['related_model_field'] = OtherModelChoiceField(OtherModel.objects.all().filter(this_field=self.instance), required=False) else: self.fields['related_model_field'] = OtherModelChoiceField(OtherModel.objects.all().filter(this_field=self.instance), required=False, initial=self.instance.related_fieldname) class Meta: model = ExampleModel fields = ['name', 'address', 'related_model_field'] This is ok for creating a dropdown set of OtherModel.related_fieldname choices if the intial is not set, but when it is set - the initial arg expects an ID generated by the choicefield widget to lookup the value. How do I set the intial to lookup by using the string value 'related_fieldname' in the widget? -
Placing a Django variable inside a URL
I'm creating a list of images, all the images are saved in the same directory so I would just like to change the image name. I've tried this: <a href="#"> <img src="my_server_url/images/"{{ item.name }}".jpg" class="img-responsive"> </a> But it doesn't seem to be working, how can I integrate the variable with the URL? thanks -
How to save/update data using resource without http request in tastypie
I have the data with me. I want to save to model using the resource. I tried this, but getting error: r = MyResource() bundle = r.build_bundle(request=request, data=data) r.save(bundle) It is not working. Can you help me here ? -
Installing Scipy.stats on pythonanywhere
At pythonanywhere I want to upload the page that works fine on my computer. While installing the scipy.stats module using: pip install -U scipy.stats in my virtual environment, I get this response: Collecting scipy.stats Could not find a version that satisfies the requirement scipy.stats (from versions: ) No matching distribution found for scipy.stats checking with pip list, I see that scipy (0.19.0) is installed. How can I install scipy.stats? Thanks -
celery set visibility_timeout not working
When running django celery tasks, i see that my task re execute after every hour, maybe by default visibility_timeout setting, so i try to change visibility_timeout = 120 for re execute task every 120 seconds in celery.py config like this. app.config_from_object('django.conf:settings') installed_apps = [app_config.name for app_config in apps.get_app_configs()] app.conf.broker_transport_options = {'visibility_timeout': 120} app.autodiscover_tasks(lambda: installed_apps, force=True) But it doesn't work, what is the correct way to change visibility_timeout? -
Render new line from a string in HTML document using Mako Templating
How to render new line in a given string in HTML document using Mako Templating such that it behaves as if there is "" tag instead of new line character? -
Why django form field errors is list?
Is it possible that field will have more that one error? As I know error created by clean method by raise forms.ValidationError more that one raise is not possible... so, why form.field_name.errors it's not that form.field_name.error for form.errors everything is logical for field not %) -
Django - manipulating foreign key attributes in template
I'm currently working with a couple of models that have a one to many relationship. I've managed to access all the attributes/foreign key attributes in my template files using template tags and one.many_set.all etc. class One(models.Model) name = models.CharField(max_length=50) class Many(models.Model) name = models.CharField(max_length=50) related = models.ForeignKey(One, null=True, blank=True) def __str__(self): return self.name What I'd like to do is split them up, so for example, have a drop down list for the 'One' model, which, on change, updates another list with it's related 'Many' objects, which I would then work with. I've looked around and there doesn't seem to be anything I can find which specifically helps. Any advice would be much appreciated. Thanks -
DJango REST Framework Read Only field
I have a field owner that is a ForeignKey to User model. This field is required at the time of creation. But it can not be changed later on. How to make fields Non-Editable? -
I am newbie to react.js can i use python as a backend and react as a frontend for data science application
I am writing API in python, When i read the react js documentation it describe's lot about view layer and JSX and i didn't find any good tutorial to start with and apart from that im confused with technology decision shall i go with these technologies or not. help me in taking right decision. -
Comment on posts Django
I want that users comment on posts, but the form in 'blog/index.html' is not displaying ! views.py class IndexView(generic.ListView): template_name = 'blog/index.html' context_object_name = 'posts' def get_queryset(self): return Post.objects.all() def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('blog:index', pk=post.pk) else: form = CommentForm() return render(request, 'blog/index.html', {'form': form}) and here the form within 'blog/index.html' <form enctype="multipart/form-data" method="post" class="post-form"> {% csrf_token %} {{ form.textc }} <button type="submit" class="save btn btn-default">Send</button> </form> -
Unable to access variable user from template in django 1.10
I'm new to django. I'm implementing user login mechanism in my app. When log the user in i can verify by opening admin app if the user is logged in or not and the user does log in. Now when i try to give user a message for example {{ Hello user.username }} i am getting nothing. Below is my complete code. view.py def login_user(request): context = RequestContext(request) if request.method == "POST": login_username = request.POST['username'] login_password = request.POST['password'] user = authenticate(username=login_username,password=login_password) if user is not None: if user.is_active: login(request,user) return HttpResponseRedirect('/albums/') else: print "Your Account is disabled" else: print "Invalid login details: {0}, {1}".format(login_username, login_password) return HttpResponse("Invalid login details supplied.") else: return render(request,'music/login.html',{},context) index.html {% if user.is_authenticated %} <h1>hello {{ user.username }}!</h1> {% else %} <h1>hello world!</h1> {% endif %} Help me, i am using Django version 1.10 with python 2.7 -
Django/Foundation - Accordion with table rows
I am pretty new on web development and want to make table where the user can click on a row in order to show more details (others rows). I do not know if it is important to notice it but, each row of my table are quiet heavy, they contain : Collapse Menu Switch I followed this documentation to do what I want but it does work. According to this help, it is written The container for an accordion needs the class .accordion, and the attribute data-accordion. Note that in these examples, we use a , but you can use any element you want. So here is my code : <table class="accordion" data-accordion data-accordion> <thead> <tr> <th>XXXX</th> <th class="sorttable_numeric">Score</th> </tr> </thead> <tbody> {% for X,couples in zipped %} <tr data-accordion-item data-multi-expand="true"> <td> <a href="http://www.XXX={{XXX}}">{{XXX}}</a> </td> <td> <body> <ul class="vertical menu" data-accordion-menu> <li> <a href="#">{{0.295}}</a> <ul class="menu vertical nested"> <li> <table> <tbody> <tr> {% for couple in couples %} <td>{{VINIO}}</td> <td>{{PINIO}}</td> <td>{{0.222}}</td> </tr> {% endfor %} </tbody> </thead> </table> </li> </li> </ul> </body> </body> </td> <td> <div class="switch tiny"> <input class="switch-input" id={{ZZZZ}}_{{forloop.counter}} type="radio" name="exampleSwitch"> <label class="switch-paddle" for={{ZZZZ}}_{{forloop.counter}}> <span class="show-for-sr">Tiny Sandwiches Enabled</span> </label> </div> </td> </tr> <div class="accordion-content" data-tab-content> Here should be … -
Django: duplicate south migrations
I had to resolve overlapping migrations because new migration files were generated in different branches, which eventually produced duplicate migrations 0077 and 0078 for the same change: a column was added. Also, two migrations starting with 0077 existed, so I renamed the newest one to 0078. I ran commands with the --remove-ghost-migrations and --fake options and thought it solved the issue. However, now I created a new model and tried generating a migration for it: py manage.py schemamigration myapp --auto The problem is that this not only generates a migration with the necessary code for that model, but it also generates again the code for the added column I was previously talking about. Then, when running the migrate I am obviously getting a column already exists error. How can I let the migration system know that the column already exists and it doesn't need to generate a migration for that? -
Admin static files not served in django on DigitalOcean droplet
I have a django page with 4 apps in DigitalOcean and the css and javascript is served perfectly, but when I go to the admin panel and I want to add a new item, the button image that supposed to say "Add" is not showing. I leave below the code part that I have at the end of my settings.py: STATIC_ROOT = '/home/django/django_project/django_project/static' STATIC_URL = '/static/' MEDIA_ROOT = '/home/django/django_project/django_project/media' MEDIA_URL = '/media/' -
Login programmatically with Django-AllAuth?
Is there a simple way to programmatically login with AllAuth? I don't really care about cookies or sessions, I just want to get a Client that corresponds to an AllAuth user account. Example: from django.test import Client from django.contrib.auth.models import User user = User.objects.first() # assuming user registered with AllAuth client.login(username=user.username) # password needed! AllAuth user accounts are not guaranteed to have passwords so the code above won't work. So how can I get the client to login without a password to make testing easier? -
Django queryset annotate field to be a list
I'm trying to use django annotation to create queryset field which is a list of values of some related model attribute. queryset = ... qs = queryset.annotate( list_field=SomeAggregateFunction( Case(When(related_model__field="abc"), then="related_model__id") ), list_elements=Count(F('list_field')) ) I was thinking about about concatenating all these id with some separator, but i don't know the appropriate functions. I know this syntax is wrong. Thank you for any help.