Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django switch flag on button
I have a tasklist app with a standard view and another view that filters the tasklist to show completed tasks. I have a hide button, but I don't want to make 'hidden' a property of the database coz that seems like overkill. A simple 'hidden' flag in a if statement would be enough. {% if hidden==False %} <a class="btn btn-primary" href="{% url 'hide' %}" data-toggle="tooltip" data-placement="top" title="Hide Completed Tasks"><i class="fas fa-eye-slash"></i></a> {% else %} <a class="btn btn-primary" href="{% url 'home' %}" data-toggle="tooltip" data-placement="top" title="Hide Completed Tasks"><i class="fas fa-eye"></i></a> {% endif %} But I don't know where to put the ternary logic that switches hidden between true and false? I would rather not resort to js coz I think it's untidy -
How to disable ajax redirect in django
I am trying to pass value from the database into the url but the ajax redirect function runs and the redirect in the view.py doesn't redirect is there a way to disable the ajax redirect success function and redirect from the views directly or how to sent the id to the success function to redirect to the right route views.py if request.method == 'POST': if not request.POST['sub_category'] == '': project = Project(project_name = request.POST['usecase_name'], user_id = request.user.id) project.save() project_value = Project.objects.filter(project_name = request.POST['usecase_name']) for item in project_value: projectId = item.project_id return render(request, 'usecases/create-usecase.html', data) else: categories = Category.objects.all() return render(request, 'usecases/create-usecase.html', {'data': categories}) else: return render(request, 'usecases/create-usecase.html') template <script type="text/javascript"> $('#nextBtn').click(function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: '/create-usecase/', data: { usecase_name: $('#usecase_name').val(), category: $('#category-list').val(), sub_category: flag, csrfmiddlewaretoken: '{{ csrf_token }}' }, success:function(response) { //console.log(window.location.href) //window.location = '{{ item.project }}'; $('#subcategory-list').replaceWith($("#subcategory-list",response)); //console.log("/create-usecase/%s/%s/%s/", $('#usecase_name').val(), $('#category-list').val(), flag); } }) }); </script> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('register/', views.register, name='register'), path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), path('dashboard/', views.dashboard, name='dashboard'), path('profile/', views.profile, name='profile'), path('create-usecase/quest/<slug:project_id>', views.quest, name='quest'), #path('create-usecase/quest/<slug:project_id>/', views.quest, name='quest'), path('create-usecase/', views.create_usecase, name='create_usecase'), ] -
Django REST Framework: sending an image from android
I'm trying to send an image through my Android application to Django, where it will make the analysis of that image (with python code). I'm sending the image in Base64, but when I receive it, the format gets all messed up. How can I send the image correctly, and is this the right format? -
Access object attributes in Django template
I would like to achieve something that in python looks like this: person = People.name('Thomas') In my views.py I'm passing every People object that matches the query and list with few names. Then, I want to access specific object and it's fields, i.e. sex, age, city of this particular person. So far I've tried defining custom filter like this: @register.filter(name='people_attributes') def object_attributes(val): return Person.objects.get(name=val) My goal is to be able to loop over list with values and then, during every iteration, access coresponding object. Let's say, my list looks like ['John', 'Adam', 'Alice', 'Katherine'], I want to access object which name attribute is equal to John, Adam, Alice or Katherine. -
Using custom subclasses in Django Registration
I have made subclasses for the two views in Django Registration (RegistrationView and ActivationView), but I am unsure how to plug these new views into Django Registration and get it to use my custom classes instead. I am adding some context data to the templates. class SeductiveBlogRegistrationView(RegistrationView): form_class = SeductiveBlogRegistrationForm def get_email_context(self, user): context = super().get_email_context(user) context['site_name'] = get_current_site(self.request).name return context class SeductiveBlogActivationView(ActivationView): def get_context_data(self, **kwargs): context = super().get_context_data() context['site_name'] = get_current_site(self.request).name return context -
My tasks are shown as unregistered on prod
So I do have my config with Celery tasks which works fine for dev machine. But then I switched to prod machines, and I cannot see task as registered in Celery. My debug_task is shown as registered correctly. Tree: mysite β βββ mysite β βββ __init__.py β βββ settings.py β βββ celery.py β βββ stats β βββ tasks.py β βββ __init__.py β βββ manage.py My mysite/init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app import pymysql pymysql.install_as_MySQLdb() __all__ = ['celery_app'] celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') app = Celery('stats') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py from mysite.celery import app @app.task def collectOnline(): transaction.set_autocommit(False) updateOnline(logoutChars()) updateOnline(getOnline()) transaction.commit() transaction.set_autocommit(True) Do you have any idea how I could solve it? -
create() method override in django rest
models.py class Product(models.Model): product_name = models.CharField(max_length=32) quantity = models.IntegerField() remarks = models.TextField(blank=True) class Customer(models.Model): customer_name = models.CharField(max_length=50) address = models.CharField(max_length=100) bill_no = models.CharField(max_length=8) product = models.ManyToManyField(Product) class Sell(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) total = models.IntegerField() vat = models.IntegerField() And after serializers and views I get that when i browse to input sell. How do I automatically connect Customer object to Sell so that I dont need to select the customers objects? Using token or any idea? Also how to override create() method on customer serializer to add products details from customer view? -
Using Slack RTM API with Django 2.0
I am a beginner to the Django framework and I am building a Django app that uses the Slack RTM API. I have a coded a program in python that performs the OAuth authentication process like so : def initialize(): url="https://slack.com/api/rtm.connect" payload={"token":"xxx"} r=requests.post(url,payload) res=json.loads(r.text) url1=res['url'] ws = create_connection(url1) return ws My Requirement: The stream of events I receive (from my slack channel that my slack app is added to) is processed to filter out events of the type - message ,then match the message with a regex pattern and then store the matched string in a database. As a stand alone python program I am receiving the stream of events from my channel. My questions: How do I successfully integrate this code to Django so that I can fulfill my requirement? Do I put the code in templates/views? What is the recommended method to process this stream of data? -
Qualified input but checked invalid by `form.is_valid`
I input qualified content to form but was checked as invalid by form.is_valid, Here is my views: I add print(request.POST) # test input to check posted successfully, and print("form is invalid.") #assert invalid to check if it's a valid form, class CommentCreateView(View): template_name = "article/article_detail.html" def get(self, request, pk): return redirect(f"/article/detail/{ pk }") def post(self, request, pk): self.article = Article.objects.get(id=pk) form = CommentForm(request.POST) print(request.POST) # test input if form.is_valid(): print("form is valid.") #assert valid comment = form.save(commit=False) print(f"Comment: {form.cleaned_data}") comment.owner = request.user comment.article = self.article comment.status = 0 comment.save() return redirect(f"/article/detail/{ pk }") else: print("form is invalid.") #assert invalid comments = (Comment.objects .filter(article=self.article, status=0) ) context = {'article': self.article, 'comments':comments, "form": form} return render(request, self.template_name, context) The Comment model data`: class Comment(models.Model): STATUS = ( (0, 'normal'), (-1, 'deleted'), ) owner = models.ForeignKey(User, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE) comment = models.TextField() # set the widget status = models.IntegerField(choices=STATUS) date_created = models.DateTimeField(default=datetime.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.comment And the forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['comment', 'date_created'] widgets = {'comment': forms.Textarea(attrs={'cols': 80})} The error report: Django version 1.11.13, using settings 'forum.settings' Starting development server at http: // 127.0.0.1: 8001/ Quit the server with CONTROL-C. <QueryDict: β¦ -
pylint E1101 ,Class 'Product' has no 'objects' member
class ProductListView(ListView): queryset = Product.objects.all() template_name = "products/list.html" def product_list_view(request): queryset = Product.objects.all() context = { 'object_list':queryset } return render(request, "products/list.html",context) -
Django and AWS s3 cached media files
When a media image is submitted to my site the image initially loads correctly, than on refresh it removes the media/ from the path which creates a broken link. ( see below) the images are loading correctly under the media folder on AWS, and I seem to have the correct Django settings. Anyone knows what could be causing the issue? Initial image load: https://.s3.amazonaws.com/media/cache/42/f8/42f8cebf023fcd3a63d236d75101817e.jpg Image load after refresh: https://.s3.amazonaws.com/cache/42/f8/42f8cebf023fcd3a63d236d75101817e.jpg as you can see the path changes to exclude the media/ from the path. just as background: I use Django-storages , I have 'storages' on my installed apps. I use Boto3 and have the following setting in my utils.py file: from storages.backends.s3boto3 import S3Boto3Storage StaticRootS3BotoStorage = lambda: S3Boto3Storage(location='static') MediaRootS3BotoStorage = lambda: S3Boto3Storage(location='media') This is my conf.py file configuration S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = S3_URL + 'media/' MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' The static files work like a charm, the issue is only with the media files after a refresh. just as additional background, the way media files are cached is that user submit a link to mysite, I crawl the website of the link and save the og:image link url on the site in my model β¦ -
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activ
I made a python virtual environment using virtualenv, then installed django. If I input 'django-admin --version' command, it outputs 1.11.13 when using virtualenv. However, when I input ' python3.6 manage.py createsuperuser', it output below: Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Thanks in advance to any suggestions! -
Select 20% random records from 1 million record Django mysql
I want to select some x % from a mysql Django model. for example if there is 1 million device id stored into the table I want to select 20% of 1 million device id. Can any one help me with this with optimised way to do it -
Django: how can you put two forms on the same template/page?
I have two forms in my view.py. I am trying to put everything in one function. I have done research but nothing I find actually works. It'd be great if somebody could send me into the right direction. def Search_Date(request): if request.method == 'POST': form = DateForm1(request.POST) date = datetime.date.today() if form.is_valid(): timeslots = form.cleaned_data['timeslots'] b = tg_list.objects.filter( tour_date=date, timeslots = timeslots, tg = request.user ).all() return render(request, 'myapp/list2.html', {'b': b}) else: form = DateForm1() return render(request, 'myapp/search.html',{'form': form, 'date':date}) def SearchTG(request): if request.method == 'POST': form1 = DateForm2(request.POST) if form1.is_valid(): date1 = form1.cleaned_data['date1'] timeslots1 = form1.cleaned_data['timeslots1'] w = tg_list.objects.filter( tour_date=date1, timeslots=timeslots1 ) return render(request, 'myapp/list3.html', {'w':w}) else: form1 = DateForm2() return render(request, 'myapp/search1.html', {'form1': form1}) -
Unable to serve static files correctly in Django app
I have installed in googlecloud VM (Ubuntu 16.04) a django application (1.8.19) with a static IP but when I access the page I am not able to load correctly all the static files (css, jquery etc.). Although I have set the correct files paths in my apache conf file, the URLs fail to include the "static" part. So instead of being like this: http://myip/**static**/lib/css/assets.min.css They are like this: http://myip/lib/css/assets.min.css Thus everything fails to get rendered correctly and I get the following errors in the webdeveloper: I believe the issue must be somewhere in the settings.py file but I am not sure where as I clearly define the path to the static folder there as: MEDIA_ROOT = '/var/www/geonode/uploaded' STATIC_ROOT = '/var/www/geonode/static/' TEMPLATE_DIRS = ( '/etc/geonode/templates', os.path.join(GEONODE_ROOT, 'templates'), ) # Additional directories which hold static files STATICFILES_DIRS = [ '/etc/geonode/media', os.path.join(GEONODE_ROOT, 'static'), ] -
How to convert the UTM to Lat/Long in Python?
{"type": "MultiPolygon", "coordinates": [[[[6707794.77817316, 1952512.97762237], [6707794.43138905, 1952566.21209599], [6707897.49942442, 1952567.26754007], [6707897.9039513, 1952513.5347079], [6707794.77817316, 1952512.97762237]]]]} these are my UTM coordinates for Sacramento city from pyproj import Proj Lat = 52.063098675 Lon = -114.132980348 ZoneNo = "11" #Manually input or from other sources myProj = Proj("+proj=utm +zone="+\ ZoneNo+", +north +ellps=WGS84 +datum=WGS84 +units=m +no_defs") Lon2, Lat2 = myProj(UTMx, UTMy,inverse=True) [57.645243963689346, -97.82662155895939][57.64521883657446, -97.82633467103226][57.64520287229081, -97.82615238782866] [57.64518564728056, -97.82595574421379][57.646086991794625, -97.82587777819731][57.64614690939316, -97.8265560026529] [57.645243963689346, -97.82662155895939] But this return coordinates located at Canada. But I want to Locate this longitudinal and latitudinal's in SACRAMENTO city Can anyone help me to convert the correct format to convert the UTM to LAN LONG coordinates. -
On_delete error
Can someone please help me with this? I'm trying to add on_delete cascade to this code but it doesn't seem to work. class Request(AbstractEntity): requester = ForeignKey(User, related_name='requests') module_ref = CharField(max_length=100) status = CharField("us", max_length=30, choices=REQUEST_STATUS) class Task(AbstractEntity): request = ForeignKey(Request, related_name='tasks') assignee = ForeignKey(Group) updated_by = ForeignKey(User) activity_ref = CharField(max_length=100) status = CharField(verbose_name="Status", max_length=30, choices=TASK_STATUS) -
Template displayed the submitted data every other post
I came across a very strange problem, the post method worked every other submit: I formulate the form with: test1, test2, test3, test4, test5, test6 sequently and submitted but got test2, test4, test6 displayed, the template of article_detail.html <div> {% for comment in comments %} <p>{{ comment.comment|linebreaks }}</p> {% endfor %} </div> <div> <h4>Comments</h4> <form action="/article/comment/create/{{ article.id }}" method='post'> {% csrf_token %} <textarea class="form-control" rows="5" value={{ form.comment.value }} name='comment'></textarea> <br> <button type="submit" class="btn btn-primary">Post Your Comment</button> </form> </div> <div><!--/class="col-xs-8 col-md-8">--> </div><!-- row --> The models.py: class Comment(models.Model): STATUS = ( (0, 'normal'), (-1, 'deleted'), ) owner = models.ForeignKey(User, on_delete=models.CASCADE) article = models.ForeignKey(Article, on_delete=models.CASCADE) comment = models.CharField(max_length=5000) # set the widget status = models.IntegerField(choices=STATUS) date_created = models.DateTimeField(default=datetime.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.comment The forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['comment'] the views.py class CommentCreateView(View): template_name = "article/article_detail.html" def get(self, request, pk): return redirect(f"/article/detail/{ pk }") def post(self, request, pk): self.article = Article.objects.get(id=pk) form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) print(f"Comment: {form.cleaned_data}") comment.owner = request.user comment.article = self.article comment.status = 0 comment.save() return redirect(f"/article/detail/{ pk }") else: comments = (Comment.objects .filter(article=self.article, status=0) ) context = {'article': self.article, 'comments':comments, "form": form} return render(request, self.template_name, context) What's β¦ -
How to get Django Queryset to filter one model entries depending on another model fields
I'm trying to filter the entries from one Model (Product) depending on what the user has bought (EntryProduct). I've been looking to other posts but none of them could solve my problem. I'm using Django 2.0. First of all I'm going to explain how this store works: One product is formed by a certain group of content. What the user have to buy is the content of this products, not the product itself (as most of the stores), so for that, the process of buying that I did is: In EntryProduct, I added a boolean for each content that the products have, so everytime the user buys content from a product, there is a function that creates a new entry putting the related boolean to true. So I have 1 entry for each content buyed by user and product. All the buying system is already done, but the problem for me now is when I have to create the view of the products buyed (show all buyed content for each product with at least one content buyed). What I had in mind is: First get the 'Entries' filtering by the logged user. Then group by product (so I could have β¦ -
Delete model-mommy instance
I'm using model-mommy to generate test data like so class AuthorDetailViewTests(TestCase): def setUp(self): # set bio manually to avoid error being thrown by template tag markdown_format self.author = mommy.make('author.Author', bio='Some bio text') def tearDown(self): self.author.delete() setUp() method works fine. Problem is that the tearDown() method doesn't actually delete the created aauthor instance. Is there any way to achieve this? Thanks -
Serving multiple Django projects in different virtualenv at the same IP (Apache)
I'm trying to serve two Django projects on different virtualenv at the same IP adress on Apache. My first site is at http://myip/site-1 and the seccond: http://myip/site-2 When I run http://myip/site-1, Apache serves it without issues, but when I run the second (http://myip/site-2) it raises the following: The requested URL /site-2/ was not found on this server. Because it searches in the first site's document root. Here is my apache.conf <VirtualHost *:80> ServerName site-1.example.com DocumentRoot /home/venv/site-1 # adjust the following line to match your Python path WSGIDaemonProcess site-1.example.com processes=2 threads=15 display-name=%{GROUP} python-home=/home/venv/lib/python2.7 WSGIProcessGroup site-1.example.com WSGIScriptAlias / /home/venv/site-1/site-1/wsgi.py <directory /home/venv/site-1> AllowOverride all Require all granted Options FollowSymlinks </directory> Alias /static/ /home/venv/site-1/static_root/ <Directory /home/venv/site-1/static_root> AllowOverride all Require all granted Options FollowSymlinks </Directory> </VirtualHost> <VirtualHost *:80> ServerName site-2.example.com DocumentRoot /home/venv_mob/site-2 # adjust the following line to match your Python path WSGIDaemonProcess site-2.example.com processes=2 threads=15 display-name=%{GROUP} python-home=/home/venv_mob/lib/python2.7 WSGIProcessGroup site-2.example.com WSGIScriptAlias / /home/venv_mob/site-2/site-2/wsgi.py <directory /home/venv_mob/site-2> AllowOverride all Require all granted Options FollowSymlinks </directory> Alias /static/ /home/venv_mob/site-2/static_root/ <Directory /home/venv_mob/site-2/static_root> AllowOverride all Require all granted Options FollowSymlinks </Directory> </VirtualHost> I have tried many solutions that I found on the web but the problem remains the same. Any ideas ? -
Parameters in Django Page Redirection
I have the following code in views: def submit_affective(request): if request.method == 'POST': choice=request.POST['aff_choices'] urlid=request.POST['url_list'] url = Url.objects.get(id=urlid) aff_result=Affective.objects.create( affective=choice, url=url ) return redirect('detail_affective',id=url.id) def detail_affective(request,id): boring_count=Affective.objects.filter(affective='Boring',url.id=id).count() confusing_count=Affective.objects.filter(affective='Confusing',url.id=id).count() engaging_count=Affective.objects.filter(affective='Engaging',url.id=id).count() context = { 'boring_count':boring_count, 'confusing_count':confusing_count, 'engaging_count':engaging_count, } return render(request,'feedback/detail_affective.html',context) I want to show the number of "boring","confusing","engaging" in detail_affective only for that URL for which choice has been submitted in submit_affective. Please tell me the problem in my code. Am I passing the url id to detail_affective correctly? And is my way of filtering correct? -
Monolithic Django project to Microservices project, best practices?
So this question is not about the exact steps, but just to know if there's a best-practice approach that I can package the apps inside my Django project each in an isolated microservice. I had an idea of packaging all the projects in a single repo but to have on manage.py file and multiple wsgis to run a microservice like this python manage.py api runserver, but I don't know if that's considered a good approach or not. -
How to transfer data/clone tables from one RDBMS to another using a python script?
I want to transfer data from all tables in a Microsoft SQL Server to a local MySQL database using a python script. This should be an Automated Task. There are over 100 tables in this database, so what is the best way to do this without having to explicitly define the table related info. -
How to setup mod_wsgi on a centos 6 server
I have recently completed the development of a django 2 app and part of the requirements is to deploy it to an apache 2 server on a centos machine. The django app is written with python3 and the centos machine has python2 pre-installed. So far, I have been having a hard time installing mod_wsgi on the apache2 server and deploying the app. Any help would be appreciated.