Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use more than two models in the same form using modelForms?
I am creating a new application using Django, my application is in need of a form to add data on the db. I am using 4 models which are all connected by foreign keys. How can I use modelForm's to enter data to the form and add them directly to db, if it's not possible what should be my approach? I checked the existing solutions which are for 2 models only, I couldn't find a way to tweak it to my own problem. I tried using inlineformset but as I said couldn't figure out how can I implement it with all my models together. I also looked through the Django documentation couple times but couldn't find anything this sort (maybe I am missing). My models are like this: class Question(models.Model): year = models.CharField(max_length=5) source = models.CharField(max_length=140) problemNumber = models.CharField(max_length=16) weblink = models.CharField(max_length=200) date_posted = models.DateTimeField(default=timezone.now) problemStatement = models.TextField() author = models.ForeignKey(User, on_delete=models.PROTECT) class QLevel(models.Model): qID = models.ForeignKey(Question, on_delete=models.CASCADE) level = models.CharField(max_length=16) class QMethod(models.Model): qID = models.ForeignKey(Question, on_delete=models.CASCADE) method = models.CharField(max_length=40) class QSubject(models.Model): qID = models.ForeignKey(Question, on_delete=models.CASCADE) subject = models.CharField(max_length=35) As can be seen 3 of the models are connected to Question model with a foreign key, whilist Question model is … -
What is the best way to organize images on a file system?
I have a site where I'd like to store multiple images (profile images, profile cover images, status images, etc.) What is the best way to store images on a file system? For example, would something like: Images avatars -ex1.jpg -ex2.jpg -ex3.jpg covers -ex1.jpg -ex2.jpg -ex3.jpg This is how Twitter lays out its images, will this make the file system sluggish? Or is better to do something like this: Images avatars user1 -ex1.jpg -ex2.jpg -ex3.jpg covers user1 -ex1.jpg -ex2.jpg -ex3.jpg What is the best way to organize images in a file system? -
I Want to start this animation on button click but form is valid?
I want to start this animation because I am creating an audio file which is taking time to prevent the user from further click I want to start this animation. Not getting any solution for it <form action="/textanalysis/upload_link/summarization/from_link" method="POST" id="form_id"> <h4 id="link2">Enter the Url::</h4> {{form.url}}<br> <h4 id="link2">Enter the No of Lines::</h4> {{form.no_of_lines}}<br><br> {%csrf_token%} <button type="submit" name="" class='btn btn-lg btn-primary' name="btnform2" value="content" onclick="ShowLoading();">Get Summary</button> </form> </div> <script type="text/javascript"> function ShowLoading(e) { var div = document.createElement('div'); var img = document.createElement('img'); img.src = "{% static 'css/images/final1.gif' %}"; div.innerHTML = "Loading... Be Patient We are Creating An Audio File For Your Summary<br />"; div.style.cssText = 'position: fixed; left:25%; top: 46%;z- index: 5000; width: 50%; text-align: center; background: #EDDBB0; border: 1px solid #B22222'; div.appendChild(img); document.body.appendChild(div); return true; } #django view if request.method=='POST': form=Take_User_Url_Form(request.POST) if form.is_valid(): #print(form.cleaned_data['no_of_lines']) link=form.cleaned_data['url'] no_of_lines=form.cleaned_data['no_of_lines'] -
Exception Type: AttributeError at /notifier/not/ Exception Value: 'AsgiRequest' object has no attribute 'loop'
when i tried to run a piece if code in my django application i have been faced with some strange error def main(request): async def hello(request): ws = web.WebSocketResponse() await ws.prepare(request) msg="this is awesome" ws.send_str(msg) # return HttpResponse("ok") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop = asyncio.get_event_loop() loop.run_until_complete(hello(request)) loop.close() when i run this code i just get Exception Value: 'AsgiRequest' object has no attribute 'loop' here is the complete traceback of the issue Environment: Request Method: GET Request URL: http://127.0.0.1:8000/notifier/not/ Django Version: 2.0.7 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest', 'accounts', 'connect', 'drones', 'notifier', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'channels', 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', 'drfpasswordless', 'taggit', 'taggit_serializer', 'elasticsearch'] Installed Middleware: ['corsheaders.middleware.CorsPostCsrfMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\madhumani\workspace\ven\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\madhumani\workspace\ven\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\madhumani\workspace\ven\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\madhumani\workspace\ven\drfc\notifier\views.py" in main 32. loop.run_until_complete(hello(request)) File "c:\users\madhumani\appdata\local\programs\python\python36-32\Lib\asyncio\base_events.py" in run_until_complete 467. return future.result() File "C:\Users\madhumani\workspace\ven\drfc\notifier\views.py" in hello 23. await ws.prepare(request) File "C:\Users\madhumani\workspace\ven\lib\site-packages\aiohttp\web_ws.py" in prepare 106. protocol, writer = self._pre_start(request) File "C:\Users\madhumani\workspace\ven\lib\site-packages\aiohttp\web_ws.py" in _pre_start 183. self._loop = request.loop Exception Type: AttributeError at /notifier/not/ Exception Value: 'AsgiRequest' object has no attribute 'loop' -
Can I use a URL other than "accounts" for django-allauth? I already have an app named "accounts" in my django project?
Can I change the following code: urlpatterns = [ ... url(r'^accounts/', include('allauth.urls')), ... ] to : urlpatterns = [ ... url(r'^something_else/', include('allauth.urls')), ... ] since I already have an app "accounts" in my django projects? Is the name "accounts" deeply integrated with django-allauth source code? -
Django: delete cookie from request
I know how to delete a cookie from response: response = HttpResponseRedirect(self.get_success_url()) response.delete_cookie("item_id") return response But how to delete a cookie from request? I've a view that only has a request but not a response: I'd like to delete the cart_id cookie when user arrives at my 'thanks.html' page. def thanks(request): order_number = Order.objects.latest('id').id return render(request, 'thanks.html', dict(order_number=order_number)) -
KeyError: <type="str> while making migration in Django
I created a model and Tried to migrate it, it is throwing error. from __future__ import unicode_literals from django.utils import timezone from django.db import models # Create your models here. class Post(models.Model): title = models.CharField(max_length = 200) body = models.TextField() created_at = models.DateTimeField(default=timezone.now, blank = True) This is the error I am getting after creating the Model. I am using mysql instead of sqlite3. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemigrations.py", line 110, in handle loader.check_consistent_history(connection) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 283, in check_consistent_history applied = recorder.applied_migrations() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 254, in cursor return self._cursor() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 229, in _cursor self.ensure_connection() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py", line 276, in get_new_connection conn.encoders[SafeBytes] = conn.encoders[bytes] KeyError: <type 'str'> -
How can I filter products to show only those belonging to selected category in Django Admin?
I am trying to filter the options shown in a foreignkey field within Django Admin inline. Using formfield_for_foreignkey I'm able to show products with category_id = 4 but instead of the 4 I would like to filter based in the category field in the inline. Using kwargs["queryset"] = Product.objects.filter(category=F('order_line__category')) does not get the category field value. class Order_lineInline(admin.StackedInline): model = Order_line def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "product": kwargs["queryset"] = Product.objects.filter(category=4) return super().formfield_for_foreignkey(db_field, request, **kwargs) class Category(models.Model): name = models.CharField(max_length=255) class Product(models.Model): part_number = models.CharField(max_length=255) category = models.ForeignKey('Category') price = models.DecimalField(max_digits=10, decimal_places=2) class Order(models.Model): customer = models.CharField(max_length=255) class Order_line(models.Model): order = models.ForeignKey('Order', on_delete=models.CASCADE) category = models.ForeignKey('Category', on_delete=models.CASCADE) product = models.ForeignKey('Product', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) -
login with facebook is not working django graphql
I am using the package django-graphql-social-auth for social login like login to facebook, google, twitter, etc. I copied the code from the example project, however, I could not login to facebook. I have created an app in facebook developer page as well. I get the following issue { "errors": [ { "message": "400 Client Error: Bad Request for url: https://graph.facebook.com/v2.9/me?access_token=f9************50&appsecret_proof=c*********ef0450ea076e42bfd9c85c6d07", "locations": [ { "line": 2, "column": 3 } ], "path": [ "socialAuth" ] } ], "data": { "socialAuth": null } } What i did is, i copied app id to SOCIAL_AUTH_FACEBOOK_KEY app secret to SOCIAL_AUTH_FACEBOOK_SECRET then in the mutation i provided the provider name as "facebook" and accessToken an app secret but it did not work and i tried accessToken with the Client Token from facebook developer page but that also raised same error. I have a doubt in accessToken part. what that accessToken should have from facebook developer page? -
How can I override "settings_overrides" variable in leaflet_map from within inside Django template
Summary I have a geodjango project to display web maps. Which I can do with no problem. However, I want to customize my map configuration from within my django template instead of from my django settings. (From django settings I can do it alright). To customize, I have to pass a python dictionary to a variable called settings_overrides. The problem is I can not figure it out how and if this is possible from within a django template. Description Let's say I want to override "SPATIAL_EXTENT" inside my template code where python dictionary that leaflet_map expects is like this: ext = {'SPATIAL_EXTENT': (-154.609, 1.561, -40.611, 65.921)} settings_overrides = ext Note: This is what I understood!! I might be wrong! See below for the signature of the leaflet_map function. This is calling function inside the template(index.html) where I want to pass the new extent to the setting_overrides: {% leaflet_map "main" callback="window.map_init_basic" creatediv=False, settings_overrides=ext %} (A) And the signature of the leaflet_map function which is located in: leaflet/templatetags/leaflet_tags.py is as follow: def leaflet_map(name, callback=None, fitextent=True, creatediv=True, loadevent=app_settings.get('LOADEVENT'), settings_overrides={}): if settings_overrides == '': settings_overrides = {} instance_app_settings = app_settings.copy() instance_app_settings.update(**settings_overrides) .... (B) As you can see from (B) in the signature, I have … -
loop.run_until_complete(main(request)) NameError: name 'request' is not defined
i tried of integrating django with asyncio and aiohttp here is how my function looks like async def main(request): ws = web.WebSocketResponse() await ws.prepare(request) msg="this is awesome" ws.send_str(msg) return HttpResponse("ok") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop = asyncio.get_event_loop() loop.run_until_complete(main(request)) loop.close() i want to send that message as websocket using aiohttp websockets but when ever i tried to run this peice of code and access the domain path i got this error in termianl loop.run_until_complete(main(request)) NameError: name 'request' is not defined but this is working perfectly fine when i tried to use web scraping in an asynchronous function using aiohttp&asyncio def djangoview(request): async def main(request): async with aiohttp.ClientSession() as client: async with client.get('http://localhost:3000/employees') as post: if post is not None: post=await post.json() page=post[0]['url'] token=post[0]['Authorization'] headers={'content-type':'application/json', 'Authorization':token} req=requests.get(page) soup = BeautifulSoup(req.content, 'html.parser') title=soup.find_all('h1')[0].get_text() body=soup.find_all('p')[0].get_text() print(title) await client.post('http://127.0.0.1:8000/api/list/',json={ "title":title,"content": body,"tags": []},headers=headers) else: print('none enctype') loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop = asyncio.get_event_loop() loop.run_until_complete(main(request)) loop.close() return HttpResponse("ok") i don't know what the issue could be and please let me know if you have better suggestions on using websockets in aiohttp with django -
Linking profile model to user
I created a separate profile form from what users enter when they sign up and I am trying to attach information inputted in this form to its relevant user. I have tried creating a foreign key in my profile model that refrences the user model however, I could not get that to work. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) bio = models.CharField(max_length=2000) instrument = models.CharField(max_length=255, choices=instrument_list, blank=True) level = models.CharField(max_length=255, choices=level_list, blank=True) preferred_language = models.CharField(max_length=255, choices=language_list, blank=True) time_zone = models.CharField(max_length=255, choices=time_list, blank=True) def create_profile(self, bio, instrument, email, level, preferred_language, time_zone): profile_obj = self.model(bio=bio, instrument=instrument, level=level, preferred_language=preferred_language, time_zone=time_zone) # add arguments full_name=full_name profile_obj.save(using=self._db) return profile_obj views.py def profile_page_edit(request): if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): bio = request.POST.get('bio', '') instrument = request.POST.get('instrument', '') level = request.POST.get('level', '') preferred_language = request.POST.get('preferred_language', '') time_zone = request.POST.get('time_zone', '') #profile = request.user #form.save() profile_obj = Profile(bio = bio, instrument = instrument, level = level, preferred_language = preferred_language, time_zone = time_zone) profile_obj.save() return redirect('/student/profile-page') else: form = ProfileForm() form = ProfileForm() context = {'form': form } return render(request, 'student/profile_page_edit.html', context) def profile_page(request): form = ProfileForm profiles = request.user.profile.objects.all() args = {'form' : form, 'profiles' : profiles} return render(request, 'student/profile_page.html', args) I am trying … -
Zappa Django project "DisallowedHost at /" even though ALLOWED_HOSTS are correct
I am deploying my django app on AWS Lambda and RDS using zappa serverlessly I am using a Postgres database as my RDS instance. When I run my commands I am not getting any errors Your updated Zappa deployment is live!: https://56ks43234234fhkshdfk48.execute-api.us-east-1.amazonaws.com/production However when I click that link I get DisallowedHost at / Invalid HTTP_HOST header: '56ks43234234fhkshdfk48.execute-api.us-east-1.amazonaws.com'. You may need to add '56ks43234234fhkshdfk48.execute-api.us-east-1.amazonaws.com' to ALLOWED_HOSTS. Now I have added ALLOWED_HOSTS in my settings.py file ALLOWED_HOSTS = ["56ks43234234fhkshdfk48.execute-api.us-east-1.amazonaws.com/", ] Below are the steps I did $ pip install zappa $ zappa init $ zappa deploy production Below is my zappa_settings.json { "production": { "aws_region": "us-east-1", "django_settings": "Cool.settings", "profile_name": "default", "project_name": "cool", "runtime": "python3.6", "s3_bucket": "cool-723m6do75", "project_directory": "/tmp/code", "slim_handler": true, "vpc config": { "SubnetIds": [ "subnet-37werwer16b", "subnet-375werrwr19", "subnet-2cwerwr3c23", "subnet-5awerwrr93d", "subnet-1dwerwrre57", "subnet-fwerwerf9c7" ], "SecurityGroupIds": [ "sg-a9c865d7" ] } }, "production_ap_northeast_1": { "aws_region": "ap-northeast-1", "extends": "production" }, "production_ap_northeast_2": { "aws_region": "ap-northeast-2", "extends": "production" }, ... #All available zones " } Somehow this is not making any sense and I am not sure how to proceed. Can someone guide me in the correct direction. If there is any additional detail anyone needs. Please feel free to ask -
Is it possible to use/test a value of Django's BooleanField without a model?
I'm trying to make a workflow where the user enters data on one page, then has to check the data and tick a tickbox to accept the T&C's. So the code has to check that the checkbox is checked before going on, but doesn't care until the second step. It's not a bound field and I think that's the problem - I don't need a model just to handle a workflow, and I don't want to have to store, in a database, a simple ephemeral field in a form! I'm running Django 2.1.5. I've tried every possible combination of: test_form.fields['tickbox'].value - doesn't exist, which is ridiculous test_form.fields['tickbox'] == False - value doesn't change at all request.POST['tickbox'] seems to go missing? views.py from django.http import HttpResponse from django.template import loader from django.forms import Form, CharField, BooleanField class test_form(Form): name = CharField() tickbox = BooleanField(required=False, initial=False) def testview(request): if request.method == 'POST': testform = test_form(request.POST) if testform.fields['tickbox'] == True: do_things() else: dont_do_things() else: testform = test_form() template = loader.get_template('testform.html') context = { 'testform : userform, } return HttpResponse(template.render(context, request)) I should be able to test the value of the field and get a changing response depending on if the user has ticked … -
Insert custom field in Django response using middleware
I am looking for the right directions to add a custom field in the HTTP response using middleware and access the custom field in the JavaScript front-end. I am trying to implement this, but on receiving the response on the JavaScript side there is no field like "is_logged" in the body. class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: response = self.get_response(request) response.body['is_logged'] = True else: response = self.get_response(request) response.body['is_logged'] = False return response -
Filter based on foreign key
So i was working on this problem for many days already and can't make it work. Basically I have three models class Year(models.Model): year = models.CharField() class Book(models.Model): name = models.CharField( verbose_name = "Library Name", max_length = 255 ) author = models.ForeignKey( Author, on_delete=models.CASCADE ) year = models.ForeignKey( Year, on_delete=models.CASCADE ) class Author(models.Model): name = models.CharField( verbose_name = "Author's Name", max_length = 255 ) num = models.CharField( max_length = 255, default=0 ) For example, If I pass 2018 i want retrieve all the Authors who published book in 2018. I tried different queries like Year.objects.filter(year=2018).filter() and don't know how to filter the rest -
Refresh data in django template without reloading page
Hi I'm trying to get new data added to DB without refresh the page. I'm using this library chartjs-plugin-streaming to live streaming data. I've tried with a ajax callback to my URL in wich my view is called My view gets to my template my model. view.py def live(request): queryset = Registro.objects.all() if request.GET.get('ensayo__exact') is not None: queryset = queryset.filter(ensayo__exact=request.GET.get('ensayo__exact')) if request.GET.get('presion') is not None: queryset = queryset.filter(presion=request.GET.get('presion')) if request.GET.get('etapa') is not None: queryset = queryset.filter(etapa=request.GET.get('etapa')) if request.GET.get('fecha__gte') is not None: queryset = queryset.filter(fecha__gte=request.GET.get('fecha__gte')) if request.GET.get('fecha__lte') is not None: queryset = queryset.filter(fecha__lte=request.GET.get('fecha__lte')) presion = [str(obj.presion) for obj in queryset] etapa = [str(obj.etapa) for obj in queryset] tempin = [str(obj.tempin) for obj in queryset] fecha = [str(obj.fecha) for obj in queryset] fecha__gte = [str(obj.fecha) for obj in queryset] fecha__lte = [str(obj.fecha) for obj in queryset] id = [int(obj.id) for obj in queryset] ensayo_id = [int(obj.ensayo_id) for obj in queryset] context = { 'presion': json.dumps(presion), 'etapa': json.dumps(etapa), 'tempin': json.dumps(tempin), 'fecha': json.dumps(fecha), 'fecha__get': json.dumps(fecha), 'fecha__lte': json.dumps(fecha), 'id': json.dumps(id), 'ensayo_id': json.dumps(ensayo_id) } return render(request, 'reporte/live_data.html', context) and this are the js functions I've tried in my tempalte and the canvas that render the li: template.html function update() { $.get('', '', function() { return presion … -
How do i Fix api data not displaying with vue and axios
I can't seem to load the data information on the html table from the api via using vue and axios I am adding vue as my frontend to my rest api and i have called the api correctly using axios the problem i am having is there is no data shown but the loop displays the number of lines cos i have 3 entries and the table shows 3 empty spaces but no meaningful data and there's no console error please what ami i doing wrong ? <div class="body"> <table class="table table-bordered table-striped table-hover dataTable "> <thead> <tr> <th>Article Id </th> <th>Title</th> <th>Body</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tfoot> <tr> <th>Article Id </th> <th>Title</th> <th>Body</th> <th>Edit</th> <th>Delete</th> </tr> </tfoot> <tbody> <tr v-for="article in articles" :key="article.article_id"> <td>{{ article.article_id }}</td> <td>{{ article.article_title }}</td> <td>{{ article.article_body }}</td> <td><button @click="geArticle(article.article_id)" class="btn btn-round btn-primary">Edit</button></td> <td><button @click="deleteArticle(article.article_id)" class="btn btn-round btn-danger">Delete</button></td> <td></td> </tr> <script> new Vue({ el: "#startapp", data: { articles: [], // loading: false, currentArticle: {}, message: null, currentArticle: {}, newArticle: {'article_title': null, 'article_body': null} }, mounted(){ this.getArticles(); }, methods: { getArticles: function() { axios({ method: 'get', url: '/api/article' }).then((response) => this.articles = response.data) } } }); </script> The data from the api is supposed to show … -
Rest Framework serializer to create parent and one of multiple child types
I have a serializer that creates a parent model, then creates a child model depending upon some information provided to the parent: class InitializeFormSerializer(serializers.Serializer): title = serializers.CharField() category = serializers.ChoiceField(choices=CATEGORY_TYPES) def create(self, validated_data, user): identifier = validated_data.get('title') obj, created = Parent.objects.update_or_create( user=user, ) if created: item_type = validated_data.get('item_type') if item_type == 'FIRST_TYPE': Child1.objects.create(identifier=obj) elif item_type == 'SECOND_TYPE': Child2.objects.create(identifier=obj) return obj This works, but the item_type check feels clumsy. Is there a paradigm within Django or Rest Framework I'm missing that might make this more elegant? -
Is there a way to pass an object + parameter using Django's list view?
I have a one question ~! Using Django's list view I want to pass the search keyword and the query set object post_list at the same time. I would like to pass the q in the function below, but I do not know how. If you know how, thank you if you let me know ex1 # pagination X search o class PostListView(ListView): model = Post template_name = 'blog/post_list.html' paginate_by = 2 q = '' def get_context_data(self, *args, **kwargs): context = super(PostListView, self).get_context_data(*args, **kwargs) q= self.request.GET.get('q','') if q: print('q : ', q) context['post_list'] = Post.objects.filter(title__icontains=q) else: context['post_list'] = Post.objects.all() return context ex2 # pagination X search o class PostListView(ListView): model = Post template_name = 'blog/post_list.html' paginate_by = 2 q = '' def get_context_data(self, *args, **kwargs): context = super(PostListView, self).get_context_data(*args, **kwargs) q= self.request.GET.get('q','') if q: print('q : ', q) context['post_list'] = Post.objects.filter(title__icontains=q) else: context['post_list'] = Post.objects.all() return context -
Celery not making task
I'm new in async and celery, this is my first time. And i have a problem with a task. My task is just taking object with field, and make minus one from IntegerField. This method is worked when i used from python manage.py shell. But when i want to do this in celery task it's not worked. Also i dont know what happening its just say me a nothing.. Can someone told me how i can get why i have no output when i call celery worker -A project_name settings.py REDIS_HOST = 'localhost' REDIS_PORT = '6379' BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} CELERY_RESULT_BACKEND = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') app = Celery('project_name') app.config_from_object('django.conf:settings') app.autodiscover_tasks() tasks.py from project_name.celery import app from .models import Post @app.task def check_post(): posts = Post.objects.filter(premium=True) if salons.count() > 0: for post in posts: salon.minus_premium_day() return True else: return False Output - i make this all on remote server.. ---- **** ----- --- * *** * -- Linux-4.9.132-0-beget-acl-x86_64-with-debian-wheezy-sid 2019-01-27 01:41:51 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: project_name:0x7f4e595081d0 … -
How to generate thumbnails in MEDIA_DIR from images stored in STATIC_DIR with Django?
I have a number of images stored in my static dir, set as per my django settings. These images are all different sizes and aspect ratios. They display fine in my django application at the moment. I want to generate thumbnails from these images using "smart crop" functionality (which looks for the parts of the image with the most entropy when reducing instead of just centering). I've tried this both with sorl-thumbnail and the easy_thumbnail packages that have the "smart crop" functionality I am after. In both cases, I get an error: SuspiciousFileOperation at /products The joined path (/static/images/products/test1.jpg) is located outside of the base path component (/home/jake/webapps/my_webapp/my_site/media) I understand that media and static dirs are meant to be distinct from each other, with media being for where users upload files and static being files that are part of the site. But, since thumbnail packages need to read images from my static dir and generate them in my media dir, how can I resolve this security conflict? Surely this should be a common configuration for people generating thumbnails, basin them on images in their static dir? Yet I can't find anything on this error coming up in this context before, … -
multiple field search in dajngo app wrong results
I would like to create a multiple field search for the my database in django app. my search work correct only if the user use all fields from html form. if the user don't use some field or if some field is empty or blank then my query return all results (like apps=movies.objects.all() ) and that is wrong because the user in not required to use all fields but anytime to use fields where need for search. any idea how to fix that ? here my code: models.py : class category(models.Model): title = models.CharField(max_length=100, blank=True, null=True) class movies(models.Model): code = models.CharField(max_length=100, blank=True, null=True) code_2 = models.CharField(max_length=100, blank=True, null=True) name = models.CharField(max_length=100, blank=True, null=True) year = models.CharField(max_length=100, blank=True, null=True) movies_title=models.ForeignKey('category', blank=True, null=True) link=models.CharField(max_length=100, blank=True, null=True) html form : <form method="POST" action="{%url 'search' %}">{% csrf_token %} <select name="link"> <option value=""></option> <option value="0">link 1</option> <option value="1">link 2</option> <option value="2">link 3</option> </select> <select name="category"> <option value=""></option> {% for data in cat%} <option value="{{ data.id }}">{{ data.title }}</option> {% endfor %} </select> <select name="year"> <option value=""></option> {% for data in apps%} <option value="{{ data.id }}">{{ data.year }}</option> {% endfor %} </select> code: <input type="text" name="code"><br> code_2: <input type="text" name="code_2"><br> name: <input type="text" name="lname"><br> <input type="submit" … -
Images database schema
I'm trying to store user profile pictures, uploaded images in statuses, etc. on my site. When the user uploads a profile picture, there should be 3 types of the same image (Original image, medium sized, small sized). This is stored in the filesystem. A user can upload a maximum of 2 pictures in their statuses and each of these images follow the same types (original, medium, and small). The reason why I'm making different thumbnails of the same image is to serve those images depending on which screen display the user is accessing the site. That being said, what is the best way to store these image's file paths in my database? What kind of schema makes the best sense, or if there is another better way I can serve these images, what is the best approach? For the profile image table, I was thinking something like this: id user_id size img 1 2 S /img/s/avatars/ex.jpg 2 2 M /img/m/avatars/ex.jpg 3 2 L /img/l/avatars/ex.jpg Does this look like a good approach? -
Trouble with redirecting to an absolute_uri
I'm attempting to redirect to a full url currenturl = request.GET.get('currenturl') #lets say this resolves to google.com return redirect(currenturl) This sends me to an 404 error page as it's trying to resolve the following url http://localhost:8000/accounts/profile/calendar/delete/15/'google.com'