Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is not displaying the image via /media/
Im stuck quite a while now I just can't display a picture a user has unloaded before. I have the option on my site to upload files and this part is working fine. I can see on the Admin Page via Posts that the image is there (name, title and tags)but when I try to view the image in admin or display it on the site I get an error. The Pictures are successfully added to my Media_cdn Folder in my project. When I try to open it via admin page it says: Request Method: GET Request URL: http://127.0.0.1:8000/media/scan.png Raised by: django.views.static.serve "/media/scan.png" does not exist Also when I try to just open /Media/ it says page does not exist. when I want to open the Image on my website it gives me the symbols of a not found picture. but I can see the rest of the given information (Name,title,tags). I hope somebody can tell me what part im missing. Main settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media_cdn') Main Urls.py enter code here if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_URL) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_URL) urls.py for the view page urlpatterns = [ url(r'^my_profile/upload',views.upload, name='upload'), url(r'^my_profile/mypost',views.mypost, name='mypost'), url(r'^$',ListView.as_view(queryset=Post.objects.all().order_by('-id')[:25],template_name='my_profile/my_profile.html')), url(r'^(?P<pk>\d+)$', DetailView.as_view(model … -
Grouping QuerySet in Django
Having scheme like this: class Model1(models.Model): pass class Model2(models.Model): model1 = models.ForeignKey(Model1) date = models.DateField() class Model3(models.Model): model2 = models.ForeignKey(Model2) I need to query Model3 having unique model2__model1__id and the least model2__date. I've managed to make required query using QuerySet.extra() method, like this: Model3.objects.select_related('model2').order_by('model2__date').extra(select={'m1_id': 'DISTINCT `app_model2`.`model1_id`'}) But I'm afraid it won't work with additional sortings etc. I also don't want to use raw queries as those don't support sorting as well, and also database-level slicing (there could be huge amounts of records). Is there more correct way to do what I'm trying to achieve? -
geo search by defined ares in python or django
I am doing location based searching Back end is in Django and mysql. Scenario Product table with lang and lat. Alert table with specified area defined by users. (In the maps user can define some circle or square ares) So when user post a product from the lng and lat. (0.1, 0.3) System search from alerts tables. - any defined areas in alerts table includes the lng, lat (0.1, 0.3) search those and send notification. How can I achieve this search? and very fast for the million records.? Any third party libraries or servers i can do this searching fast in python ? Thanks. -
Django: Class Instance in context_processor
I need to input in a base template a reference to a model class. I could do it in returning a list of models instances from context_processor but it would be more elegant to add a reference to a class. Here is my template code: {% for langue in Langue.objects.all %} <li><a href="{% url "ListeUEsParLangue" langue.code %}">{{ langue.label }}</a></li> {% endfor %} Here, my context_processor code : def add_langue_object(request): from ..baobab.models import Langue return {'Langue': Langue} My error infos : AttributeError at /2016/ue/1896/ Manager isn't accessible via Langue instances Request Method: GET Request URL: http://enseignements-2017.local:8000/2016/ue/1896/ Django Version: 1.9.2 Exception Type: AttributeError Exception Value: Manager isn't accessible via Langue instances Exception Location: /Users/xxxxxxxxxxxxx/.virtualenvs/enseignements-2017/lib/python2.7/site-packages/django/db/models/manager.py in __get__, line 250 I guess that in creating Context Django calls on returned class instances. Any idea? Thx a lot, -
Django save Array of JSON object to database
I am sending AJAX POST request to Django and in the request body data is sent as array of objects. Request Payload:(Javascript) [{"x":1423182600000},{"x":1423237500000},{"x":1423259100000},{"x":1423281600000},{"x":1423295100000}] On Django side I am reading JSON data like this, def put_flag_data(request): res=json.loads(request.body) for value in res: print value and the printed value on Django side is as shown below {u'x': 1423182600000L} {u'x': 1423237500000L} {u'x': 1423259100000L} {u'x': 1423281600000L} {u'x': 1423295100000L} Problem here is the printed value include special char in {u'x'. How do I remove this. Is there a better way to read and save this list in database? -
Paragraph element prepending not appending to table in django html
I'm using the Django Web Framework and I have a html table displaying some fields from one of my tables. If there are no fields to display (records in a queryset), I pass variable = "0" from python. I want to append text to the table in this case so it appears underneath my table. But it's appearing above my table.... <div class="1" style="overflow-x:auto;"> <table id="1" class="1"> <tr> <th>Heading 1</th> <th>Heading 2</th> </tr> {% ifequal variable "0" %} <p>No items to show</p> {% else %} <--append some fields--> {% endifnotequal %} </table> </div> If I'm appending the fields this works fine they appear as expected, but in the other case it prepends above the table instead... Why? Help! -
Crontab don't send email
I have file with crontab code to send email: #!/bin/bash file=$1 current=`date +%s`; last_modified=`stat -c "%Y" $file`; if [ $(($current-$last_modified)) -gt 86400 ]; then echo "The file is older than 24 hours" | mailx -r noreply@email -s "The json file is not up to date..." email@to.me else echo "file is ok"; fi; I call this file here: */2 * * * * /path to the file with crontab code/send_email.sh /path to the file to check file.zip But I don't receive email. When I try test mailx with: echo "something" | mailx -s "subject" mail@to.me - everything is ok. zip and sh files have the same permissions: -rwxrwxrwx 1 userone userone 451 Mar 17 11:02 send_email.sh -
Update form showing <django.db.models.query_utils.DeferredAttribute object at 0x0424AA70> instead of value [on hold]
I am new to python and trying to build a Django CRUD webapp. The add and delete forms are working fine but in edit form in the fields instead of actual value of the field, it is displaying like . I am using python 3.6 and Django 1.10.6 -
Django ORM Arithmetic operation with columns from different subqueries
I have a table: test_id url value 1 'url1' 3 1 'url2' 3 1 'url3' 7 2 'url1' 5 2 'url2' 4 2 'url3' 2 In django I have a function with 2 incoming variables for different test_id`s: def tests_compare_aggregate(request, test_id_1, test_id_2): I need to execute SQL-query, which will show the difference between urls values for these 2 test_id`s, like: SELECT t1.url, t1.value - t2.value FROM (SELECT url, value FROM table WHERE test_id = test_id_1) t1, (SELECT url, value FROM table WHERE test_id = test_id_2) t2 WHERE t1.url = t2.url So I have two QuerySet`s: t1 = Table.objects.filter(test_id=test_id_1).values('test_id,'url','value') t2 = Table.objects.filter(test_id=test_id_2).values('test_id,'url','value') What to do with them next or is there any another way? I tryed a lot of things, but nothing worked. -
How to safely render html in a div in Django templates
My view is returning a Model object, that object has a field with value as HTML code. def my_view(request): ob = MyModel.objects.get(pk=1) print ob.html # "<div> Description <span> number </span>" return render(request,'page.html',{'ob':ob}) Some of my html values have not properly closed tags like <div> Description <span> number </span> If I render that value in template like {{ ob.html | safe }}, It's breaking parent elements structure and my page got unaligned as I designed. How can I safely put that HTML code without breaking parents structure. -
Deploying a Django application to an offline server
I'm developing a Django application on a CentOS 7 dev machine that has internet access. Once I have finished it I want to deploy it to a second machine that does not have internet access, also CentOS 7. If I develop my Django application within a virtual environment, will I be able to just copy the directory over to the offline server? What difficulties may I encounter? I may be able to resolve some dependencies on the offline server via a local yum repo although that's likely to be hit and miss. Is there anything I can do at the start of this project that will make the deployment easier later on? -
Django app connect with external API
I have this web app where I upload files and do some stuff with them. There's been a request to connect this app with another site and upload files (upon request) form the app to the site. This site provides an API and with it python code to interact with that. Since I am one year old in programming years I don't quite get the API concept. All I know so far is that it's something in the middle that handles requests. Anyway, The code provided(from the site) has a class and several methods to that class like so: class ApiClient(object): def method1(self,param1): Since I haven't,so far, worked with external APIs before I don't know how to handle it and have some questions. 1.Regardless the class ApiClinet(object) I get that they provide python code so the class is an object, but how do I handle it? Do I make it a models.Model? 2.Adittionaly to my first question,do I store the information for this in the database? So do I need fields? thanks in advnace! -
Django - reload div upon form submit
I am trying to refresh a certain div in a django application when a form is submitted. index.html <div class="col-md-8" id="notesColumn"> {% crispy note_form %} {% include 'item/item_notes.html' %} </div> item_notes.html <div class="panel-group panel-group-simple m-b-0" id="notesList" aria-multiselectable="true" role="tablist"> {% for note in object.itemnote_set.all reversed %} <div class="panel"> <div class="panel-heading" id="noteHeading{{ forloop.counter }}" role="tab"> <a class="panel-title collapsed" data-parent="#notesList" data-toggle="collapse" href="#noteCollapse{{ forloop.counter }}" aria-controls="noteCollapse{{ forloop.counter }}" aria-expanded="false"> <span class="tag tag-default">{{ note.owner.first_name }}</span> {{ note.get_action_display|upper }} <small class="panel-actions">{{ note.date_added }}</small> </a> </div> <div class="panel-collapse collapse" id="noteCollapse{{ forloop.counter }}" aria-labelledby="noteHeading{{ forloop.counter }}" role="tabpanel" aria-expanded="false" style="height: 0px;"> <div class="panel-body"> {{ note.content }} </div> </div> </div> {% endfor %} </div> app.js (included in index.html) $(document).ready(function () { $("#notesTab form").submit(function(event){ event.preventDefault(); $('#notesList').remove(); $.ajax({ url: "{% url item_notes %}", success: function(data){ $('#notesColumn').html('data'); } }) }) views.py def item_notes(request): return render_to_response(request, 'candidate/candidate_notes.html') urls.py url(r'item/profile/(?P<pk>[0-9]+)/$', views.ItemProfile.as_view(), name='item_profile'), url(r'item/notes', views.item_notes, name='item_notes'), The error I get from chrome is: http://127.0.0.1:8000/crm/item/profile/45/%7B%%20url%20item_notes%20%%7D Failed to load resource: the server responded with a status of 404 (Not Found) -
What's the best way to represent IMEI in Django models
I would like to store IMEI for a SimCard model in my app, I found here that IMEI can be a number of 14, 15 or 16 digits length. I would like to know what is the best way to do that in models: BigIntegerField with min_value and max_value (problem for IMEIs starting with several 0) DecimalField with max_digits but this requires decimal_places argument ! CharField with max_length + a regex validators Thank you. -
jQuery script not importing in django template
I want to import my js files into my django template. But it is not importing while css import is working fine. If I try to import using direct http links of these files, then they are working fine but if I download these files into my myApp/static/js folder, they are not working. Here's my template: {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'css/FormStyle.css' %}"> **<script type = "text/javascript" src="{% static "js\validateForm.js" %}" ></script>** **<script type = "text/javascript" src="{% static 'js/jquery.validate.min.js' %)"></script>** <script src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/additional-methods.js"></script> <div class = "formArea"> <div class = "fileForm"> <form id = 'formFile' enctype="multipart/form-data" method="post"> {% csrf_token %} <div class = "formFields"> <label for = "file"> {{ form.file.label }} </label> {{ form.file }} {{ form.file.errors }} </div> <div class = "formFields"> <input type="submit" value="Submit"> </div> </form> </div> </div> <script> $(document).ready(function() { $('#formFile').validate({ rules: { 'file': { required: true, extension: "txt|jpe?g|png|gif" } }, messages: { 'file': { required: 'Please Upload a File!', extension: 'Only Image & txt Files are allowed!' }} }); }); </script> -
Form post to Django view renders no input to database
So, Im trying to save a todo to a database with django. My template is as follows: <form action="{% url 'todo:add' %}" method="POST"> {% csrf_token %} <input type="text" id="text" value="{{new_todo_text}}"/> <input type="submit" value="Submit todo" /> </form> {%if not_done_todos %} <ul> {%for todo in not_done_todos%} <li> <span>{{todo.text}}</span> </li> {%endfor%} </ul> {%else%} <span>No todos for you!</span> {%endif%} My view where Im trying to catch the "new_todo_text" looks like this: def add(request): """Add todo to database""" new_todo = Todo(text=request.POST.get('new_todo_text'), done=False, date_created=timezone.now()) new_todo.save() return HttpResponseRedirect(reverse('todo:index')) The problem is that the todo.text turns up empty no matter what I add to the form... whats my problem here? -
template condition of FK value
I have two models, Item and Quality. Item has a field named quality which is a FK to Quality.name. The two tables look something like this: Item ----- itemId int PK name varchar quality varchar FK - Quality.name Quality ----- qualityId int PK name varchar I'm trying to make a template that lists all Items that have a certain quality. This is my code in question: {% for Item in items %} {% if Item.quality == "Common" %} <div id="name_{{ Item.id }}" class="itemName">{{ Item.name }}</div> {% endif %} {% endfor %} I know that my table contains at least one tuple with quality="Common", but I'm not getting any output. If I try to condition any other field then it works fine (ex: if Item.name == "exampleName"). How do I use an if-statement on a value from a FK? -
Execute manage.py runserver using Upstart in Ubuntu 16.04
I have a small project using Raspberry Pi 3 device and using Django for my application. I follow this tutorial but sadly it can't be used for 16.04. I'm not using apache because of my device, i want to use runserver because of the limitations of my unit. Thanks -
show ReferForm for already requested for invitation user
I want to implement a feature for growth hacking where a user gets to signup only after admin accepts his/her invitation. The general flow of this feature is At first the user is shown a request invitation form where he has to fill his/her email address. If he request for invitation his/her email address is saved to db. If he now open the page, instead of request invitation form he/she should see ReferForm. How can I do it? class Invitation(models.Model): email = models.EmailField(unique=True, verbose_name=_('e-mail Address')) invited_by_email_address = \ models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE) custom_invite_code = models.UUIDField(default=uuid.uuid4, unique=True) points = models.PositiveIntegerField(default=0) invite_accepted = \ models.BooleanField(verbose_name=_('invite accepted'), default=False) request_approved = models.BooleanField(default=True, verbose_name=_('request accepted')) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return 'Invite: {0}'.format(self.email) class InviteForm(forms.Form, CleanEmailMixin): email = forms.EmailField(label=_('E-mail'), required=True) def save(self, email): print ('email', email) return Invitation.objects.create(email=email) class ReferForm(forms.Form, CleanEmailMixin): email = forms.EmailField(label=_('Receiver E-mail'), required=True) invited_by_email_address = forms.EmailField(label=_('sender E-mail' ), required=True) def save(self, email, invited_by_email_address): return Invitation.objects.create(email=email, invited_by_email_address=invited_by_email_address) class RequestInvitation(LoginRequiredMixin, FormView): template_name = 'home.html' form_class = InviteForm def get_custom_invite_code(self): custom_invite_code = str(uuid.uuid4()) try: id_exists = \ Invitation.objects.get(custom_invite_code=custom_invite_code) get_custom_invite_code() except: return custom_invite_code def form_valid(self, form): email = form.cleaned_data.get('email') invite_instance = form.save(email) invite_instance.invited_by_email_address = self.request.user invite_instance.custom_invite_code = \ self.get_custom_invite_code() print ('invite_instance.custom_invite_code', invite_instance.custom_invite_code) invite_instance.save() … -
Connecting Two Django Apps, but Keeping them Separated
I have two distinct Django Apps, each one completely working separated. Those Apps are "PointOfSale" and "Inventory". What occurs is that both of these Apps have a "Product" table, in which the products are inserted. Now, keeping those two tables filled with basic the same data is obvious redundant (actually, the Inventory table of Products have more fields). I'm now contemplating the different merge strategies to deal with this issue and I would like some help. Ideally, I would like to keep the possibility of each App working independently. So, I envisioned the following scenarios: A Save Signal that keep the two tables insync The connection of the two with OneToOne connection Generic Relationship The creation of a third App, called Products, in which the tables Products and CategoryOfProducts are kept, and both the Apps PointOfSale and Inventory uses it as a prerequisite. MErge everything in one big App. Another that I couldn't think of. Thanks -
Django app on AWS Elastic Beanstalk - DJANGO_SETTINGS_MODULE
Where should the DJANGO_SETTINGS_MODULE environment variable be set? Multiple possible locations: In a config file (.ebextensions) as follows: option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "app.settings" In the wsgi.py file before application is loaded In manage.py (I also see this on different Django projects on the web) If I don't specify it in wsgi.py, it looks like it can't be found at all. Therefore, I wonder if the environment variables set in .ebextensions are set before wsgi.py is loaded. Any idea? -
Django Oscar multi Vendor Register
I am working on a project for eCommerce. where there are suppose to be multiple vendors selling there project. i have managed to do everything using Oscar's own templates and all except i am nor able to add vendors , i.e, a user can also sell items, there is no dashboard for him. i want to that users who register on website can also sell products. I Have gone thru this link but not able to under stand that what do i have to do exactly. need help Thanks in Advance -
Django ORM does not refresh foreign key from saved object
After updating a foreign key in a object, the related object does not refresh. model.py: class Name(models.Model): name = models.CharField(max_length=30, unique=True) status = models.ForeignKey( 'NameStatus' ) class NameStatus(models.Model): status = models.CharField(max_length=30, unique=True) testing it: >>> status = Name.objects.exclude(name="Foo").get() >>> print ( status.status.id ) 2 >>> status.status_id = status.status.id + 1 >>> print ( "%d vs %d" % (status.status.id, status.status_id ) 2 vs 3 What am I missing? Should .get() be called again in a queryset up refresh the object? I understand that this is probably to reduce unneeded calls to the database, but how to avoid this? -
Doing certain actions upon user creation in Django
I'm using social-auth-app-django to do social authentication with Facebook and Google. I'm trying to create a receiver once a user has been created to perform certain commands such as showing a tutorial (only once) after user creation. Below is what I'm trying to do but haven't been able to get it to work. from social_core.pipeline.user import create_user @receiver(create_user) def after_user_created(request, user, **kwargs): userprofile = UserProfile.objects.create(user=user) userprofile.full_name = user.first_name + " " + user.last_name userprofile.save() request.session['first_login'] = True return render_to_response("main/highlights/highlights.html",locals(),RequestContext(request)) Essentially, how can I create some sort of receiver to activate once I create a unique user so that I can perform custom actions once that user has been created? My current code doesn't seem to be working. -
How to catch a HttpRequest sent from an android app in django
I am trying to catch a requests from an android app which contains data that will be used. But i don't know how to catch that. Like generally when deployed in local host we use url patterns to link a url to one of the views.What i mean is that, to which url the requests should be sent so that i can make a view to process it.And my views are generally listening to urls on local server,how to make them listen to url that the android app will sent a request to. This is my first time trying to do something like this,so any help will be appreciated. Thank you