Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django modelManager - can not see instances/objects in View/listview - no erroer
iam new to django. Iam trying to display with a models.Manager only the published=True instances. In the terminal no error comes. What iam doing wrong? I have a feeling it has sth to do with my view. Any help would be highly appreciated. my code - models.py from django.db import models # Create your models here. class BlogPostManager(models.Manager): use_for_related_fields = True def freetosee(self, **kwargs): return self.filter(published=True, **kwargs) class Post(models.Model): NOT_RATED = 0 RATED_G = 1 RATED_PG = 2 RATED_R = 3 RATINGS =( (NOT_RATED, 'NR-Not Rated'), (RATED_G, 'G - General Audience'), (RATED_PG, 'Parental'), (RATED_R, 'Restriced'), ) title = models.CharField(max_length=140) body = models.TextField() published = models.BooleanField(default=False) rating = models.IntegerField( choices=RATINGS, default=NOT_RATED, ) objects = BlogPostManager() def __str__(self): return self.title views.py from django.shortcuts import render # Create your views here. from django.views.generic import DetailView, ListView from .models import Post class PostListView(ListView): model = Post context_object_name = 'posts' template_name = 'postlist.html' template {% extends "base.html" %} {% block content %} {% for post in posts.objects.freetosee %} {{ post.title }} - {{ post.body }} {% endfor %} {% endblock %} urls.py from django.urls import path, include from django.views.generic import TemplateView from .views import PostListView app_name = 'blog' urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('list/', … -
'contenttypes': None in MIGRATION_MODULES but "Table 'django_content_type' doesn't exist" error
I have a new project with django and I want to get ride of the auth_* and django_* tables. I want the applications listed in INSTALLED_APPS so I used MIGRATION_MODULES = { 'admin': None, 'auth': None, 'contenttypes': None, 'default': None, 'sessions': None, 'authtoken': None, } My next step is to makemigrations myapp and then run the migrate command, but at some point I get this error: django.db.utils.ProgrammingError: (1146, "Table 'django_content_type' doesn't exist") Is there something I'm missing or doing wrong? -
Lost connection to MySQLserver
I try to run my app django but I get this error super(Connection, self).__init__(*args, **kwargs2) django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'handshake: reading inital communication packet', syste m error: 10061") my databases is declared as DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sdms_tracker', 'USER': 'root', 'PASSWORD': 'fadma', 'HOST': 'localhost', 'PORT': '82', 'OPTIONS': {"init_command": "SET storage_engine=MyISAM"}, } } -
Django REST Framework saving ModelSerializers
I am trying to create model objects using the create action of a ModelSerializer, however it seems that the serializer does not call the related model's .save function. Is there any direct way to do so or do I have to explicitly call it for every model? -
Mocking some fixtures inside a test
I want to mock timezone.now in test AND in fixtures which test retrieve. def time_to_test(): return datetime(year=2019, month=4, day=30, hour=6, minute=2, second=3) I try: with patch('django.utils.timezone.now', side_effect=time_to_test): @pytest.mark.django_db def test_only_one(user_helpers, user): print(django.utils.timezone.now()) # Here is mocked timezone print(user_helpers.created_time) # Here is real time assert user_helpers.count == 4 and @patch('django.utils.timezone.now', side_effect=time_to_test): @pytest.mark.django_db def test_only_one(user_helpers, user): print(django.utils.timezone.now()) # Here is mocked timezone print(user_helpers.created_time) # Here is real time assert user_helpers.count == 4 Mocked value not applied in fixtures, because they called before start a test, but I would like have patched this fixtures in this test only. I don't want to create distinguish fixture or fabric for test. -
Hello I am using get_object_or_404 in django but not able to get result how I should fetch the objects from blog post database?
Here is my post_detail function, every time for valid objects it is not working . Views.py def post_details(request,year,month,day,post): post=get_object_or_404(Post,slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request,'blog/post_detail.html',{'post':post}) url pattern: url(r'^(?P<year>\d{4})/ (?P<month>\d{2})/ (?P<day>\d{2})/ (?P<post>[- \w]+)/$', views.post_details,name='post_detail'), I have used the get get absolute url method: def get_absolute_url(self): return reverse('post_detail',args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) Please help me how should I fetch the objects. -
Django: A common/global variable that is constructed on server start and destroyed on server exit
I'd like to use Django as a relay to another layer. When the user makes a request, a thrift client calls a function that goes to another software to retrieve the result. I understand the potential thread-safety issues, which is why there will be an object pool of clients based on Python's multiprocessing, and every user request will pop one, use it, and put it back. The object pool has to be initialized at the beginning of the program, and destroyed (hopefully cleanly) when the program exits (when the server is interrupted with SIGINT). The motivation to this question is to know how to do this in the correct way without hacks. The only way I found so far is the following prototype with global variables, given that the following is the views file with function based views: clients_pool = ClientsPool("127.0.0.1", 9090, size=64) # pool size def get_data(request): global clients_pool c = clients_pool.pop() res = c.get_data(request.body) clients_pool.release(c) return HttpResponse(res) def get_something(request): global clients_pool c = clients_pool.pop() res = c.get_something(request.body) clients_pool.release(c) return HttpResponse(res) Is this the correct way to do this? Or does Django offer a better mechanism to do this? -
How to serve Static and Media files in Azure blob with gunicorn and nginx
I'm trying to upload my assets to Azure blob, in my local it's working. collectstatic saving the static files in Azure blob only. But when i'm running via gunicorn it's saving in my local. I didn't add any configuration for static and media in nginx. nginx configuration: server { listen 8000; server_name x.x.x.x:8000; location / { include proxy_params; proxy_read_timeout 300s; proxy_connect_timeout 300s; proxy_pass http://unix/home/myproject/project.sock; } } -
Connect existing Redshift read-only database to django project
I am trying to connect my django app to a third database where I need to retrieve some datas. I will use this datatable on read-only. I have made these configurations: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'xxx', 'USER':'xxx', 'PASSWORD':'xxx', 'HOST':'xxx', 'PORT':'5432', }, 'histo':{ 'ENGINE':'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR,'db.sqlite3'), }, 'redshift': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'xxx', 'USER':'xxx', 'PASSWORD':'xxx', 'HOST':'xxx', 'PORT':'5439', } } DATABASE_ROUTERS = ['livedb.database_routers.redshiftrouter.Router'] And written this router: redshiftrouter.py class Router(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'redshift': return 'redshift' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'redshift': return 'redshift' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'redshift' or \ obj2._meta.app_label == 'redshift': return True return None def allow_migrate(self, db, app_label, model=None, **hints): if app_label == 'redshift': return False return None My problem is that when I am running manage.py migrate --database=redshift, I am having a migrationsschemamissing exception because the django_migrations.id has unsupported type 'serial'. However, I thought that thanks to my router I was avoiding the migration on this database. I read that other post was about the same subject, but none of them was giving an answer to that issue. Can you help me with this problem? Thank you -
checkbox not woring on django
when checkbox is checked, delete and checkbox counter button should appear like Chrome History if you check any visited page the header changes i also inlcluded this kind of part in my project but when i click first row of the table delete button appear but if i click second row it does not show <tbody> {% for item in items %} <th scope="row"><input type="checkbox" id="check" name="wpmm[]"></th> <td>{{ item.item_name }}</td> <td>{{ item.sku }}</td> <td>{{ item.quantity }}</td> {% endfor %} </tbody> here is the script var fnUpdateCount = function () { var generallen = $("input[name='wpmm[]']:checked").length; if (generallen > 0) { $("#general i .counter").text('(' + generallen + ')'); } else { $("#general i .counter").text(' '); } }; $("input:checkbox").on("change", function () { fnUpdateCount(); }); $('.select_all').change(function () { var checkthis = $(this); var checkboxes = $("input:checkbox"); if (checkthis.is(':checked')) { checkboxes.prop('checked', true); } else { checkboxes.prop('checked', false); } fnUpdateCount(); }); here is the code which should show when chechbox is checked <div class="row justify-content-between start-dash mb-4" id="general"> <div class="col-6"> <h4 class="text-left mt-4">Selected Items: <span class="counter"></span></h4> </div> </div> for this this code is used $('#general').hide(); $(function () { $('#check').on('change', function () { if ($('#check').prop('checked')) { $('#item_info').hide(); $('#general').show(); } else { $('#item_info').show(); $('#general').hide(); } }); }); -
How to query MS SQL Server from within Django view?
For my Django project, I need to query MS SQL Server database. I have the following script for that: conn = pyodbc.connect('DRIVER={ODBC Driver 11 for SQL Server};SERVER="some_server";DATABASE="some_database";UID="some_UID";PWD="some_pwd"') cursor = conn.cursor() table_names = (table_info.table_name for table_info in conn.cursor().tables()) for table_name in table_names: print(table_name) The script will work when run standalone. It will also work when run from within Django shell. However, if I convert it to a Django view: def query_database(request): conn = pyodbc.connect('DRIVER={ODBC Driver 11 for SQL Server};SERVER="some_server";DATABASE="some_database";UID="some_UID";PWD="some_pwd"') cursor = conn.cursor() table_names = (table_info.table_name for table_info in conn.cursor().tables()) for table_name in table_names: print(table_name) return HttpResponse('OK') and go to this view's URL, I will get (after a longer time): pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 11 for SQL Server]Unable to complete login process due to delay in opening server connection (0) (SQLDriverConnect)') I thought that maybe I need to include the database in settings.py, butthis is not the project's main database, only an external database to query once in a while. How can I fix this? -
Django generic_inlineformset_factory in template : retrieved id is None
I generate a generic_inlineformset_factory with - the model is the same as given in docs : tags = word.tags.all().values() tag_formset = TaggedItemFormSet(initial=tags) which produces the following example in template for one form : <td> <label for="id_glossary-taggeditem-content_type-object_id-0-tag" class="labeled">Tag 1</label> </td> <td> <input type="text" name="glossary-taggeditem-content_type-object_id-0-tag" value="75" maxlength="50" id="id_glossary-taggeditem-content_type-object_id-0-tag"> </td> But when I changed the value "75" to "755" for example, the returned form.clean_data is : {'tag': '755', 'id': None, 'DELETE': False} I don't understand what happened to my id ? Thanks -
Django App : Perform arithmetic operation on two fields in database and store result in third field in DB while adding data in form
I have One form in my application with different fields from which i need to subtracts value of one field from other and store result in third field on the fly in Database. Example i have 2 fields : 1. Cost of PR Basic & 2. Cost of PO Basic Need to calculate Delta : Cost of PO Basic - Cost of PR Basic. Delta is also field in database table. -
How to access the values of a list that is inside tasks.py via views.py while the list is filling and the task is not finished yet?
I have a simple function in views.py and i need to call a task in this function to do something and put the result in a list. So i need to read the first 10 of list values while list is filling by the task and it's not complete yet(or task is not finished yet). How can i do this? I use celery 4.3.0(rhubrab) and RabbitMQ 3.7.14 for task handling in django 2.1.7 Since more than one user may want to use website, therefore i think it's need to call a worker for each request so i try to use class based task but this is not recommended in celery documentation(although was not resolve my trouble again) and i use functional task. the view function and task function which i expected to work is as follows: views.py : from .tasks import fetch def search_result(request): if request.method == 'POST': my_task = fetch.delay(arg1, arg2) my_task_id = my_task.task_id while True: if len(fetch.MAIN_LIST) > 9 : initial = fetch.MAIN_LIST[0:10] return HttpResponse(temp.render({'initial' : initial}, request)) elif AsyncResult(my_task_id).ready(): initial = fetch.main_list.get() return HttpResponse(temp.render({'initial' : initial}, request)) else: time.sleep(1) tasks.py : @shared_task def fetch(larg1, arg2): main_list = [] # do something and get result main_list.append(result) # this … -
How do i query model managers in my function based views for single_page(detail.html)
I'm finding it difficult to query a custom django model manager in my function based detail view. How can i resolve this? I'm using django 2.2. in my models.py file, i have this code below, which works perfectly. Querying for the listview is working fine and when i query the detail view using get_object_or_404(Modelname, id), the detail views works too but when i try to query it using my custom model manager, i keep getting this error "movie_detail() got an unexpected keyword argument 'id'". i've also tried removing---> def get_absolute_url(self): return reverse('core:movie_detail', args=[self.id,]) from my movie model when querying the model manager, but am still get same error How can i resolve this? my models.py class MovieManager(models.Manager): def all_with_related_persons(self): qs = self.get_queryset() qs = qs.select_related('director') qs = qs.prefetch_related('writers', 'actors') return qs class Movie(models.Model): NOT_RATED = 0 RATED_G = 1 RATED_PG = 2 RATED_R = 3 RATINGS = ( (NOT_RATED, 'NR - Not Rated'), (RATED_G, 'G - General Audiences'), (RATED_PG, ' PG - Parental Guidance' 'Suggested'), (RATED_R, 'R - Restricted'), ) title = models.CharField(max_length=140) plot = models.TextField() year = models.PositiveIntegerField() rating = models.IntegerField(choices=RATINGS, default=NOT_RATED) runtime = models.PositiveIntegerField() website = models.URLField(blank=True) director = models.ForeignKey(to='Person', on_delete=models.SET_NULL, related_name="directed", null=True, blank=True) writer = models.ManyToManyField(to="Person", related_name="writing_credits", … -
Render the index.html from outter directory in Django
I am new in Django, please help to browse the index.html from above packages and render it as the url path.enter image description here -
How do you log in when using django-rest-knox?
Django-Rest-Knox provides a view to give you the Token to authenticate, but that view requires authentication: https://github.com/James1345/django-rest-knox/blob/05f218f1922999d1be76753076cf8af78f134e02/knox/views.py#L16 How is this intended to be used? -
DJANGO change_form_object_tools.html template with parameter that is not the id
I have a button that points to a url. At this point I have original.pk, but I want to pass object.country to the url. {% load i18n admin_urls %} {% block object-tools-items %} <li> <a href="www.sometext{% object.country %}.com ">{% trans "Country" %}</a></a> </li> {% endblock %} -
pg_config executable not found using django-redshift-backend
I am having trouble installing redshift on my django app. When I am running pip3 install django-redshift-backend I get the error pg_config executable not found. My version of pip is 9.0.1 and I don't know why I'm having this error. Can you help me on this? -
django rest framework dynamic schema serializer
I have a model which holds the schema of all other hybrid tables(which means some relational fields and some fields inside the JSON field) Eg. class DynamicSchema(models.Model): # Fields model_name = models.CharField(max_length=255,unique=True) slug = extension_fields.AutoSlugField(populate_from='model_name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) schema_data = JSONField(default=list) class Meta: ordering = ('-created',) def __unicode__(self): return u'%s' % self.slug def get_absolute_url(self): return reverse('api_dynamicschema_detail', args=(self.slug,)) def get_update_url(self): return reverse('api_dynamicschema_update', args=(self.slug,)) all other models like some fixed fields and one json field: class Customer(models.Model): # Fields name = models.CharField(max_length=255,unique=True) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) details = JSONField(default=dict) class Meta: ordering = ('-created',) def __unicode__(self): return u'%s' % self.slug def get_absolute_url(self): return reverse('api_customer_detail', args=(self.slug,)) def get_update_url(self): return reverse('api_customer_update', args=(self.slug,)) in Customer model I have a field details which is JSON type . in that json fields schema will be defined in DynamicSchema table how to define Serializer with dynamic fields from DynamicSchema to make API for example : in dynamic schema table: model_name= 'Customer' schema_data={first_name:'text',second_name:'text',age:'number'} ..... now my Customer API should give all fields as below with all operations like search sort filter ..etc Is there any way to create dynamic serializers according to dynamic schema table? … -
How to fix key-error : 'x-wp-totalpages' when using woocommerce api in django
I can not fetch total_pages in order to proceed with data afterwards The problem is in line: total_pages = int(r.headers['X-WP-TotalPages']) The traceback from command line is : Traceback (most recent call last): File "<console>", line 1, in <module> File "/var/www/vhosts/intranet.rodkok.gr/rodkok_inventory/intranet/views.py", line 731, in update_orders get_from_woocommerce_orders(eshop) File "/var/www/vhosts/intranet.rodkok.gr/rodkok_inventory/intranet/views.py", line 237, in get_from_woocommerce_orders total_pages = int(r.headers['X-WP-TotalPages']) File "/usr/local/lib/python2.7/dist-packages/requests/structures.py", line 54, in __getitem__ return self._store[key.lower()][1] KeyError: 'x-wp-totalpages' My view function is: def get_from_woocommerce_orders(eshop): wcapi = API( url=eshop.url, consumer_key=eshop.consumer_key, consumer_secret=eshop.consumer_secret, wp_api=True, version="wc/v2", query_string_auth=True, verify_ssl = True, timeout=10 ) yesterday = date.today() - timedelta(2) r=wcapi.get("orders?after="+str(yesterday)+"T00:00:00Z") total_pages = int(r.headers['X-WP-TotalPages']) Can anyone have an idea why I came up with error KeyError: 'x-wp-totalpages'? -
Django-Instance Group of User to Form
I want to instance a Group of User for Form When i instance user profile its work, but its not work to instance user groups There is my Code test = User.objects.get(id=id) second_form = UpdateAccountDetailForm(request.POST or None, instance=test.profile) third_form = GroupUserForm(request.POST or None, instance=test.groups) if request.method == 'POST': form = UsersForm(request.POST, instance=test) form2 = second_form form3 = third_form -
How fix the unregistered users and custom LOGIN_URL?
Just only for unregistered users I have this problem. Can you help me explain the mechanism to make the necessary adjustments in a correct way? The error tells me to set the LOGIN_URL: ... in Login return HttpResponseRedirect(settings.LOGIN_URL) NameError: name 'settings' is not defined I use Django version 2.1.1. The source code (is from a tutorial about create a chat, this is part of view.py): from django.http import HttpResponse, HttpResponseRedirect, JsonResponse ... def Login(request): next = request.GET.get('next', '/home/') if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) #WelcomeUser(user) return HttpResponseRedirect(next) else: return HttpResponse("Account is not active at the moment.") else: return HttpResponseRedirect(settings.LOGIN_URL) return render(request, "mychat/login.html", {'next': next}) The url.py : from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.Login, name='login'), url(r'^login/$', views.Login, name='login'), url(r'^logout/$', views.Logout, name='logout'), url(r'^home/$', views.Home, name='home'), url(r'^post/$', views.Post, name='post'), url(r'^messages/$', views.Messages, name='messages'), ] def __unicode__(self): return self.message I read the documentation but this is for login area and I don't understand how this working between default settings and custom one : -
Django read the same CBV for different urls
I'm using TamplateView in my views so that when a user is logged in, it will be redirect to his home page. I have two apps: app_manager(responsible for login and sign up) and app_user where we can found all the functionalities of the user. app_manager.views: return HttpResponseRedirect(reverse("app_user:switcher_user", args=(slugify(username_instance),))) app_user.views: def switcher_user(request, username): print(username) qs = User.objects.filter(username=username) print(qs) if not qs.exists(): print("user not found") return HttpResponseRedirect(reverse('app_user:access_denied')) else: print("user already exists") return user_index.as_view()(request) class user_index(LoginRequiredMixin,TemplateView): print("this is from user_index") template_name = "app_user/user_index.html" model = User context_object_name = 'user' class ProfilView(LoginRequiredMixin,TemplateView): template_name = "app_user/user_profil.html" class GroupsView(LoginRequiredMixin,ListView): template_name = "app_user/user_groups.html" app_user.urls: app_name ="app_user" urlpatterns = [ re_path(r'^(?P<username>[\w.@+-]+)/', views.switcher_user, name='switcher_user'), re_path(r'^(?P<username>[\w.@+-]+)/profil', views.ProfilView.as_view(), name='user_profil'), re_path(r'^(?P<username>[\w.@+-]+)/groups', views.GroupsView.as_view(), name='user_groups'), In my app_user application, I have a template folder where we can find all the html page for this type of user. In my base.html: <li> <a href="{% url 'app_user:user_profil' username=user.username %}">Profil</a></li> <li> <a href="{% url 'app_user:user_groups' username=user.username %}">Groups</a></li> The problem here is, when I click on Profil or Groups to go to the profil page or the groups page, I get the correct url in the browser address bar but the wrong html file. It always read the same view which is switcher_user and then user_index and bring … -
Confluent-Kafka Python : How to list all topics pragmatically?
I have a kafka broker running in my local system. To communicate with the broken using my Django based web application I am using confluent-kafka wrapper. However by browsing through the admin api, I could not find out any api for listing kafka topics. (The topics are created pragmatically and are dynamic). Is there any way I could list them within my program? The requirement is that, if my worker reboots all assigned consumers listening to those topics will have to be re-initialized so I want to loop to all the topics and assign a consumer to each.