Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm trying to install this library but can't find the original library?
I ran my project and received the following error: File "/home/nguyentv/schoollink/web/views/apis.py", line 10, in <module> from util.redis.redis_client import Redis ImportError: No module named util.redis.redis_client How to install this library ??? -
inserting and retrivel of file using monogo with django?
I want to save a user selected file to MongoDB and also download that file.I'm trying with Gridfs but it not working,below is my code in view.py file. file = open(file_name.name, 'rb') db = file_detailes() db.File.put(file,file_name=file_name.name, content_type = 'file/doc') -
Django: Debug page doesn't show up with DEBUG=True
I tried to debug my project but dubug page doesn't show up even with DEBUG=True. Instead 404 page shows up like when I turn off the debug. A weird thing I noticed is debug page actually works for other project. The project I'm working on is the one I cloned from GitHub. I restart the server but it still doesn't change anything. What is the cause possibly? -
Cant pass data to template html page [Django]
I have a python django project where I am simply trying to pass data to a template but, for some reason cannot seem to get it working. My views.py file is located in myproject/mystuff/views.py and looks like this: from django.shortcuts import render def index(request): return HttpResponse("TESTING") def myview(request): tempData = {'firstname': 'bob','lastname': 'jones'} weather = "sunny" data = { 'person': tempData, 'weather': weather } return render(request,'myproject/templates/myview.html',data) inside the myview.html page I simply have add <h1>Hi {{ person.firstname }} {{ person.lastname }}</h1> <h1>Today it is {{ weather }}</h1> my urls.py located in myproject/mystuff/urls.py looks like this: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^$', views.myview, name='myview'), ] finally, I also have a 2nd urls.py for django rest framework with a urlpatterns[] that holds: url(r'^myview$', TemplateView.as_view(template_name='myview.html'), name='home') Any help would be appreciated. -
Django ORM: Many to Many Self-Reference with Through Model
I have a many-to-many self-referencing relationship that includes a through model. Products are composed of other Products, including an amount (I.E a screw is made from iron rods). I made the through model, although I can't seem to access the 'amount' field in the through model: Model code: from django.db import models class Product(models.Model): name = models.CharField(max_length=200, unique=True) produced = models.IntegerField(default=0) speed = models.IntegerField() type = models.CharField(max_length=200) ingredients = models.ManyToManyField('self', through='RecipeComponent', symmetrical=False) def __str__(self): return self.name class RecipeComponent(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="item") ingredient = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="ingredient") amount = models.IntegerField() def __str__(self): return str(self.amount) + " of " + self.ingredient.name I've tried a number of other queries, but as you can see they seem to fail. I know I'm missing something but I can't put my finger on it. screw.ingredients.all() >>> <QuerySet [<Product: iron_rod>]> screw.ingredients.all()[0].amount >>> Traceback (most recent call last): >>> File "<input>", line 1, in <module> >>> AttributeError: 'Product' object has no attribute 'amount' -
" can't open file 'manage.py': [Errno 2] No such file or directory " Getting this error when i am trying to runserver localhost
whenever i try to runserver i get this error in Django. here is my shell commands: PS C:\Users\Prozzzz\Django_projects> Django-admin startproject Django_projects PS C:\Users\Prozzzz\Django_projects> python manage.py runserver C:\Users\Prozzzz\AppData\Local\Programs\Python\Python37-32\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory -
access to For Loop variable inside another For Loop (Django Template)
I try to acces into for loop variable "i" inside another for loop but don't work !: something like : {% for i in l %} {% for j in i %} {{ j }} {% endfor%} {% endfor %} l : list - Context Variable (like : l=[[1,2,3],[4,5,6]] ) -
Django ORM SELECT with join sql
I'm trying to get the data by doing a join with django ORM. But there is a problem as below. Models in django: class LawyerCounsel(models.Model): lawyer_idx = models.AutoField(primary_key=True) lawyer_name = models.CharField(max_length=50) lawyer_status = models.CharField(max_length=1) register_date = models.DateTimeField() lawyeridx = models.ForeignKey(CounselAnswer, to_field='lawyer_idx', unique='true', db_column="counsel_answer_idx", on_delete="models.DO_NOTHING") class Meta: managed = False db_table = 'lawyer' class CounselAnswer(models.Model): counsel_answer_idx = models.AutoField(primary_key=True) counsel_idx = models.IntegerField() lawyer_idx = models.IntegerField() counsel_answer_title = models.CharField(max_length=255) counsel_answer_contents = models.TextField() counsel_seleted = models.CharField(max_length=1) counsel_answer_agree = models.IntegerField() lawyer_ip = models.CharField(max_length=20, blank=True, null=True) counsel_answer_delay_time = models.IntegerField() register_date = models.DateTimeField() update_date = models.DateTimeField() class Meta: managed = False db_table = 'counsel_answer' I need to select from DB stats_data_test = LawyerCounsel.objects.filter(register_date=yearmonth).order_by("cnt") May I use django ORM to make this selection? (for example in SQL select looks like this) select * from ( select y.lawyer_name, DATE_FORMAT(y.register_date, '%%Y-%%m-%%d') as reg_date, (select count(counsel_answer_idx) from counsel_answer where lawyer_idx = y.lawyer_idx and DATE_FORMAT(register_date, '%%Y%%m') = '%s') as cnt, (select count(counsel_answer_idx) from counsel_answer where lawyer_idx = y.lawyer_idx and DATE_FORMAT(register_date, '%%Y%%m') = '%s' and week(register_date,5) - week(DATE_SUB(register_date,INTERVAL DAYOFMONTH(register_date)-1 DAY),5) = 1) as cnt1, (select count(counsel_answer_idx) from counsel_answer where lawyer_idx = y.lawyer_idx and DATE_FORMAT(register_date, '%%Y%%m') = '%s' and week(register_date,5) - week(DATE_SUB(register_date,INTERVAL DAYOFMONTH(register_date)-1 DAY),5) = 2) as cnt2, (select count(counsel_answer_idx) from counsel_answer where lawyer_idx … -
Can't refresh the page after form submission
I am building a comment system in a blog like Django project. There is a form at the end of each article (that works fine). I want to make it so that when the form is submitted, the page refreshes and the comment is visible. (Before I just linked to the front page of the blog, and the comments were saved and displayed) I try the code below, but the page is stuck in "loading", then displays a {{ ip_adress }} can't be reached, but nevertheless writes the DB. This is my views.py def view_article(request, id): try: article =get_object_or_404(Article, id=id) comments = CommentArticle.objects.filter(article_id=id) form = CommentForm(request.POST or None, initial={'article_id': id}) url = "submit_comment/" + str(id) if form.is_valid(): message = form.cleaned_data['message'] poster_name = form.cleaned_data['poster_name'] article_id = id return HttpResponseRedirect(reverse('refresh_article')) except Article.DoesNotExist: raise Http404 return render( request, 'blog/view_article.html', locals()) def refresh_article(request, id): url = 'view_article' + str(id) return HttpResponseRedirect(reverse(url)) Does anyone has any clue? Thanks ! -
is_staff field is not showing in Django admin
is_staff is defined as boolean field but its checkbox is not visible in the admin page. But is_admin is visible and it can be changed. I can't able to make changes to that field using views.py class Users(AbstractBaseUser, PermissionsMixin): objects = UserManager() mobile_no = models.IntegerField(_('MobNumber'), null=True, blank=True,unique=True) email = models.EmailField(_('Email'), max_length=75, null=False, blank=False) first_name = models.CharField(_('FirstName'), max_length=50, null=True, blank=True) last_name = models.CharField(_('LastName'), max_length=70, null=True, blank=True) role = models.CharField(_('Role'), max_length=70, null=True, blank=True) location = models.CharField(_('Location'), max_length=70, null=True, blank=True) date_time = models.DateTimeField(_('DateTime'), auto_now=True, null=True, blank=True) activated = models.BooleanField(_('Activated'), default=False) is_admin = models.BooleanField(_('is_admin'), default=False) is_staff = models.BooleanField(_('is_staff'), default=False) def __unicode__(self): return str(self.mobile_no) def __str__(self): return str(self.mobile_no) def get_full_name(self): return self.first_name + " " + self.last_name class Meta: ordering = ['-id'] @property def is_staff(self): return self.is_admin def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin USERNAME_FIELD = 'mobile_no' REQUIRED_FIELDS = ['role'] -
Django print data of radio button?
I printed my data within the text box as data = request.GET['information'] print(data) in views.py <form class="homepage" action = "{% url 'count' %}" > <textarea name="information" rows="8" cols="80"></textarea> <input type="submit" name="" value="Wordecounter"> </form> so basically it is returning the text from the text box but the question is if i used radio buttun and selected radio button on my browser then how could i print my data from views.py Thanku in advance -
Django: return reverse and return object at the same time
After submitting a form, I would like two things to happen: Form is reset (reload the form empty) /or redirected Return a file as attachment Now, I get the dialogue to download file, but form does not reset/re-load empty /nor redirected. I can amend get_success_url but then I do not get the download dialogue I have tried to insert success_url but no result. What is the solution for this? Simplified code below: urls.py urlpatterns = [ path('product/csv/', ProductFormView.get_csv, name='product-csv'), ] views.py class ProductFormView(FormView): form_class = ProductForm model = Product def form_valid(self, form): self.object = form.save() return super().form_valid(form) def get_success_url(self): return reverse('product-csv') def get_csv(request): csv = FileDB.objects.latest('id').csvfile response = HttpResponse(content_type='application/CSV') response.write(csv.ToString()) response['Content-Disposition'] = 'attachment; filename='f" {filename} + .csv" return response -
Django Oscar - email admin on order placed
I am trying to get django-oscar to send me an email everytime an order is placed. It sounds simple but I am struggling. I have tried a couple of methods but all failed... Is there an easy way? -
How to works with password change and profile update forms?
I've found some examples of this, but I want to know what the best use is for my case. Basically, I have a form for: changing the user password and updating the session hash (I think that's how PasswordChangeView works), and another form, to change user data such as username and country. I was trying to do this with several views returning to the same url, but I lost some control over the fields, and it still got a bit inconsistent, since it will only redirect to the same page on success, and I I want the user to always stay on the same page. Any tips for working with this? I think I can do this with functions quietly, but it would have a very bloated code, and I'm looking for a more "clean" alternative. ps: my views: class PasswordChangePage( SuccessMessageMixin, LoginRequiredMixin, auth_views.PasswordChangeView ): """ Change password and return redirect """ template_name = "users/registration/password_change.html" success_url = reverse_lazy("users:settings") success_message = "password changed" and class UserEditPage(LoginRequiredMixin, generic.View): def get(self, request, *args, **kwargs): template_name = "users/registration/update.html" form = ProfileUpdateForm(instance=request.user) context = {"form": form} return render(request, template_name, context) def post(self, request, *args, **kwargs): form = ProfileUpdateForm(request.POST, instance=request.user) if form.is_valid(): form.save() messages.add_message( request, messages.SUCCESS, … -
Gunicorn workers timing out after SSL install (Django, Nginx)
After a bit of a struggle to set up AWS Route53 IPv6 and my DSN (Ionos) I've managed to set up SSL in my Django blog app running with Gunicorn and nginx. I've used this tutorial Unfortunately, first it ran into the redirect loop error that I managed to fix but now it's 502 Bad Gateway and when I check the logs it looks like Gunicorn workers are alway timing out. I tried setting the timeout to 300s for both nginx and Gunicorn but it just means a longer wait for 502 error, nothing else changes. Here's the log: Mar 21 23:13:46 ip-172-31-35-104 systemd[1]: Started A high performance web server and a reverse proxy server. -- Subject: Unit nginx.service has finished start-up -- Defined-By: systemd -- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- Unit nginx.service has finished starting up. -- -- The start-up result is done. Mar 21 23:13:46 ip-172-31-35-104 sudo[2107]: pam_unix(sudo:session): session closed for user root Mar 21 23:14:19 ip-172-31-35-104 gunicorn[2055]: [2019-03-21 23:14:19 +0000] [2055] [CRITICAL] WORKER TIMEOUT (pid:2061) Mar 21 23:14:19 ip-172-31-35-104 gunicorn[2055]: [2019-03-21 23:14:19 +0000] [2061] [INFO] Worker exiting (pid: 2061) Mar 21 23:14:19 ip-172-31-35-104 gunicorn[2055]: base dir path /home/ubuntu/puchalatravel/puchalatravel Mar 21 23:14:19 ip-172-31-35-104 gunicorn[2055]: [2019-03-21 23:14:19 +0000] [2125] [INFO] … -
convert queryset into pure string only
I have some code that checks if two string matches and they do in the database, but when I query them using this code r = Usertasks.objects.all().filter(user=request.user).filter(randomURL=payment_id).values_list("TaskPostedToNetwork", flat=True) e = Usertasks.objects.all().filter(user=request.user).filter(randomURL=payment_id).values_list("PaymentConfirmed", flat=True) It returns <QuerySet [False]> <QuerySet ['yes']> My if loop that checks for the string is never ran because it doesnt return as a string but with the queryset around it, I guess if r == "False" and e == "yes": print("Works") How do I make it return just False yes -
Django: convert string to array
I have this string variable auxi_espec = '1, 3, 5, 7,' And I need to convert it to array in order to make a queryset where I filter using __in. (Possibly I think I'll also need to slice the last comma). -
Deploy on Heroku django app psycopg2.ProgrammingError: relation " tableName " does not exist
I'm deploying my django project on heroku and my db is on postgresql , however, when i open the app on heroku doesn't show me a particular template called "products.html". So , i checked the logs and it's showing me an error of psycopg2 and the relations im my models and views associated to that template . I makemigrations/migrate locally , updated the git repo , pushed to heroku and migrate it on heroku, but none of these things works . In addition , when i run heroku run manage.py migrate , it tells me there are no migrations to apply. No migrations to apply Can anyone suggest me something please? 2019-03-21T22:43:30.822852+00:00 app[web.1]: 10.51.203.60 - - [21/Mar/2019:22:43:30 +0000] "GET / HTTP/1.1" 404 77 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0" 2019-03-21T22:43:39.202942+00:00 app[web.1]: Internal Server Error: /petit/productos 2019-03-21T22:43:39.202960+00:00 app[web.1]: Traceback (most recent call last): 2019-03-21T22:43:39.202963+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute 2019-03-21T22:43:39.202964+00:00 app[web.1]: return self.cursor.execute(sql, params) 2019-03-21T22:43:39.202966+00:00 app[web.1]: psycopg2.ProgrammingError: relation "product" does not exist 2019-03-21T22:43:39.202968+00:00 app[web.1]: LINE 1: ..."product"."k_idcommerce", "product"."v_price" FROM "product" 2019-03-21T22:43:39.202969+00:00 app[web.1]: ^ 2019-03-21T22:43:39.202971+00:00 app[web.1]: 2019-03-21T22:43:39.202972+00:00 app[web.1]: 2019-03-21T22:43:39.202973+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2019-03-21T22:43:39.202974+00:00 app[web.1]: 2019-03-21T22:43:39.202976+00:00 app[web.1]: Traceback … -
Django admin panel won't render CSS
I have followed multiple guides and read many other answers about this problem (example: here, here, here, here, here, etc. ), but none of them help. Using nginx 1.15.5, Django 2.2.1, gunicorn 19.9.0, Python 3.6 Right now, my Django admin panel looks like this: my nginx config: nginx.conf error_log logs/error.log warn; events { } http { access_log logs/access.log combined; include default-site.conf; include myapp.conf; } myapp.conf server { # http://nginx.org/en/docs/http/ngx_http_log_module.html#access_log access_log logs/myapp/access.log combined; server_name myserver.com; listen 1234; # ignore favion messages location = /favicon.ico { access_log off; log_not_found off; } # path to socket for gunicorn location / { proxy_pass http://unix:/usr/local/bin/apps/myapp/myapp.sock; } # location for static files to serve; mostly the admin panel CSS files location /static/ { root /usr/local/bin/apps/myapp/; } } Gunicorn daemon start command (inside the myapp project directory): gunicorn webapp.wsgi \ --bind "unix:/usr/local/bin/apps/myapp/myapp.sock" \ --config "../server-conf/myserver.com/myapp/gunicorn_config.py" \ --pid "logs/gunicorn.pid" \ --access-logfile "logs/gunicorn.access.log" \ --error-logfile "logs/gunicorn.error.log" \ --log-file "logs/gunicorn.log" \ --name "gunicorn-myapp" \ --daemon Django settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') I already ran python manage.py collectstatic, the files are there, and have global read permissions: $ ll /usr/local/bin/apps/myapp/static/ total 12K drwxrwsr-x. 3 myusername myusergroup 4.0K Mar 21 14:57 . drwxrwsr-x. 10 myusername myusergroup 4.0K Mar 21 … -
how to access to specific value in nested dict of context, in Django 2 template?
I'd like to render a variable in a Django template, and this variable is inside a dict, in another dict. How could I do? Below an example. views.js> ....(view) dicIn = {'one': 1, 'two': 2} dicOut = { 'a': None, 'b': dicIn } context={ res: dicOut } return render_to_response('app/results.html', context) .... Here is what I'd like to do results.html> <ul class="list-group"> These are {{ context.res.b.two }} apples. </ul> Rendered as * These are 2 apples. Thank you in advance ^^ -
django-autocomplete-light not working with autocomplete.ModelSelect2Multiple
Following the tutorial when I create a model with a ManyToManyField: class Country(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Person(models.Model): visited_countries = models.ManyToManyField(Country) And then render a form using the ModelSelect2Multiple widget: widgets = { 'visited_countries': autocomplete.ModelSelect2Multiple( url='country-autocomplete') } The data that is submitted comes in as a single value as opposed to an array, so the Person object is never created on form save. Is there a way to have it come in as an array and appropriately create the ManyToMany relationship? -
How to remove put from a pre written view in django
I have the following view: class ReadClass(generics.RetrieveUpdateDestroyAPIView): queryset = MyCModel.objects.all() serializer_class = MySerializer def post(self, request, *args, **kwargs): ''' defined my post here''' I know retrieveupdatedestroyapiview doesn't have post in it. And I have created my own post in the view here and on the front end, I see both post and put! Is there any way to remove the put. Or is there any other way to do it better, I tried using ListCreateApi view. The problem with that is while it gives me the post functionality, it lists all the values, while I am looking for a specific pk. I cannot see any other generic view that gives me get and post functionality. -
how to create a view to update user data in Django?
I know that UpdateView exists, but I do not want it because I have to include the id in the url. I'm using FormView along with widget tweaks. But it does not seem to be working properly. Currently it looks like this: # view class UserEditPage(SuccessMessageMixin, LoginRequiredMixin, generic.FormView): template_name = "users/registration/update.html" form_class = ProfileUpdateForm success_url = reverse_lazy("users:settings") success_message = "sucess!" # form User = get_user_model() # custom user in users.User class ProfileUpdateForm(UserChangeForm): class Meta: model = User fields = ("username", "email", "country") # html {% load widget_tweaks%} <h1>update page</h1> <form action="." method="post"> {% csrf_token %} <span>username - current: {{request.user.username}}</span> {% render_field form.username %} <span>email - current: {{request.user.email}}</span> {% render_field form.email %} <span>country - current: {{request.user.country}}</span> {% render_field form.country %} <button type="submit">SEND</button> </form> I can update this data, I think there should be the current value of the field in value = "" in the inputs / fields. I was able to add default value for username and email, but not for country, because it simply does not work by placing value = request.user.country -
HttpResponse error django generic template
I am able to render class based view generic ListView template using parameter hard coded in views.py. class ResourceSearchView(generic.ListView): model = creations context_object_name = 'reviews' template_name = 'reviews.html' query = 'theory' # def get(self, request): # if request.GET.get('q'): # query = request.GET.get('q') queryset = creations.objects.filter(narrative__contains=query).order_by('-post_date') However, when parameter is sent via form by GET method (below), class ResourceSearchView(generic.ListView): model = creations context_object_name = 'reviews' template_name = 'reviews.html' query = 'theory' def get(self, request): if request.GET.get('q'): query = request.GET.get('q') queryset = creations.objects.filter(narrative__contains=query).order_by('-post_date') I receive this error The view creations.views.ResourceSearchView didn't return an HttpResponse object. It returned None instead. -
Python: Getting rid of nested for loops while accessing database (Models? View?)
I am trying to solve performance issues at a Django-based web site, with very little knowledge of Django and Python syntax. I seem to have correctly identified the problem. I also seem to know what to do next, but I can't get a grasp on the Python/Django syntax to make everything work. class Company(models.Model): name = models.CharField(max_length=100) bic = models.CharField(max_length=100, blank=True) def get_order_count(self): return self.orders.count() def get_order_sum(self): total_sum = 0 for contact in self.contacts.all(): for order in contact.orders.all(): total_sum += order.total return total_sum class Contact(models.Model): company = models.ForeignKey( Company, related_name="contacts", on_delete=models.DO_NOTHING) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, blank=True) def get_order_count(self): return self.orders.count() class Order(models.Model): order_number = models.CharField(max_length=100) company = models.ForeignKey(Company, related_name="orders", on_delete=models.DO_NOTHING) contact = models.ForeignKey(Contact, related_name="orders", on_delete=models.DO_NOTHING) total = models.DecimalField(max_digits=18, decimal_places=9) order_date = models.DateTimeField(null=True, blank=True) def __str__(self): return "%s" % self.order_number My hunch is that the performance problems are caused by the nested loop in get_order_sum. And my solution is quite clear: nested "fors" should be replaced by a simple command, that uses aggregation and utilizes the database's own efficient internal SQL functionality. So in my mind, the solution should look something like this: return self.contacts.all().orders.all().aggregate(Sum('total')) The problem is that I can't figure out how to properly write what I …