Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dynamically added task does not start running without restart the beat
I am trying to add/remove periodic task dynamically (while the django app is running). There is an item in PeriodicTask table in django database that I can enable/disable when a user goes to the specific page. The problem is that it works only if I restart the beat process. If I just update the database, and even refresh the counter in PeriodicTasks (using PeriodicTasks.changed(), it doesn't help. What do I do wrong? the full code is here: https://github.com/chapkovski/tango in views.py: from django_celery_beat.models import PeriodicTask, PeriodicTasks from django.http import HttpResponse from celery import app from datetime import timedelta from .tasks import * def index(request): ppp10 = PeriodicTask.objects.get(name='add every 10') ppp10.enabled = not ppp10.enabled ppp10.save() PeriodicTasks.changed(ppp10) return HttpResponse("You have changed the task!") two different processes for celery worker and celery beat: celery -A tango worker -l info -s django celery -A tango beat -l info -
take select request from django from
hello i have create a select django form with list of images for per user. How to take that select request in my views.py ? i have success only to create correct that select list but i need take that select request but i dont know how. models.py class MyModel(models.Model): user = models.ForeignKey(User, unique=True) upload = models.ImageField(upload_to='upload') views.py @login_required(login_url="login/") def carlist(request): Myform = MyModelForm(user=request.user) return render(request,'about.html',{'Myform':Myform}) select django form : class MyModelForm(ModelForm): def __init__(self, *args, **kwargs): # extract "user" from kwrags (passed upon form init) if 'user' in kwargs: self.user = kwargs.pop('user') super(MyModelForm, self).__init__(*args, **kwargs) # generate the choices as (display, value). # Display is the one that'll be shown to user, value is # the one that'll be sent upon submitting # (the "value" attribute of <option>) choices = MyModel.objects.filter(user=self.user).values_list('upload', 'id') self.fields['upload'].widget = Select(choices=choices) class Meta: model = MyModel fields = ('upload',) html : <form class="" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ Myform}} <input type="submit" name="" value="Submit"> for example Myform now have a list of user images that is correct but after from that i need the select images from the form. can do it that with my code or not ? -
Django template OBJECT from FOR loop into Javascript
Its a Django template which have FOR LOOP and contain 1 DIV in it. {% for player in players_details %} <div data-playerId="{{ player }}" class=" my_player_id > .... some functionality ..... </div> {% endfor %} 1. Multiple div will be generated wrt Objects in for loop 2. Now Model will open on above div click //THIS IS JAVASCRIPT FUNCTION $(".my_player_id").click(function(){ var myPlayer = $(this).data('playerId'); console.log(myPlayer); $("#myModal").modal(); }); 3. Now Problem is i am not getting objects in javascript Inside DIV <div data-playerId="{{ player }}" Inside JS var myPlayer = $(this).data('playerId'); 4. Note : Its Working fine for 1 Object data(object.data) This is working <div data-playerId="{{ player.name }}" Inside JS var myPlayer = $(this).data('playerId'); -
Passing location to Django view and sort by location
I'm running into a problem trying to pass the users' (HTML Geolocation) location to my Django view, which displays a list of elements by distance. I'm using GeoDjango for filtering the results, which works fine. I found some code that uses AJAX to pass the javascript var to the view, so this is where I'm at: Javascript function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { var latlon = position.coords.latitude + "," + position.coords.longitude; } function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } $.ajax({ headers: { 'Content-Type':'application/json', 'X-CSRFToken': getCookie('csrftoken') }, url: '/' + latlon, type: "GET", success:function(response){ //alert("success: " + response); }, error:function (xhr, textStatus, thrownError){ //alert("failure: " + xhr.statusText); } }).done(function (response) { //alert("end"); }); which I'm trying to pass into my view as "latlon": def fetch_places(request): loc= request.GET.get('latlon') finder_location = loc nearby= Places.objects.filter( location__distance_lte=( finder_location, D(km=500))).distance(finder_location).order_by('distance') context= … -
I'm trying to make a div background responsive in html using model image
HTML file I want to set model image as responsive background to main . adding CSS property like max-width is not working to div. how to overlap bootstraps div? <div class="game-cover"> <div class="container-fluid" id="about"> <div class="row" style="background: url({{ game.game_cover.url }})"> <div class="col-md-6 hidden-xs"> </div> <div class="col-md-6 col-xs-12"> <div class="game-header"> <h2 class="text-uppercase" style="color: whitesmoke"> {{ game.game_title }} </h2> <hr class="divider"> </div> <div class="game-details"> <p class="text-justify" style="color: whitesmoke">{{ game.game_intro }} </p> </div> </div> </div> </div> </div> what i want to do is this and make them overlap <div class="game-cover"> <div class="container-fluid" id="about"> <div class="row"> <div class="col-md-12"> <img class="img-responsive" src="{{ game.game_cover.url }}"> </div> <div class="col-md-6 hidden-xs"> </div> <div class="col-md-6 col-xs-12"> <div class="game-header"> <h2 class="text-uppercase" style="color: whitesmoke"> {{ game.game_title }} </h2> <hr class="divider"> </div> <div class="game-details"> <p class="text-justify" style="color: whitesmoke">{{ game.game_intro }} </p> </div> </div> </div> </div> </div> -
django-compressor can not install with django-shop
I cann't install django-compressor with django-shop. It's give an error like this. Failed building wheel for rcssmin ================================= Failed building wheel for rjsmin ------------------------------------------------------------------ Command "/home/raisul/Django/Django-Shop/virenv/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-_3410eu4/rcssmin/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-kau2lsqm-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/raisul/Django/Django-Shop/virenv/include/site/python3.5/rcssmin" failed with error code 1 in /tmp/pip-build-_3410eu4/rcssmin/ ------------------------------------------------------------------------ -
Running function on queryset in Django
I am trying to manipulate my data from a queryset using ListAPIView. I wrote the query in plain Python first (here), but have been unable to get it working in Django. I get a variety of errors, as I've tried using get_queryset too- but Im getting something wrong. With the code below, I get 'TagList' should either include aquerysetattribute, or override theget_queryset()method. as an error class TagList(generics.ListAPIView): serializer_class = AllSerializer def retrieve(self, d): if d.tag.exists(): ret = {} (level_one,) = [tagd for tagd in d.tag.all() if tagd.taglevel == 1] ret.update(level_one) ret.tag = [tagd for tagd in d.tag if tagd.taglevel != 1] newdata = [retrieve(d) for d in Task.objects.all()] else: print("no tag") return newdata() My data looks like this: { "title": "Yo", "tag": [ { "name": "Animals", "level": 1, }, { "name": "Cats", "level": 2, } ], }, { "title": "Hi", "tag": [ { "name": "Fruits", "level": 1, }, { "name": "Oranges", "level": 2, }, { "name": "Apples", "level": 3, } ], } -
how to automatically set foreign key in django create view
I want to assign the profile instance automatically to order, I tried as shown in views, but still form error shows profile required. Hope somebody can help, Thank you. models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) first_name = models.CharField(max_length=80,blank=True, null=True) middle = models.CharField(max_length=80, blank=True, null=True) last_name = models.CharField(max_length=80, blank=True, null=True) class Order(models.Model): profile = models.ForeignKey(Profile) qty_ordered = models.IntegerField(blank=True, null=True) views.py class OrderCreate(CreateView): model = Order form_class = OrderForm success_url = reverse_lazy('home') def form_valid(self, form): form.instance.order_id = self.kwargs.get('pk') return super(OrderCreate, self).form_valid(form) order_form.html <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %} {{ form.qty_ordered| as_crispy_field }} <input type='submit' class='btn btn-primary' value='Save & Continue' /> -
Django Single-Cart to Multiple-Carts Using Parameters
So I have this App that allows customers to add products from stores from product list page or product detail page. The problem is there is only one cart for all stores, I'd customers to have a different cart created everytime they add a product from a different store, using parameters such as: sotre_id. also more that one cart for same store depends on the order type such as: delivery, pickup .. Here is the code: models.py class Store(models.Model): name = models.CharField(max_length=500) state = models.CharField(max_length=500) class Product(models.Model): store = models.ForeignKey(Store, related_name='product') name = models.CharField(max_length=500) class Order(models.Model): PICKUP = 1 DELIVERY = 2 ORDER_CHOICES = ( (PICKUP, "Pick up"), (DELIVERY, "Delivery"), ) store = models.ForeignKey(Store, related_name='product') order_for = models.IntegerField(choices=ORDER_CHOICES) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items') product = models.ForeignKey(Product, related_name='order_items') price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) views.py from cart.cart import Cart def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save(commit=False) if cart.coupon: order.coupon = cart.coupon order.discount = cart.coupon.discount order.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # clear the cart cart.clear() # launch asynchronous task order_created.delay(order.id) # set the order in the session request.session['order_id'] = order.id # redirect to the payment return … -
Django Pagination Current page in View.py
I am using Pagination in Django but using AJAX so I have to send all variables values from view to AJAX call. But For Current page there is no builtin variable available ?. As I saw official documentation. So how to Send this data already calculated in view.py ? <span class="current"> Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}. </span> Link referenceFollowing this example -
Django - Cannot add middleware
I added a middleware django-user-agents to my application, used for getting user agent information and now my app won't start up. I followed all steps mentioned on their github page: django_user_agents but cannot get this thing working. Here's the stacktrace: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000000000520B048> Traceback (most recent call last): File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\core\management\commands\runserver.py", line 142, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super(Command, self).get_handler(*args, **options) File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\core\servers\basehttp.py", line 49, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\utils\module_loading.py", line 20, in import_string module = import_module(module_path) File "C:\Python34\lib\importlib\__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "C:\Users\catch\PycharmProjects\Backend_Noticeboard\noticeboard\noticeboard\wsgi.py", line 16, in <module> application = get_wsgi_application() File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\core\wsgi.py", line 14, in get_wsgi_application return WSGIHandler() File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\core\handlers\wsgi.py", line 153, in __init__ self.load_middleware() File "C:\Users\catch\AppData\Roaming\Python\Python34\site-packages\django\core\handlers\base.py", line 82, in load_middleware mw_instance = … -
nginx redirect www and non www
Hi im having trouble with my first Django site and not sure what im doing wrong. I basically want to redirect http:// www. example.com and http:// example.com and https:// www. example.com all to > https://example.com The redirect from http:// example.com seems to work. This is what my conf file looks like. server { #listen 80 default_server; #listen [::]:80 default_server ipv6only=on; listen 443 ssl; server_name example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/django_project/media; } # your Django project's static files - amend as required location /static { alias /home/django/django_project/django_project/static; } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } server { listen 80; server_name www.example.com; return 301 $scheme://$host$request_uri; } server { listen 80; server_name example.com; return 301 $scheme://$host$request_uri; } server { listen [::]:443 ssl; listen 443 ssl; server_name www.example.com; return 301 $scheme://$host$request_uri; } What am i doing wrong? -
Auto-incrementing Django DateField
How does one create a DateField, which automatically increments by 1 day in the way that the pk field does? For example, I would create a new object, this would be of 16/04/2017, the next object would be of 17/04/2017, even if they are both submitted on the same day. How would I do this? -
Send post that includes file to Django REST framework site
How to add file in this post that I have created? Using TamperData in firefox I tried to simulate upload. This is how the page looks like Page where is Uploaded Simulation looks like this: Results of Tamper Detailed post data is: POSTDATA =-----------------------------187452125318904 Content-Disposition: form-data; name="csrfmiddlewaretoken" BXVenM1edFGGc1WrGLEzZJslN9ZfgkQT5KV12VdavS8OMcHNdQ9OWCvlCDREYHD4 -----------------------------187452125318904 Content-Disposition: form-data; name="image"; filename="MyImage.jpeg" Content-Type: image/jpeg PNG And this is a code that I wrote by now: from httpie.core import * import re ses = requests.session() f = [('images', ('MyImage.jpeg', open('C:\Users\draga\PycharmProjects\CAPREAD\ImgLib\MyImage.jpeg', 'rb'), 'image/jpeg'))] url = 'http://127.0.0.1:8000/api-auth/login/' r = ses.get(url) csrftoken = r.cookies['csrftoken'] cookies2 = re.findall("<input type='hidden' name='csrfmiddlewaretoken' value='(.*?)' />",r.content)[0] form = {'username': 'some_username', 'password': 'some_pass','next':'http://127.0.0.1:8000/images/'} header = {'X-CSRFToken': csrftoken} cookies = {'csrftoken': csrftoken} resp = ses.post(url, data=form, headers=header, cookies=cookies) print resp.content -
how to pass parameters to a python script from django html template?
I am new to Python (Using Version 2.7) and I have built this Django app. I have a python script that requests services from google cloud vision api. The python script runs by taking few arguments from the command line. I have a django project and I want to pass the arguments to the python script from the html template of the project. The html page takes an image and uploads it, but when I am trying to send the uploaded image url to the python script its not working. The html snippet is as follows: api.html <body> <!-- List of uploaded documents --> {% if documents %} <form id="myForm"> {% csrf_token %} {% for document in documents %} <input type="checkbox" name="{{ document.docfile.url }}" value="{{ document.docfile.url }}"> {{ document.docfile.url }}<br> {% endfor %} <button type="submit">Submit</button> </form> {% else %} <p>No documents.</p> {% endif %} </body> <script> $('#myForm').on('submit', function(event) { event.preventDefault(); var inputs = []; $("form#myForm :input").each(function(){ var input = $(this); if(input.prop('checked')){ inputs.push(input.val()); } }); console.log(inputs); $.ajax({ type: 'POST', url: '{% url "api" %}', data: { csrfmiddlewaretoken: '{{ csrf_token }}', input: JSON.stringify(inputs) }, success: function(response){ console.log("YAY"); }, error: function(xhr, errmsg, err){ console.error('Submission error'); } }); }); </script> </html> and the api … -
Error during WebSocket handshake with user endpoint once app is deployed
I'm trying to set up a websocket connection at the user level in my django app for receiving notifications. prod is https so need to use wss. Here is the js: $( document ).ready(function() { socket = new WebSocket("wss://" + window.location.host + "/user_id/"); var $notifications = $('.notifications'); var $notificationList = $('.dropdown-menu.notification-list'); $notifications.click(function(){ $(this).removeClass('newNotification') }); socket.onmessage = function(e) { // notification stuff // Call onopen directly if socket is already open if (socket.readyState == WebSocket.OPEN) socket.onopen(); } locally, this handshakes just fine. 2017-04-16 16:37:04,108 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-04-16 16:37:04,109 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-04-16 16:37:04,109 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-04-16 16:37:04,110 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-04-16 16:37:04,111 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2017-04-16 16:37:04,112 - INFO - server - Using busy-loop synchronous mode on channel layer 2017-04-16 16:37:04,112 - INFO - server - Listening on endpoint tcp:port=8000:interface=127.0.0.1 [2017/04/16 16:37:22] HTTP GET / 200 [0.55, 127.0.0.1:60129] [2017/04/16 16:37:23] WebSocket HANDSHAKING /user_id/ [127.0.0.1:60136] [2017/04/16 16:37:23] WebSocket CONNECT /user_id/ [127.0.0.1:60136] … -
Django Cant Add Comment
I try to add a comment but it does not save it to the database without giving any error My Views is def add_comment(request, id): article = get_object_or_404(Article, id=id) if request.method == "POST": form = CommentForm(request.POST,instance=article) if form.is_valid(): comment = form.save(commit=False) comment.post = article comment.save() return redirect('articles:detail', pk=article.pk) else: form = CommentForm() template="article/comment.html" return render(request, template, {'form': form}) Commnt.html is <form method="POST">{% csrf_token %} {{form.as_p}} <button type="submit">Send</button> -
Django-form is not bounded when used __init__ to create fields
I used init method to create a ChoiceField in the form in order to call another function which populates the choices of the field. Now when the user selects the dropdown and submits the form, I cannot successfully create the form with the request, and I'm thinking "bound=False" is making the form invalid. Is there a way to use the init method to create form fields while making the form valid when passed in request.POST? Thanks in advance. Forms.py class CoursesForm(forms.Form): def __init__(self, subject, *args, **kwargs): super(CoursesForm, self).__init__(*args, **kwargs) self.fields['course'] = forms.ChoiceField(choices=get_uw_courses_from_subject(subject), required=False) View.py: the method that handles the submitted form def display_selection(request): if request.method == 'POST': course_form = CoursesForm(request.POST) # <CourseForm bound=False...> if course_form.is_valid(): # Not valid here selected_course = course_form.cleaned_data['course'] else: pass -
Automatic script to run django command
I am using django haystack and i want to make an automatic command that whenever the development server or the real server refreshes it automaticaly runs. . /manage.py update_index. This is to automate things so that i will not have to constantly run the command to index the pages whenever something is posted -
share button for own site Django
I want to implement a ''share on my profile'' button on my page but I have a hard time how to do so. When I try to find something like that (google/here) the results are "how to share something from your site on twitter/facebook". If there is a similar question please share the link I was not able to find something. So i have a site where users have a profile where the liked content is displayed and I would like to give the user the option to share a Post on his own profile with a personal comment(like FB/twitter does). My problem is that I don't know how to implement this into my models. If I want to save the "shared" post in a QuerySet in the UserProfile model I don't know where to save the comment for each shared post. If I make an extra table for all the shared posts with a extra form combined its a total mess since each post is saved individually and I don't know how to combine the existing image in to the form where the user writes his comment . Can anybody tell me in which direction I have to walk? … -
In misago forum getting error edit database.NAME
while installing misago forum in Django iam getting an error when I try command Python manage.py migrate It shows that database.NAME is not configured . What to do please help me to run misago forum in my system i am beginner in Django I am still learning Thank you Related links: https://github.com/rafalp/Misago https://misago-project.org -
Sharing Django user model between two apps in the same project
I see some similar questions, but they don't appear to be the same or have answers. I am practicing with Django and trying to make a simple dutch auction project. Initially I thought that the idea would be to create two distinct apps, a buyer app and a seller app, and just have them share databases (or three apps, a commonApp a buyerApp and a sellerApp). However, the more I dig into this the more complicated it seems - I feel like Django isn't really meant to have different apps that are designed around sharing all of their data from one set of tables (maybe I'm wrong?), loosely based on what I've found about having to modify the way Migrations work to accommodate this. So idea #2, just make one app that separates out the functionality by carefully managing the views, but keeping just one set of models since pretty much all of the data I can think of (the users, the products, etc.) are shared anyway. This seems like it has the advantage of letting Django do all of the data management without my having to sweat about the database design. However, I worry that maybe managing the views … -
How to restrict access users who are not an author to post on django generic editing views?
Building a website with referring a book, I made a blog application. And I found even nonauthors can edit/delete the post which they didn't write. So I've tried to fix it in many ways but failed so far. Here are my codes. models.py class Post(models.Model): title = models.CharField('TITLE', max_length=50) slug = models.SlugField('SLUG', unique=True, allow_unicode=True) description = models.CharField('DESCRIPTION', max_length=100, blank=True) content = models.TextField('CONTENT') create_date = models.DateTimeField('Create Date', auto_now_add=True) modify_date = models.DateTimeField('Modify Date', auto_now=True) tag = TagField() author = models.ForeignKey(User, null=True) class Meta: ordering = ('-modify_date',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=(self.slug,)) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title, allow_unicode=True) super(Post, self).save(*args, **kwargs) views.py class PostUpdateView(LoginRequiredMixin, edit.UpdateView): model = Post fields = ['title', 'slug', 'description', 'content', 'tag'] success_url = reverse_lazy('blog:index') def form_valid(self, form): form.instance.author = self.request.user return super(PostUpdateView, self).form_valid(form) class PostDeleteView(LoginRequiredMixin, edit.DeleteView): model = Post success_url = reverse_lazy('blog:index') def form_valid(self, form): form.instance.author = self.request.user return super(PostDeleteView, self).form_valid(form) Below is the only code which worked and I found it in docs(Using FormMixin with DetailView) def post(self, request, *args, **kwargs): if not ((request.user==Post.author) or request.user.is_superuser): return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) It worked, in some points, cuz it returns … -
How do I distribute a Django reusable app that depends on another app?
I have a Django app I wish to distribute - call it my_app. The user would, of course, need to add my_app to his INSTALLED_APPS array to install it. However, my_app makes use of somebody_elses_app. In order to make it work, I have to add the latter to INSTALLED_APPS, too. Is there any way to make the user not have to do it - to make Django understand that if my application is called, then somebody_elses_app is, too? -
Get ImageField path after post django
I'm trying to get path where the image is save after user has clicked button post and print it in cmd (where runserver has started). I think that I have to grab it in here in models.py but I tried so many ways in past 24 hours that I really don't know what has left... Every question on this subject on this website didn't work. from django.db import models import uuid,os def scramble_uploaded_filename(instance, filename): extension = filename.split(".")[-1] return "{}.{}".format(uuid.uuid4(), extension) # Our main model: Uploaded Image class UploadedImage(models.Model): image = models.ImageField("Uploaded image",upload_to=scramble_uploaded_filename) # stores the filename of an uploaded image on local host that is this part -> upload image So if it is not there it could be here in serializer.py from rest_framework import serializers from webservis.quickstart.models import UploadedImage class UploadedImageSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UploadedImage fields = ('id', 'image',) # only serialize the primary key and the image field Not sure does this in main settings can have that info. STATIC_URL = '/static/' # at the bottom of settings.py MEDIA_ROOT = os.path.join(BASE_DIR, '../ws', 'uploaded_media') MEDIA_URL = '/media/'